blob: f4210e7b02ea8312125bb4167d2526f8430109d4 [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
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000145void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147}
148
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151 return false;
152}
153
154const Type *SCEVCouldNotCompute::getType() const {
155 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
156 return 0;
157}
158
159bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
160 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
161 return false;
162}
163
Dan Gohman9bc642f2009-06-24 04:48:43 +0000164const SCEV *
165SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
166 const SCEV *Sym,
167 const SCEV *Conc,
168 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 return this;
170}
171
Dan Gohman13058cc2009-04-21 00:47:46 +0000172void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 OS << "***COULDNOTCOMPUTE***";
174}
175
176bool SCEVCouldNotCompute::classof(const SCEV *S) {
177 return S->getSCEVType() == scCouldNotCompute;
178}
179
Owen Andersonecd0cd72009-06-22 21:39:50 +0000180const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000181 FoldingSetNodeID ID;
182 ID.AddInteger(scConstant);
183 ID.AddPointer(V);
184 void *IP = 0;
185 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
186 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
187 new (S) SCEVConstant(V);
188 UniqueSCEVs.InsertNode(S, IP);
189 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190}
191
Owen Andersonecd0cd72009-06-22 21:39:50 +0000192const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000193 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194}
195
Owen Andersonecd0cd72009-06-22 21:39:50 +0000196const SCEV*
Dan Gohman8fd520a2009-06-15 22:12:54 +0000197ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
198 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
199}
200
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000201void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
202 ID.AddInteger(scConstant);
203 ID.AddPointer(V);
204}
205
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206const Type *SCEVConstant::getType() const { return V->getType(); }
207
Dan Gohman13058cc2009-04-21 00:47:46 +0000208void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 WriteAsOperand(OS, V, false);
210}
211
Dan Gohman2a381532009-04-21 01:25:57 +0000212SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Andersonb70139d2009-06-22 21:57:23 +0000213 const SCEV* op, const Type *ty)
214 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman2a381532009-04-21 01:25:57 +0000215
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000216void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
217 ID.AddInteger(getSCEVType());
218 ID.AddPointer(Op);
219 ID.AddPointer(Ty);
220}
221
Dan Gohman2a381532009-04-21 01:25:57 +0000222bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
223 return Op->dominates(BB, DT);
224}
225
Owen Andersonb70139d2009-06-22 21:57:23 +0000226SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
227 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000228 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
229 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231}
232
Dan Gohman13058cc2009-04-21 00:47:46 +0000233void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000234 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235}
236
Owen Andersonb70139d2009-06-22 21:57:23 +0000237SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
238 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000239 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
240 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242}
243
Dan Gohman13058cc2009-04-21 00:47:46 +0000244void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000245 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246}
247
Owen Andersonb70139d2009-06-22 21:57:23 +0000248SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
249 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000250 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
251 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253}
254
Dan Gohman13058cc2009-04-21 00:47:46 +0000255void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000256 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257}
258
Dan Gohman13058cc2009-04-21 00:47:46 +0000259void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
261 const char *OpStr = getOperationStr();
262 OS << "(" << *Operands[0];
263 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
264 OS << OpStr << *Operands[i];
265 OS << ")";
266}
267
Dan Gohman9bc642f2009-06-24 04:48:43 +0000268const SCEV *
269SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
270 const SCEV *Sym,
271 const SCEV *Conc,
272 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000274 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000275 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000277 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 NewOps.reserve(getNumOperands());
279 for (unsigned j = 0; j != i; ++j)
280 NewOps.push_back(getOperand(j));
281 NewOps.push_back(H);
282 for (++i; i != e; ++i)
283 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000284 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285
286 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000287 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000289 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000290 else if (isa<SCEVSMaxExpr>(this))
291 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000292 else if (isa<SCEVUMaxExpr>(this))
293 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 else
295 assert(0 && "Unknown commutative expr!");
296 }
297 }
298 return this;
299}
300
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000301void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
302 ID.AddInteger(getSCEVType());
303 ID.AddInteger(Operands.size());
304 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
305 ID.AddPointer(Operands[i]);
306}
307
Dan Gohman72a8a022009-05-07 14:00:19 +0000308bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000309 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
310 if (!getOperand(i)->dominates(BB, DT))
311 return false;
312 }
313 return true;
314}
315
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000316void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
317 ID.AddInteger(scUDivExpr);
318 ID.AddPointer(LHS);
319 ID.AddPointer(RHS);
320}
321
Evan Cheng98c073b2009-02-17 00:13:06 +0000322bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
323 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
324}
325
Dan Gohman13058cc2009-04-21 00:47:46 +0000326void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000327 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328}
329
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000330const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000331 // In most cases the types of LHS and RHS will be the same, but in some
332 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
333 // depend on the type for correctness, but handling types carefully can
334 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
335 // a pointer type than the RHS, so use the RHS' type here.
336 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337}
338
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000339void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
340 ID.AddInteger(scAddRecExpr);
341 ID.AddInteger(Operands.size());
342 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
343 ID.AddPointer(Operands[i]);
344 ID.AddPointer(L);
345}
346
Dan Gohman9bc642f2009-06-24 04:48:43 +0000347const SCEV *
348SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
349 const SCEV *Conc,
350 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000352 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000353 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000355 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 NewOps.reserve(getNumOperands());
357 for (unsigned j = 0; j != i; ++j)
358 NewOps.push_back(getOperand(j));
359 NewOps.push_back(H);
360 for (++i; i != e; ++i)
361 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000362 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
Dan Gohman89f85052007-10-22 18:31:58 +0000364 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 }
366 }
367 return this;
368}
369
370
371bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000372 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000373 if (!QueryLoop)
374 return false;
375
376 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
377 if (QueryLoop->contains(L->getHeader()))
378 return false;
379
380 // This recurrence is variant w.r.t. QueryLoop if any of its operands
381 // are variant.
382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
383 if (!getOperand(i)->isLoopInvariant(QueryLoop))
384 return false;
385
386 // Otherwise it's loop-invariant.
387 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388}
389
390
Dan Gohman13058cc2009-04-21 00:47:46 +0000391void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
397
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000398void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
399 ID.AddInteger(scUnknown);
400 ID.AddPointer(V);
401}
402
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
404 // All non-instruction values are loop invariant. All instructions are loop
405 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000406 // Instructions are never considered invariant in the function body
407 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000409 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 return true;
411}
412
Evan Cheng98c073b2009-02-17 00:13:06 +0000413bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
416 return true;
417}
418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419const Type *SCEVUnknown::getType() const {
420 return V->getType();
421}
422
Dan Gohman13058cc2009-04-21 00:47:46 +0000423void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 WriteAsOperand(OS, V, false);
425}
426
427//===----------------------------------------------------------------------===//
428// SCEV Utilities
429//===----------------------------------------------------------------------===//
430
431namespace {
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
434 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
436 LoopInfo *LI;
437 public:
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
439
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
444
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
448
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
453
Dan Gohmand0c01232009-05-19 02:15:55 +0000454 // Order pointer values after integer values. This helps SCEVExpander
455 // form GEPs.
456 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
457 return false;
458 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
459 return true;
460
Dan Gohman5d486452009-05-07 14:39:04 +0000461 // Compare getValueID values.
462 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
463 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
464
465 // Sort arguments by their position.
466 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
467 const Argument *RA = cast<Argument>(RU->getValue());
468 return LA->getArgNo() < RA->getArgNo();
469 }
470
471 // For instructions, compare their loop depth, and their opcode.
472 // This is pretty loose.
473 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
474 Instruction *RV = cast<Instruction>(RU->getValue());
475
476 // Compare loop depths.
477 if (LI->getLoopDepth(LV->getParent()) !=
478 LI->getLoopDepth(RV->getParent()))
479 return LI->getLoopDepth(LV->getParent()) <
480 LI->getLoopDepth(RV->getParent());
481
482 // Compare opcodes.
483 if (LV->getOpcode() != RV->getOpcode())
484 return LV->getOpcode() < RV->getOpcode();
485
486 // Compare the number of operands.
487 if (LV->getNumOperands() != RV->getNumOperands())
488 return LV->getNumOperands() < RV->getNumOperands();
489 }
490
491 return false;
492 }
493
Dan Gohman56fc8f12009-06-14 22:51:25 +0000494 // Compare constant values.
495 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
496 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
497 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
498 }
499
500 // Compare addrec loop depths.
501 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
502 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
503 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
504 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
505 }
Dan Gohman5d486452009-05-07 14:39:04 +0000506
507 // Lexicographically compare n-ary expressions.
508 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
509 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
510 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
511 if (i >= RC->getNumOperands())
512 return false;
513 if (operator()(LC->getOperand(i), RC->getOperand(i)))
514 return true;
515 if (operator()(RC->getOperand(i), LC->getOperand(i)))
516 return false;
517 }
518 return LC->getNumOperands() < RC->getNumOperands();
519 }
520
Dan Gohman6e10db12009-05-07 19:23:21 +0000521 // Lexicographically compare udiv expressions.
522 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
523 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
524 if (operator()(LC->getLHS(), RC->getLHS()))
525 return true;
526 if (operator()(RC->getLHS(), LC->getLHS()))
527 return false;
528 if (operator()(LC->getRHS(), RC->getRHS()))
529 return true;
530 if (operator()(RC->getRHS(), LC->getRHS()))
531 return false;
532 return false;
533 }
534
Dan Gohman5d486452009-05-07 14:39:04 +0000535 // Compare cast expressions by operand.
536 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
537 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
538 return operator()(LC->getOperand(), RC->getOperand());
539 }
540
541 assert(0 && "Unknown SCEV kind!");
542 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 }
544 };
545}
546
547/// GroupByComplexity - Given a list of SCEV objects, order them by their
548/// complexity, and group objects of the same complexity together by value.
549/// When this routine is finished, we know that any duplicates in the vector are
550/// consecutive and that complexity is monotonically increasing.
551///
552/// Note that we go take special precautions to ensure that we get determinstic
553/// results from this routine. In other words, we don't want the results of
554/// this to depend on where the addresses of various SCEV objects happened to
555/// land in memory.
556///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000557static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000558 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 if (Ops.size() < 2) return; // Noop
560 if (Ops.size() == 2) {
561 // This is the common case, which also happens to be trivially simple.
562 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000563 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 std::swap(Ops[0], Ops[1]);
565 return;
566 }
567
568 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000569 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570
571 // Now that we are sorted by complexity, group elements of the same
572 // complexity. Note that this is, at worst, N^2, but the vector is likely to
573 // be extremely short in practice. Note that we take this approach because we
574 // do not want to depend on the addresses of the objects we are grouping.
575 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000576 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 unsigned Complexity = S->getSCEVType();
578
579 // If there are any objects of the same complexity and same value as this
580 // one, group them.
581 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
582 if (Ops[j] == S) { // Found a duplicate.
583 // Move it to immediately after i'th element.
584 std::swap(Ops[i+1], Ops[j]);
585 ++i; // no need to rescan it.
586 if (i == e-2) return; // Done!
587 }
588 }
589 }
590}
591
592
593
594//===----------------------------------------------------------------------===//
595// Simple SCEV method implementations
596//===----------------------------------------------------------------------===//
597
Eli Friedman7489ec92008-08-04 23:49:06 +0000598/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000599/// Assume, K > 0.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000600static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000601 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000602 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000603 // Handle the simplest case efficiently.
604 if (K == 1)
605 return SE.getTruncateOrZeroExtend(It, ResultTy);
606
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000607 // We are using the following formula for BC(It, K):
608 //
609 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
610 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000611 // Suppose, W is the bitwidth of the return value. We must be prepared for
612 // overflow. Hence, we must assure that the result of our computation is
613 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
614 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000615 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000616 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000617 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000618 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
619 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000620 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000621 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000622 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000623 // This formula is trivially equivalent to the previous formula. However,
624 // this formula can be implemented much more efficiently. The trick is that
625 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
626 // arithmetic. To do exact division in modular arithmetic, all we have
627 // to do is multiply by the inverse. Therefore, this step can be done at
628 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000629 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000630 // The next issue is how to safely do the division by 2^T. The way this
631 // is done is by doing the multiplication step at a width of at least W + T
632 // bits. This way, the bottom W+T bits of the product are accurate. Then,
633 // when we perform the division by 2^T (which is equivalent to a right shift
634 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
635 // truncated out after the division by 2^T.
636 //
637 // In comparison to just directly using the first formula, this technique
638 // is much more efficient; using the first formula requires W * K bits,
639 // but this formula less than W + K bits. Also, the first formula requires
640 // a division step, whereas this formula only requires multiplies and shifts.
641 //
642 // It doesn't matter whether the subtraction step is done in the calculation
643 // width or the input iteration count's width; if the subtraction overflows,
644 // the result must be zero anyway. We prefer here to do it in the width of
645 // the induction variable because it helps a lot for certain cases; CodeGen
646 // isn't smart enough to ignore the overflow, which leads to much less
647 // efficient code if the width of the subtraction is wider than the native
648 // register width.
649 //
650 // (It's possible to not widen at all by pulling out factors of 2 before
651 // the multiplication; for example, K=2 can be calculated as
652 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
653 // extra arithmetic, so it's not an obvious win, and it gets
654 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000655
Eli Friedman7489ec92008-08-04 23:49:06 +0000656 // Protection from insane SCEVs; this bound is conservative,
657 // but it probably doesn't matter.
658 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000659 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000660
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000661 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000662
Eli Friedman7489ec92008-08-04 23:49:06 +0000663 // Calculate K! / 2^T and T; we divide out the factors of two before
664 // multiplying for calculating K! / 2^T to avoid overflow.
665 // Other overflow doesn't matter because we only care about the bottom
666 // W bits of the result.
667 APInt OddFactorial(W, 1);
668 unsigned T = 1;
669 for (unsigned i = 3; i <= K; ++i) {
670 APInt Mult(W, i);
671 unsigned TwoFactors = Mult.countTrailingZeros();
672 T += TwoFactors;
673 Mult = Mult.lshr(TwoFactors);
674 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000676
Eli Friedman7489ec92008-08-04 23:49:06 +0000677 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000678 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000679
680 // Calcuate 2^T, at width T+W.
681 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
682
683 // Calculate the multiplicative inverse of K! / 2^T;
684 // this multiplication factor will perform the exact division by
685 // K! / 2^T.
686 APInt Mod = APInt::getSignedMinValue(W+1);
687 APInt MultiplyFactor = OddFactorial.zext(W+1);
688 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
689 MultiplyFactor = MultiplyFactor.trunc(W);
690
691 // Calculate the product, at width T+W
692 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Andersonecd0cd72009-06-22 21:39:50 +0000693 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000694 for (unsigned i = 1; i != K; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000695 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000696 Dividend = SE.getMulExpr(Dividend,
697 SE.getTruncateOrZeroExtend(S, CalculationTy));
698 }
699
700 // Divide by 2^T
Owen Andersonecd0cd72009-06-22 21:39:50 +0000701 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000702
703 // Truncate the result, and divide by K! / 2^T.
704
705 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
706 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707}
708
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709/// evaluateAtIteration - Return the value of this chain of recurrences at
710/// the specified iteration number. We can evaluate this recurrence by
711/// multiplying each element in the chain by the binomial coefficient
712/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
713///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000714/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000716/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000718const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman89f85052007-10-22 18:31:58 +0000719 ScalarEvolution &SE) const {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000720 const SCEV* Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000722 // The computation is correct in the face of overflow provided that the
723 // multiplication is performed _after_ the evaluation of the binomial
724 // coefficient.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000725 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000726 if (isa<SCEVCouldNotCompute>(Coeff))
727 return Coeff;
728
729 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 }
731 return Result;
732}
733
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734//===----------------------------------------------------------------------===//
735// SCEV Expression folder implementations
736//===----------------------------------------------------------------------===//
737
Owen Andersonecd0cd72009-06-22 21:39:50 +0000738const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000739 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000740 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000741 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000742 assert(isSCEVable(Ty) &&
743 "This is not a conversion to a SCEVable type!");
744 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000745
Dan Gohmanc76b5452009-05-04 22:02:23 +0000746 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000747 return getConstant(
748 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749
Dan Gohman1a5c4992009-04-22 16:20:48 +0000750 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000751 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000752 return getTruncateExpr(ST->getOperand(), Ty);
753
Nick Lewycky37d04642009-04-23 05:15:08 +0000754 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000755 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000756 return getTruncateOrSignExtend(SS->getOperand(), Ty);
757
758 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000759 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000760 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
761
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000762 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000763 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000764 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000766 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
767 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 }
769
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000770 FoldingSetNodeID ID;
771 ID.AddInteger(scTruncate);
772 ID.AddPointer(Op);
773 ID.AddPointer(Ty);
774 void *IP = 0;
775 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
776 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
777 new (S) SCEVTruncateExpr(Op, Ty);
778 UniqueSCEVs.InsertNode(S, IP);
779 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780}
781
Owen Andersonecd0cd72009-06-22 21:39:50 +0000782const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000783 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000784 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000785 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000786 assert(isSCEVable(Ty) &&
787 "This is not a conversion to a SCEVable type!");
788 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000789
Dan Gohmanc76b5452009-05-04 22:02:23 +0000790 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000791 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000792 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
793 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000794 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000795 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796
Dan Gohman1a5c4992009-04-22 16:20:48 +0000797 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000798 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000799 return getZeroExtendExpr(SZ->getOperand(), Ty);
800
Dan Gohmana9dba962009-04-27 20:16:15 +0000801 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000803 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000805 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000806 if (AR->isAffine()) {
807 // Check whether the backedge-taken count is SCEVCouldNotCompute.
808 // Note that this serves two purposes: It filters out loops that are
809 // simply not analyzable, and it covers the case where this code is
810 // being called from within backedge-taken count analysis, such that
811 // attempting to ask for the backedge-taken count would likely result
812 // in infinite recursion. In the later case, the analysis code will
813 // cope with a conservative value, and it will take care to purge
814 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000815 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000816 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000817 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000818 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000819 const SCEV* Start = AR->getStart();
820 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000821
822 // Check whether the backedge-taken count can be losslessly casted to
823 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000824 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000825 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000826 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000827 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
828 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000829 const Type *WideTy =
830 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000831 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000832 const SCEV* ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000833 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000834 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000835 const SCEV* Add = getAddExpr(Start, ZMul);
836 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000837 getAddExpr(getZeroExtendExpr(Start, WideTy),
838 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
839 getZeroExtendExpr(Step, WideTy)));
840 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000841 // Return the expression with the addrec on the outside.
842 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
843 getZeroExtendExpr(Step, Ty),
844 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000845
846 // Similar to above, only this time treat the step value as signed.
847 // This covers loops that count down.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000848 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000849 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000850 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000851 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000852 OperandExtendedAdd =
853 getAddExpr(getZeroExtendExpr(Start, WideTy),
854 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
855 getSignExtendExpr(Step, WideTy)));
856 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000857 // Return the expression with the addrec on the outside.
858 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
859 getSignExtendExpr(Step, Ty),
860 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000861 }
862 }
863 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000865 FoldingSetNodeID ID;
866 ID.AddInteger(scZeroExtend);
867 ID.AddPointer(Op);
868 ID.AddPointer(Ty);
869 void *IP = 0;
870 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
871 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
872 new (S) SCEVZeroExtendExpr(Op, Ty);
873 UniqueSCEVs.InsertNode(S, IP);
874 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875}
876
Owen Andersonecd0cd72009-06-22 21:39:50 +0000877const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000878 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000879 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000880 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000881 assert(isSCEVable(Ty) &&
882 "This is not a conversion to a SCEVable type!");
883 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000884
Dan Gohmanc76b5452009-05-04 22:02:23 +0000885 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000886 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000887 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
888 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000889 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000890 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891
Dan Gohman1a5c4992009-04-22 16:20:48 +0000892 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000893 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000894 return getSignExtendExpr(SS->getOperand(), Ty);
895
Dan Gohmana9dba962009-04-27 20:16:15 +0000896 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000898 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000900 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000901 if (AR->isAffine()) {
902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000910 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000912 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000913 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000914 const SCEV* Start = AR->getStart();
915 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000916
917 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000918 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000919 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000920 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000921 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000922 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
923 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000924 const Type *WideTy =
925 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000926 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000927 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000928 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000929 getTruncateOrSignExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000930 const SCEV* Add = getAddExpr(Start, SMul);
931 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000932 getAddExpr(getSignExtendExpr(Start, WideTy),
933 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
934 getSignExtendExpr(Step, WideTy)));
935 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000936 // Return the expression with the addrec on the outside.
937 return getAddRecExpr(getSignExtendExpr(Start, Ty),
938 getSignExtendExpr(Step, Ty),
939 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000940 }
941 }
942 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000944 FoldingSetNodeID ID;
945 ID.AddInteger(scSignExtend);
946 ID.AddPointer(Op);
947 ID.AddPointer(Ty);
948 void *IP = 0;
949 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
950 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
951 new (S) SCEVSignExtendExpr(Op, Ty);
952 UniqueSCEVs.InsertNode(S, IP);
953 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954}
955
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000956/// getAnyExtendExpr - Return a SCEV for the given operand extended with
957/// unspecified bits out to the given type.
958///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000959const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000960 const Type *Ty) {
961 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
962 "This is not an extending conversion!");
963 assert(isSCEVable(Ty) &&
964 "This is not a conversion to a SCEVable type!");
965 Ty = getEffectiveSCEVType(Ty);
966
967 // Sign-extend negative constants.
968 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
969 if (SC->getValue()->getValue().isNegative())
970 return getSignExtendExpr(Op, Ty);
971
972 // Peel off a truncate cast.
973 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000974 const SCEV* NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000975 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
976 return getAnyExtendExpr(NewOp, Ty);
977 return getTruncateOrNoop(NewOp, Ty);
978 }
979
980 // Next try a zext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000981 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000982 if (!isa<SCEVZeroExtendExpr>(ZExt))
983 return ZExt;
984
985 // Next try a sext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000986 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000987 if (!isa<SCEVSignExtendExpr>(SExt))
988 return SExt;
989
990 // If the expression is obviously signed, use the sext cast value.
991 if (isa<SCEVSMaxExpr>(Op))
992 return SExt;
993
994 // Absent any other information, use the zext cast value.
995 return ZExt;
996}
997
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000998/// CollectAddOperandsWithScales - Process the given Ops list, which is
999/// a list of operands to be added under the given scale, update the given
1000/// map. This is a helper function for getAddRecExpr. As an example of
1001/// what it does, given a sequence of operands that would form an add
1002/// expression like this:
1003///
1004/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1005///
1006/// where A and B are constants, update the map with these values:
1007///
1008/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1009///
1010/// and add 13 + A*B*29 to AccumulatedConstant.
1011/// This will allow getAddRecExpr to produce this:
1012///
1013/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1014///
1015/// This form often exposes folding opportunities that are hidden in
1016/// the original operand list.
1017///
1018/// Return true iff it appears that any interesting folding opportunities
1019/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1020/// the common case where no interesting opportunities are present, and
1021/// is also used as a check to avoid infinite recursion.
1022///
1023static bool
Owen Andersonecd0cd72009-06-22 21:39:50 +00001024CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
1025 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001026 APInt &AccumulatedConstant,
Owen Andersonecd0cd72009-06-22 21:39:50 +00001027 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001028 const APInt &Scale,
1029 ScalarEvolution &SE) {
1030 bool Interesting = false;
1031
1032 // Iterate over the add operands.
1033 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1034 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1035 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1036 APInt NewScale =
1037 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1038 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1039 // A multiplication of a constant with another add; recurse.
1040 Interesting |=
1041 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1042 cast<SCEVAddExpr>(Mul->getOperand(1))
1043 ->getOperands(),
1044 NewScale, SE);
1045 } else {
1046 // A multiplication of a constant with some other value. Update
1047 // the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001048 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1049 const SCEV* Key = SE.getMulExpr(MulOps);
1050 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001051 M.insert(std::make_pair(Key, APInt()));
1052 if (Pair.second) {
1053 Pair.first->second = NewScale;
1054 NewOps.push_back(Pair.first->first);
1055 } else {
1056 Pair.first->second += NewScale;
1057 // The map already had an entry for this value, which may indicate
1058 // a folding opportunity.
1059 Interesting = true;
1060 }
1061 }
1062 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1063 // Pull a buried constant out to the outside.
1064 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1065 Interesting = true;
1066 AccumulatedConstant += Scale * C->getValue()->getValue();
1067 } else {
1068 // An ordinary operand. Update the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001069 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001070 M.insert(std::make_pair(Ops[i], APInt()));
1071 if (Pair.second) {
1072 Pair.first->second = Scale;
1073 NewOps.push_back(Pair.first->first);
1074 } else {
1075 Pair.first->second += Scale;
1076 // The map already had an entry for this value, which may indicate
1077 // a folding opportunity.
1078 Interesting = true;
1079 }
1080 }
1081 }
1082
1083 return Interesting;
1084}
1085
1086namespace {
1087 struct APIntCompare {
1088 bool operator()(const APInt &LHS, const APInt &RHS) const {
1089 return LHS.ult(RHS);
1090 }
1091 };
1092}
1093
Dan Gohmanc8a29272009-05-24 23:45:28 +00001094/// getAddExpr - Get a canonical add expression, or something simpler if
1095/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001096const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 assert(!Ops.empty() && "Cannot get empty add!");
1098 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001099#ifndef NDEBUG
1100 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1101 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1102 getEffectiveSCEVType(Ops[0]->getType()) &&
1103 "SCEVAddExpr operand types don't match!");
1104#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105
1106 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001107 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108
1109 // If there are any constants, fold them together.
1110 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001111 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112 ++Idx;
1113 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001114 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001116 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1117 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001118 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001119 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001120 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 }
1122
1123 // If we are left with a constant zero being added, strip it off.
1124 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1125 Ops.erase(Ops.begin());
1126 --Idx;
1127 }
1128 }
1129
1130 if (Ops.size() == 1) return Ops[0];
1131
1132 // Okay, check to see if the same value occurs in the operand list twice. If
1133 // so, merge them together into an multiply expression. Since we sorted the
1134 // list, these values are required to be adjacent.
1135 const Type *Ty = Ops[0]->getType();
1136 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1137 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1138 // Found a match, merge the two values into a multiply, and add any
1139 // remaining values to the result.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001140 const SCEV* Two = getIntegerSCEV(2, Ty);
1141 const SCEV* Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 if (Ops.size() == 2)
1143 return Mul;
1144 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1145 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001146 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 }
1148
Dan Gohman45b3b542009-05-08 21:03:19 +00001149 // Check for truncates. If all the operands are truncated from the same
1150 // type, see if factoring out the truncate would permit the result to be
1151 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1152 // if the contents of the resulting outer trunc fold to something simple.
1153 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1154 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1155 const Type *DstType = Trunc->getType();
1156 const Type *SrcType = Trunc->getOperand()->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00001157 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001158 bool Ok = true;
1159 // Check all the operands to see if they can be represented in the
1160 // source type of the truncate.
1161 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1162 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1163 if (T->getOperand()->getType() != SrcType) {
1164 Ok = false;
1165 break;
1166 }
1167 LargeOps.push_back(T->getOperand());
1168 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1169 // This could be either sign or zero extension, but sign extension
1170 // is much more likely to be foldable here.
1171 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1172 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001173 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001174 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1175 if (const SCEVTruncateExpr *T =
1176 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1177 if (T->getOperand()->getType() != SrcType) {
1178 Ok = false;
1179 break;
1180 }
1181 LargeMulOps.push_back(T->getOperand());
1182 } else if (const SCEVConstant *C =
1183 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1184 // This could be either sign or zero extension, but sign extension
1185 // is much more likely to be foldable here.
1186 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1187 } else {
1188 Ok = false;
1189 break;
1190 }
1191 }
1192 if (Ok)
1193 LargeOps.push_back(getMulExpr(LargeMulOps));
1194 } else {
1195 Ok = false;
1196 break;
1197 }
1198 }
1199 if (Ok) {
1200 // Evaluate the expression in the larger type.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001201 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001202 // If it folds to something simple, use it. Otherwise, don't.
1203 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1204 return getTruncateExpr(Fold, DstType);
1205 }
1206 }
1207
1208 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1210 ++Idx;
1211
1212 // If there are add operands they would be next.
1213 if (Idx < Ops.size()) {
1214 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001215 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 // If we have an add, expand the add operands onto the end of the operands
1217 // list.
1218 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1219 Ops.erase(Ops.begin()+Idx);
1220 DeletedAdd = true;
1221 }
1222
1223 // If we deleted at least one add, we added operands to the end of the list,
1224 // and they are not necessarily sorted. Recurse to resort and resimplify
1225 // any operands we just aquired.
1226 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001227 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 }
1229
1230 // Skip over the add expression until we get to a multiply.
1231 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1232 ++Idx;
1233
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001234 // Check to see if there are any folding opportunities present with
1235 // operands multiplied by constant values.
1236 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1237 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001238 DenseMap<const SCEV*, APInt> M;
1239 SmallVector<const SCEV*, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001240 APInt AccumulatedConstant(BitWidth, 0);
1241 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1242 Ops, APInt(BitWidth, 1), *this)) {
1243 // Some interesting folding opportunity is present, so its worthwhile to
1244 // re-generate the operands list. Group the operands by constant scale,
1245 // to avoid multiplying by the same constant scale multiple times.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001246 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1247 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001248 E = NewOps.end(); I != E; ++I)
1249 MulOpLists[M.find(*I)->second].push_back(*I);
1250 // Re-generate the operands list.
1251 Ops.clear();
1252 if (AccumulatedConstant != 0)
1253 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001254 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1255 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001256 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001257 Ops.push_back(getMulExpr(getConstant(I->first),
1258 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001259 if (Ops.empty())
1260 return getIntegerSCEV(0, Ty);
1261 if (Ops.size() == 1)
1262 return Ops[0];
1263 return getAddExpr(Ops);
1264 }
1265 }
1266
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 // If we are adding something to a multiply expression, make sure the
1268 // something is not already an operand of the multiply. If so, merge it into
1269 // the multiply.
1270 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001271 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001273 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001275 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001277 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 if (Mul->getNumOperands() != 2) {
1279 // If the multiply has more than two operands, we must get the
1280 // Y*Z term.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001281 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001283 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001285 const SCEV* One = getIntegerSCEV(1, Ty);
1286 const SCEV* AddOne = getAddExpr(InnerMul, One);
1287 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 if (Ops.size() == 2) return OuterMul;
1289 if (AddOp < Idx) {
1290 Ops.erase(Ops.begin()+AddOp);
1291 Ops.erase(Ops.begin()+Idx-1);
1292 } else {
1293 Ops.erase(Ops.begin()+Idx);
1294 Ops.erase(Ops.begin()+AddOp-1);
1295 }
1296 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001297 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 }
1299
1300 // Check this multiply against other multiplies being added together.
1301 for (unsigned OtherMulIdx = Idx+1;
1302 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1303 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001304 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 // If MulOp occurs in OtherMul, we can fold the two multiplies
1306 // together.
1307 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1308 OMulOp != e; ++OMulOp)
1309 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1310 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001311 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001313 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1314 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001316 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001318 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001320 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1321 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001323 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001325 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1326 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 if (Ops.size() == 2) return OuterMul;
1328 Ops.erase(Ops.begin()+Idx);
1329 Ops.erase(Ops.begin()+OtherMulIdx-1);
1330 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001331 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 }
1333 }
1334 }
1335 }
1336
1337 // If there are any add recurrences in the operands list, see if any other
1338 // added values are loop invariant. If so, we can fold them into the
1339 // recurrence.
1340 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1341 ++Idx;
1342
1343 // Scan over all recurrences, trying to fold loop invariants into them.
1344 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1345 // Scan all of the other operands to this add and add them to the vector if
1346 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001347 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001348 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1350 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1351 LIOps.push_back(Ops[i]);
1352 Ops.erase(Ops.begin()+i);
1353 --i; --e;
1354 }
1355
1356 // If we found some loop invariants, fold them into the recurrence.
1357 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001358 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 LIOps.push_back(AddRec->getStart());
1360
Owen Andersonecd0cd72009-06-22 21:39:50 +00001361 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001362 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001363 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364
Owen Andersonecd0cd72009-06-22 21:39:50 +00001365 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366 // If all of the other operands were loop invariant, we are done.
1367 if (Ops.size() == 1) return NewRec;
1368
1369 // Otherwise, add the folded AddRec by the non-liv parts.
1370 for (unsigned i = 0;; ++i)
1371 if (Ops[i] == AddRec) {
1372 Ops[i] = NewRec;
1373 break;
1374 }
Dan Gohman89f85052007-10-22 18:31:58 +00001375 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 }
1377
1378 // Okay, if there weren't any loop invariants to be folded, check to see if
1379 // there are multiple AddRec's with the same loop induction variable being
1380 // added together. If so, we can fold them.
1381 for (unsigned OtherIdx = Idx+1;
1382 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1383 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001384 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1386 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001387 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1388 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1390 if (i >= NewOps.size()) {
1391 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1392 OtherAddRec->op_end());
1393 break;
1394 }
Dan Gohman89f85052007-10-22 18:31:58 +00001395 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001397 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398
1399 if (Ops.size() == 2) return NewAddRec;
1400
1401 Ops.erase(Ops.begin()+Idx);
1402 Ops.erase(Ops.begin()+OtherIdx-1);
1403 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001404 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 }
1406 }
1407
1408 // Otherwise couldn't fold anything into this recurrence. Move onto the
1409 // next one.
1410 }
1411
1412 // Okay, it looks like we really DO need an add expr. Check to see if we
1413 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001414 FoldingSetNodeID ID;
1415 ID.AddInteger(scAddExpr);
1416 ID.AddInteger(Ops.size());
1417 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1418 ID.AddPointer(Ops[i]);
1419 void *IP = 0;
1420 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1421 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1422 new (S) SCEVAddExpr(Ops);
1423 UniqueSCEVs.InsertNode(S, IP);
1424 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425}
1426
1427
Dan Gohmanc8a29272009-05-24 23:45:28 +00001428/// getMulExpr - Get a canonical multiply expression, or something simpler if
1429/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001430const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001432#ifndef NDEBUG
1433 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1434 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1435 getEffectiveSCEVType(Ops[0]->getType()) &&
1436 "SCEVMulExpr operand types don't match!");
1437#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438
1439 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001440 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441
1442 // If there are any constants, fold them together.
1443 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001444 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445
1446 // C1*(C2+V) -> C1*C2 + C1*V
1447 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001448 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 if (Add->getNumOperands() == 2 &&
1450 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001451 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1452 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453
1454
1455 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001456 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001458 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001459 RHSC->getValue()->getValue());
1460 Ops[0] = getConstant(Fold);
1461 Ops.erase(Ops.begin()+1); // Erase the folded element
1462 if (Ops.size() == 1) return Ops[0];
1463 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 }
1465
1466 // If we are left with a constant one being multiplied, strip it off.
1467 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1468 Ops.erase(Ops.begin());
1469 --Idx;
1470 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1471 // If we have a multiply of zero, it will always be zero.
1472 return Ops[0];
1473 }
1474 }
1475
1476 // Skip over the add expression until we get to a multiply.
1477 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1478 ++Idx;
1479
1480 if (Ops.size() == 1)
1481 return Ops[0];
1482
1483 // If there are mul operands inline them all into this expression.
1484 if (Idx < Ops.size()) {
1485 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001486 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 // If we have an mul, expand the mul operands onto the end of the operands
1488 // list.
1489 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1490 Ops.erase(Ops.begin()+Idx);
1491 DeletedMul = true;
1492 }
1493
1494 // If we deleted at least one mul, we added operands to the end of the list,
1495 // and they are not necessarily sorted. Recurse to resort and resimplify
1496 // any operands we just aquired.
1497 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001498 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499 }
1500
1501 // If there are any add recurrences in the operands list, see if any other
1502 // added values are loop invariant. If so, we can fold them into the
1503 // recurrence.
1504 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1505 ++Idx;
1506
1507 // Scan over all recurrences, trying to fold loop invariants into them.
1508 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1509 // Scan all of the other operands to this mul and add them to the vector if
1510 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001511 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001512 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1514 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1515 LIOps.push_back(Ops[i]);
1516 Ops.erase(Ops.begin()+i);
1517 --i; --e;
1518 }
1519
1520 // If we found some loop invariants, fold them into the recurrence.
1521 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001522 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Andersonecd0cd72009-06-22 21:39:50 +00001523 SmallVector<const SCEV*, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 NewOps.reserve(AddRec->getNumOperands());
1525 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001526 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001527 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001528 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529 } else {
1530 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001531 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001533 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534 }
1535 }
1536
Owen Andersonecd0cd72009-06-22 21:39:50 +00001537 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538
1539 // If all of the other operands were loop invariant, we are done.
1540 if (Ops.size() == 1) return NewRec;
1541
1542 // Otherwise, multiply the folded AddRec by the non-liv parts.
1543 for (unsigned i = 0;; ++i)
1544 if (Ops[i] == AddRec) {
1545 Ops[i] = NewRec;
1546 break;
1547 }
Dan Gohman89f85052007-10-22 18:31:58 +00001548 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549 }
1550
1551 // Okay, if there weren't any loop invariants to be folded, check to see if
1552 // there are multiple AddRec's with the same loop induction variable being
1553 // multiplied together. If so, we can fold them.
1554 for (unsigned OtherIdx = Idx+1;
1555 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1556 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001557 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1559 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001560 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001561 const SCEV* NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 G->getStart());
Owen Andersonecd0cd72009-06-22 21:39:50 +00001563 const SCEV* B = F->getStepRecurrence(*this);
1564 const SCEV* D = G->getStepRecurrence(*this);
1565 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001566 getMulExpr(G, B),
1567 getMulExpr(B, D));
Owen Andersonecd0cd72009-06-22 21:39:50 +00001568 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001569 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570 if (Ops.size() == 2) return NewAddRec;
1571
1572 Ops.erase(Ops.begin()+Idx);
1573 Ops.erase(Ops.begin()+OtherIdx-1);
1574 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001575 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 }
1577 }
1578
1579 // Otherwise couldn't fold anything into this recurrence. Move onto the
1580 // next one.
1581 }
1582
1583 // Okay, it looks like we really DO need an mul expr. Check to see if we
1584 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001585 FoldingSetNodeID ID;
1586 ID.AddInteger(scMulExpr);
1587 ID.AddInteger(Ops.size());
1588 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1589 ID.AddPointer(Ops[i]);
1590 void *IP = 0;
1591 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1592 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1593 new (S) SCEVMulExpr(Ops);
1594 UniqueSCEVs.InsertNode(S, IP);
1595 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596}
1597
Dan Gohmanc8a29272009-05-24 23:45:28 +00001598/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1599/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001600const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1601 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001602 assert(getEffectiveSCEVType(LHS->getType()) ==
1603 getEffectiveSCEVType(RHS->getType()) &&
1604 "SCEVUDivExpr operand types don't match!");
1605
Dan Gohmanc76b5452009-05-04 22:02:23 +00001606 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001608 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001609 if (RHSC->isZero())
1610 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001611
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001612 // Determine if the division can be folded into the operands of
1613 // its operands.
1614 // TODO: Generalize this to non-constants by using known-bits information.
1615 const Type *Ty = LHS->getType();
1616 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1617 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1618 // For non-power-of-two values, effectively round the value up to the
1619 // nearest power of two.
1620 if (!RHSC->getValue()->getValue().isPowerOf2())
1621 ++MaxShiftAmt;
1622 const IntegerType *ExtTy =
1623 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1624 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1625 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1626 if (const SCEVConstant *Step =
1627 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1628 if (!Step->getValue()->getValue()
1629 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001630 getZeroExtendExpr(AR, ExtTy) ==
1631 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1632 getZeroExtendExpr(Step, ExtTy),
1633 AR->getLoop())) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001634 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001635 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1636 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1637 return getAddRecExpr(Operands, AR->getLoop());
1638 }
1639 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001640 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001641 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001642 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1643 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1644 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001645 // Find an operand that's safely divisible.
1646 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001647 const SCEV* Op = M->getOperand(i);
1648 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001649 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001650 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1651 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001652 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001653 Operands[i] = Div;
1654 return getMulExpr(Operands);
1655 }
1656 }
Dan Gohman14374d32009-05-08 23:11:16 +00001657 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001658 // (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 +00001659 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001660 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001661 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1662 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1663 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1664 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001665 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001666 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001667 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1668 break;
1669 Operands.push_back(Op);
1670 }
1671 if (Operands.size() == A->getNumOperands())
1672 return getAddExpr(Operands);
1673 }
Dan Gohman14374d32009-05-08 23:11:16 +00001674 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001675
1676 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001677 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678 Constant *LHSCV = LHSC->getValue();
1679 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001680 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1681 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 }
1683 }
1684
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001685 FoldingSetNodeID ID;
1686 ID.AddInteger(scUDivExpr);
1687 ID.AddPointer(LHS);
1688 ID.AddPointer(RHS);
1689 void *IP = 0;
1690 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1691 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1692 new (S) SCEVUDivExpr(LHS, RHS);
1693 UniqueSCEVs.InsertNode(S, IP);
1694 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001695}
1696
1697
Dan Gohmanc8a29272009-05-24 23:45:28 +00001698/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1699/// Simplify the expression as much as possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001700const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1701 const SCEV* Step, const Loop *L) {
1702 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001704 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 if (StepChrec->getLoop() == L) {
1706 Operands.insert(Operands.end(), StepChrec->op_begin(),
1707 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001708 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 }
1710
1711 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001712 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001713}
1714
Dan Gohmanc8a29272009-05-24 23:45:28 +00001715/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1716/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001717const SCEV *
1718ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
1719 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001721#ifndef NDEBUG
1722 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1723 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1724 getEffectiveSCEVType(Operands[0]->getType()) &&
1725 "SCEVAddRecExpr operand types don't match!");
1726#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727
Dan Gohman7b560c42008-06-18 16:23:07 +00001728 if (Operands.back()->isZero()) {
1729 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001730 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001731 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732
Dan Gohman42936882008-08-08 18:33:12 +00001733 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001734 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001735 const Loop* NestedLoop = NestedAR->getLoop();
1736 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001737 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001738 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001739 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001740 // AddRecs require their operands be loop-invariant with respect to their
1741 // loops. Don't perform this transformation if it would break this
1742 // requirement.
1743 bool AllInvariant = true;
1744 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1745 if (!Operands[i]->isLoopInvariant(L)) {
1746 AllInvariant = false;
1747 break;
1748 }
1749 if (AllInvariant) {
1750 NestedOperands[0] = getAddRecExpr(Operands, L);
1751 AllInvariant = true;
1752 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1753 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1754 AllInvariant = false;
1755 break;
1756 }
1757 if (AllInvariant)
1758 // Ok, both add recurrences are valid after the transformation.
1759 return getAddRecExpr(NestedOperands, NestedLoop);
1760 }
1761 // Reset Operands to its original state.
1762 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001763 }
1764 }
1765
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001766 FoldingSetNodeID ID;
1767 ID.AddInteger(scAddRecExpr);
1768 ID.AddInteger(Operands.size());
1769 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1770 ID.AddPointer(Operands[i]);
1771 ID.AddPointer(L);
1772 void *IP = 0;
1773 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1774 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1775 new (S) SCEVAddRecExpr(Operands, L);
1776 UniqueSCEVs.InsertNode(S, IP);
1777 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778}
1779
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001780const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1781 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001782 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001783 Ops.push_back(LHS);
1784 Ops.push_back(RHS);
1785 return getSMaxExpr(Ops);
1786}
1787
Owen Andersonecd0cd72009-06-22 21:39:50 +00001788const SCEV*
1789ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001790 assert(!Ops.empty() && "Cannot get empty smax!");
1791 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001792#ifndef NDEBUG
1793 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1794 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1795 getEffectiveSCEVType(Ops[0]->getType()) &&
1796 "SCEVSMaxExpr operand types don't match!");
1797#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001798
1799 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001800 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001801
1802 // If there are any constants, fold them together.
1803 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001804 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001805 ++Idx;
1806 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001807 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001808 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001809 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001810 APIntOps::smax(LHSC->getValue()->getValue(),
1811 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001812 Ops[0] = getConstant(Fold);
1813 Ops.erase(Ops.begin()+1); // Erase the folded element
1814 if (Ops.size() == 1) return Ops[0];
1815 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001816 }
1817
Dan Gohmand156c092009-06-24 14:46:22 +00001818 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001819 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1820 Ops.erase(Ops.begin());
1821 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001822 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1823 // If we have an smax with a constant maximum-int, it will always be
1824 // maximum-int.
1825 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001826 }
1827 }
1828
1829 if (Ops.size() == 1) return Ops[0];
1830
1831 // Find the first SMax
1832 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1833 ++Idx;
1834
1835 // Check to see if one of the operands is an SMax. If so, expand its operands
1836 // onto our operand list, and recurse to simplify.
1837 if (Idx < Ops.size()) {
1838 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001839 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001840 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1841 Ops.erase(Ops.begin()+Idx);
1842 DeletedSMax = true;
1843 }
1844
1845 if (DeletedSMax)
1846 return getSMaxExpr(Ops);
1847 }
1848
1849 // Okay, check to see if the same value occurs in the operand list twice. If
1850 // so, delete one. Since we sorted the list, these values are required to
1851 // be adjacent.
1852 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1853 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1854 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1855 --i; --e;
1856 }
1857
1858 if (Ops.size() == 1) return Ops[0];
1859
1860 assert(!Ops.empty() && "Reduced smax down to nothing!");
1861
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001862 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001863 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001864 FoldingSetNodeID ID;
1865 ID.AddInteger(scSMaxExpr);
1866 ID.AddInteger(Ops.size());
1867 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1868 ID.AddPointer(Ops[i]);
1869 void *IP = 0;
1870 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1871 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1872 new (S) SCEVSMaxExpr(Ops);
1873 UniqueSCEVs.InsertNode(S, IP);
1874 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001875}
1876
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001877const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1878 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001879 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001880 Ops.push_back(LHS);
1881 Ops.push_back(RHS);
1882 return getUMaxExpr(Ops);
1883}
1884
Owen Andersonecd0cd72009-06-22 21:39:50 +00001885const SCEV*
1886ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001887 assert(!Ops.empty() && "Cannot get empty umax!");
1888 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001889#ifndef NDEBUG
1890 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1891 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1892 getEffectiveSCEVType(Ops[0]->getType()) &&
1893 "SCEVUMaxExpr operand types don't match!");
1894#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001895
1896 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001897 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001898
1899 // If there are any constants, fold them together.
1900 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001901 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001902 ++Idx;
1903 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001904 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001905 // We found two constants, fold them together!
1906 ConstantInt *Fold = ConstantInt::get(
1907 APIntOps::umax(LHSC->getValue()->getValue(),
1908 RHSC->getValue()->getValue()));
1909 Ops[0] = getConstant(Fold);
1910 Ops.erase(Ops.begin()+1); // Erase the folded element
1911 if (Ops.size() == 1) return Ops[0];
1912 LHSC = cast<SCEVConstant>(Ops[0]);
1913 }
1914
Dan Gohmand156c092009-06-24 14:46:22 +00001915 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001916 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1917 Ops.erase(Ops.begin());
1918 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001919 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1920 // If we have an umax with a constant maximum-int, it will always be
1921 // maximum-int.
1922 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001923 }
1924 }
1925
1926 if (Ops.size() == 1) return Ops[0];
1927
1928 // Find the first UMax
1929 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1930 ++Idx;
1931
1932 // Check to see if one of the operands is a UMax. If so, expand its operands
1933 // onto our operand list, and recurse to simplify.
1934 if (Idx < Ops.size()) {
1935 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001936 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001937 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1938 Ops.erase(Ops.begin()+Idx);
1939 DeletedUMax = true;
1940 }
1941
1942 if (DeletedUMax)
1943 return getUMaxExpr(Ops);
1944 }
1945
1946 // Okay, check to see if the same value occurs in the operand list twice. If
1947 // so, delete one. Since we sorted the list, these values are required to
1948 // be adjacent.
1949 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1950 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1951 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1952 --i; --e;
1953 }
1954
1955 if (Ops.size() == 1) return Ops[0];
1956
1957 assert(!Ops.empty() && "Reduced umax down to nothing!");
1958
1959 // Okay, it looks like we really DO need a umax expr. Check to see if we
1960 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001961 FoldingSetNodeID ID;
1962 ID.AddInteger(scUMaxExpr);
1963 ID.AddInteger(Ops.size());
1964 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1965 ID.AddPointer(Ops[i]);
1966 void *IP = 0;
1967 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1968 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1969 new (S) SCEVUMaxExpr(Ops);
1970 UniqueSCEVs.InsertNode(S, IP);
1971 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001972}
1973
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001974const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1975 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001976 // ~smax(~x, ~y) == smin(x, y).
1977 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1978}
1979
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001980const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1981 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001982 // ~umax(~x, ~y) == umin(x, y)
1983 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1984}
1985
Owen Andersonecd0cd72009-06-22 21:39:50 +00001986const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001987 // Don't attempt to do anything other than create a SCEVUnknown object
1988 // here. createSCEV only calls getUnknown after checking for all other
1989 // interesting possibilities, and any other code that calls getUnknown
1990 // is doing so in order to hide a value from SCEV canonicalization.
1991
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001992 FoldingSetNodeID ID;
1993 ID.AddInteger(scUnknown);
1994 ID.AddPointer(V);
1995 void *IP = 0;
1996 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1997 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
1998 new (S) SCEVUnknown(V);
1999 UniqueSCEVs.InsertNode(S, IP);
2000 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001}
2002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002003//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004// Basic SCEV Analysis and PHI Idiom Recognition Code
2005//
2006
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002007/// isSCEVable - Test if values of the given type are analyzable within
2008/// the SCEV framework. This primarily includes integer types, and it
2009/// can optionally include pointer types if the ScalarEvolution class
2010/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002011bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002012 // Integers are always SCEVable.
2013 if (Ty->isInteger())
2014 return true;
2015
2016 // Pointers are SCEVable if TargetData information is available
2017 // to provide pointer size information.
2018 if (isa<PointerType>(Ty))
2019 return TD != NULL;
2020
2021 // Otherwise it's not SCEVable.
2022 return false;
2023}
2024
2025/// getTypeSizeInBits - Return the size in bits of the specified type,
2026/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002027uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002028 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2029
2030 // If we have a TargetData, use it!
2031 if (TD)
2032 return TD->getTypeSizeInBits(Ty);
2033
2034 // Otherwise, we support only integer types.
2035 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2036 return Ty->getPrimitiveSizeInBits();
2037}
2038
2039/// getEffectiveSCEVType - Return a type with the same bitwidth as
2040/// the given type and which represents how SCEV will treat the given
2041/// type, for which isSCEVable must return true. For pointer types,
2042/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002043const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002044 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2045
2046 if (Ty->isInteger())
2047 return Ty;
2048
2049 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2050 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002051}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002052
Owen Andersonecd0cd72009-06-22 21:39:50 +00002053const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002054 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002055}
2056
Dan Gohmand83d4af2009-05-04 22:20:30 +00002057/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00002058/// computed.
2059bool ScalarEvolution::hasSCEV(Value *V) const {
2060 return Scalars.count(V);
2061}
2062
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2064/// expression and create a new one.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002065const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002066 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067
Owen Andersonecd0cd72009-06-22 21:39:50 +00002068 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069 if (I != Scalars.end()) return I->second;
Owen Andersonecd0cd72009-06-22 21:39:50 +00002070 const SCEV* S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002071 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002072 return S;
2073}
2074
Dan Gohman984c78a2009-06-24 00:54:57 +00002075/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002076/// specified signed integer value and return a SCEV for the constant.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002077const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002078 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2079 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002080}
2081
2082/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2083///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002084const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002085 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002086 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002087
2088 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002089 Ty = getEffectiveSCEVType(Ty);
2090 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002091}
2092
2093/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Andersonecd0cd72009-06-22 21:39:50 +00002094const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002095 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002096 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002097
2098 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002099 Ty = getEffectiveSCEVType(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002100 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002101 return getMinusSCEV(AllOnes, V);
2102}
2103
2104/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2105///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002106const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2107 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002108 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002109 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002110}
2111
2112/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2113/// input value to the specified type. If the type must be extended, it is zero
2114/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002115const SCEV*
2116ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002117 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002118 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002119 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2120 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002121 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002122 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002123 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002124 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002125 return getTruncateExpr(V, Ty);
2126 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002127}
2128
2129/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2130/// input value to the specified type. If the type must be extended, it is sign
2131/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002132const SCEV*
2133ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002134 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002135 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002136 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2137 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002138 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002139 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002140 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002141 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002142 return getTruncateExpr(V, Ty);
2143 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002144}
2145
Dan Gohmanac959332009-05-13 03:46:30 +00002146/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2147/// input value to the specified type. If the type must be extended, it is zero
2148/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002149const SCEV*
2150ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002151 const Type *SrcTy = V->getType();
2152 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2153 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2154 "Cannot noop or zero extend with non-integer arguments!");
2155 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2156 "getNoopOrZeroExtend cannot truncate!");
2157 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2158 return V; // No conversion
2159 return getZeroExtendExpr(V, Ty);
2160}
2161
2162/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2163/// input value to the specified type. If the type must be extended, it is sign
2164/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002165const SCEV*
2166ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002167 const Type *SrcTy = V->getType();
2168 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2169 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2170 "Cannot noop or sign extend with non-integer arguments!");
2171 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2172 "getNoopOrSignExtend cannot truncate!");
2173 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2174 return V; // No conversion
2175 return getSignExtendExpr(V, Ty);
2176}
2177
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002178/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2179/// the input value to the specified type. If the type must be extended,
2180/// it is extended with unspecified bits. The conversion must not be
2181/// narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002182const SCEV*
2183ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002184 const Type *SrcTy = V->getType();
2185 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2186 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2187 "Cannot noop or any extend with non-integer arguments!");
2188 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2189 "getNoopOrAnyExtend cannot truncate!");
2190 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2191 return V; // No conversion
2192 return getAnyExtendExpr(V, Ty);
2193}
2194
Dan Gohmanac959332009-05-13 03:46:30 +00002195/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2196/// input value to the specified type. The conversion must not be widening.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002197const SCEV*
2198ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002199 const Type *SrcTy = V->getType();
2200 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2201 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2202 "Cannot truncate or noop with non-integer arguments!");
2203 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2204 "getTruncateOrNoop cannot extend!");
2205 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2206 return V; // No conversion
2207 return getTruncateExpr(V, Ty);
2208}
2209
Dan Gohman8e8b5232009-06-22 00:31:57 +00002210/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2211/// the types using zero-extension, and then perform a umax operation
2212/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002213const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2214 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002215 const SCEV* PromotedLHS = LHS;
2216 const SCEV* PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002217
2218 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2219 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2220 else
2221 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2222
2223 return getUMaxExpr(PromotedLHS, PromotedRHS);
2224}
2225
Dan Gohman9e62bb02009-06-22 15:03:27 +00002226/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2227/// the types using zero-extension, and then perform a umin operation
2228/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002229const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2230 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002231 const SCEV* PromotedLHS = LHS;
2232 const SCEV* PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002233
2234 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2235 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2236 else
2237 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2238
2239 return getUMinExpr(PromotedLHS, PromotedRHS);
2240}
2241
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002242/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2243/// the specified instruction and replaces any references to the symbolic value
2244/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002245void
2246ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2247 const SCEV *SymName,
2248 const SCEV *NewVal) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002249 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002250 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002251 if (SI == Scalars.end()) return;
2252
Owen Andersonecd0cd72009-06-22 21:39:50 +00002253 const SCEV* NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002254 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255 if (NV == SI->second) return; // No change.
2256
2257 SI->second = NV; // Update the scalars map!
2258
2259 // Any instruction values that use this instruction might also need to be
2260 // updated!
2261 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2262 UI != E; ++UI)
2263 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2264}
2265
2266/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2267/// a loop header, making it a potential recurrence, or it doesn't.
2268///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002269const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002271 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 if (L->getHeader() == PN->getParent()) {
2273 // If it lives in the loop header, it has two incoming values, one
2274 // from outside the loop, and one from inside.
2275 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2276 unsigned BackEdge = IncomingEdge^1;
2277
2278 // While we are analyzing this PHI node, handle its value symbolically.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002279 const SCEV* SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280 assert(Scalars.find(PN) == Scalars.end() &&
2281 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002282 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283
2284 // Using this symbolic name for the PHI, analyze the value coming around
2285 // the back-edge.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002286 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287
2288 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2289 // has a special value for the first iteration of the loop.
2290
2291 // If the value coming around the backedge is an add with the symbolic
2292 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002293 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294 // If there is a single occurrence of the symbolic value, replace it
2295 // with a recurrence.
2296 unsigned FoundIndex = Add->getNumOperands();
2297 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2298 if (Add->getOperand(i) == SymbolicName)
2299 if (FoundIndex == e) {
2300 FoundIndex = i;
2301 break;
2302 }
2303
2304 if (FoundIndex != Add->getNumOperands()) {
2305 // Create an add with everything but the specified operand.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002306 SmallVector<const SCEV*, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2308 if (i != FoundIndex)
2309 Ops.push_back(Add->getOperand(i));
Owen Andersonecd0cd72009-06-22 21:39:50 +00002310 const SCEV* Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311
2312 // This is not a valid addrec if the step amount is varying each
2313 // loop iteration, but is not itself an addrec in this loop.
2314 if (Accum->isLoopInvariant(L) ||
2315 (isa<SCEVAddRecExpr>(Accum) &&
2316 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002317 const SCEV *StartVal =
2318 getSCEV(PN->getIncomingValue(IncomingEdge));
2319 const SCEV *PHISCEV =
2320 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321
2322 // Okay, for the entire analysis of this edge we assumed the PHI
2323 // to be symbolic. We now need to go back and update all of the
2324 // entries for the scalars that use the PHI (except for the PHI
2325 // itself) to use the new analyzed value instead of the "symbolic"
2326 // value.
2327 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2328 return PHISCEV;
2329 }
2330 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002331 } else if (const SCEVAddRecExpr *AddRec =
2332 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333 // Otherwise, this could be a loop like this:
2334 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2335 // In this case, j = {1,+,1} and BEValue is j.
2336 // Because the other in-value of i (0) fits the evolution of BEValue
2337 // i really is an addrec evolution.
2338 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002339 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002340
2341 // If StartVal = j.start - j.stride, we can use StartVal as the
2342 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002343 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002344 AddRec->getOperand(1))) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002345 const SCEV* PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002346 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002347
2348 // Okay, for the entire analysis of this edge we assumed the PHI
2349 // to be symbolic. We now need to go back and update all of the
2350 // entries for the scalars that use the PHI (except for the PHI
2351 // itself) to use the new analyzed value instead of the "symbolic"
2352 // value.
2353 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2354 return PHISCEV;
2355 }
2356 }
2357 }
2358
2359 return SymbolicName;
2360 }
2361
2362 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002363 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002364}
2365
Dan Gohman509cf4d2009-05-08 20:26:55 +00002366/// createNodeForGEP - Expand GEP instructions into add and multiply
2367/// operations. This allows them to be analyzed by regular SCEV code.
2368///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002369const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002370
2371 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002372 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002373 // Don't attempt to analyze GEPs over unsized objects.
2374 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2375 return getUnknown(GEP);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002376 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002377 gep_type_iterator GTI = gep_type_begin(GEP);
2378 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2379 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002380 I != E; ++I) {
2381 Value *Index = *I;
2382 // Compute the (potentially symbolic) offset in bytes for this index.
2383 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2384 // For a struct, add the member offset.
2385 const StructLayout &SL = *TD->getStructLayout(STy);
2386 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2387 uint64_t Offset = SL.getElementOffset(FieldNo);
2388 TotalOffset = getAddExpr(TotalOffset,
2389 getIntegerSCEV(Offset, IntPtrTy));
2390 } else {
2391 // For an array, add the element offset, explicitly scaled.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002392 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002393 if (!isa<PointerType>(LocalOffset->getType()))
2394 // Getelementptr indicies are signed.
2395 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2396 IntPtrTy);
2397 LocalOffset =
2398 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002399 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002400 IntPtrTy));
2401 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2402 }
2403 }
2404 return getAddExpr(getSCEV(Base), TotalOffset);
2405}
2406
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002407/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2408/// guaranteed to end in (at every loop iteration). It is, at the same time,
2409/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2410/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002411uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002412ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002413 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002414 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415
Dan Gohmanc76b5452009-05-04 22:02:23 +00002416 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002417 return std::min(GetMinTrailingZeros(T->getOperand()),
2418 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002419
Dan Gohmanc76b5452009-05-04 22:02:23 +00002420 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002421 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2422 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2423 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002424 }
2425
Dan Gohmanc76b5452009-05-04 22:02:23 +00002426 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002427 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2428 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2429 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002430 }
2431
Dan Gohmanc76b5452009-05-04 22:02:23 +00002432 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002433 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002434 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002435 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002436 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002437 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002438 }
2439
Dan Gohmanc76b5452009-05-04 22:02:23 +00002440 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002441 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002442 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2443 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002444 for (unsigned i = 1, e = M->getNumOperands();
2445 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002446 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002447 BitWidth);
2448 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002449 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002450
Dan Gohmanc76b5452009-05-04 22:02:23 +00002451 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002452 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002453 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002454 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002455 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002456 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002458
Dan Gohmanc76b5452009-05-04 22:02:23 +00002459 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002460 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002461 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002462 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002463 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002464 return MinOpRes;
2465 }
2466
Dan Gohmanc76b5452009-05-04 22:02:23 +00002467 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002468 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002469 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002470 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002471 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002472 return MinOpRes;
2473 }
2474
Dan Gohman6e923a72009-06-19 23:29:04 +00002475 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2476 // For a SCEVUnknown, ask ValueTracking.
2477 unsigned BitWidth = getTypeSizeInBits(U->getType());
2478 APInt Mask = APInt::getAllOnesValue(BitWidth);
2479 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2480 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2481 return Zeros.countTrailingOnes();
2482 }
2483
2484 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002485 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486}
2487
Dan Gohman6e923a72009-06-19 23:29:04 +00002488uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002489ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002490 // TODO: Handle other SCEV expression types here.
2491
2492 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2493 return C->getValue()->getValue().countLeadingZeros();
2494
2495 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2496 // A zero-extension cast adds zero bits.
2497 return GetMinLeadingZeros(C->getOperand()) +
2498 (getTypeSizeInBits(C->getType()) -
2499 getTypeSizeInBits(C->getOperand()->getType()));
2500 }
2501
2502 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2503 // For a SCEVUnknown, ask ValueTracking.
2504 unsigned BitWidth = getTypeSizeInBits(U->getType());
2505 APInt Mask = APInt::getAllOnesValue(BitWidth);
2506 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2507 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2508 return Zeros.countLeadingOnes();
2509 }
2510
2511 return 1;
2512}
2513
2514uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002515ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002516 // TODO: Handle other SCEV expression types here.
2517
2518 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2519 const APInt &A = C->getValue()->getValue();
2520 return A.isNegative() ? A.countLeadingOnes() :
2521 A.countLeadingZeros();
2522 }
2523
2524 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2525 // A sign-extension cast adds sign bits.
2526 return GetMinSignBits(C->getOperand()) +
2527 (getTypeSizeInBits(C->getType()) -
2528 getTypeSizeInBits(C->getOperand()->getType()));
2529 }
2530
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002531 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2532 unsigned BitWidth = getTypeSizeInBits(A->getType());
2533
2534 // Special case decrementing a value (ADD X, -1):
2535 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2536 if (CRHS->isAllOnesValue()) {
2537 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2538 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2539 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2540
2541 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2542 // sign bits set.
2543 if (LZ == BitWidth - 1)
2544 return BitWidth;
2545
2546 // If we are subtracting one from a positive number, there is no carry
2547 // out of the result.
2548 if (LZ > 0)
2549 return GetMinSignBits(OtherOpsAdd);
2550 }
2551
2552 // Add can have at most one carry bit. Thus we know that the output
2553 // is, at worst, one more bit than the inputs.
2554 unsigned Min = BitWidth;
2555 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2556 unsigned N = GetMinSignBits(A->getOperand(i));
2557 Min = std::min(Min, N) - 1;
2558 if (Min == 0) return 1;
2559 }
2560 return 1;
2561 }
2562
Dan Gohman6e923a72009-06-19 23:29:04 +00002563 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2564 // For a SCEVUnknown, ask ValueTracking.
2565 return ComputeNumSignBits(U->getValue(), TD);
2566 }
2567
2568 return 1;
2569}
2570
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571/// createSCEV - We know that there is no SCEV for the specified value.
2572/// Analyze the expression.
2573///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002574const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002575 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002576 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002577
Dan Gohman3996f472008-06-22 19:56:46 +00002578 unsigned Opcode = Instruction::UserOp1;
2579 if (Instruction *I = dyn_cast<Instruction>(V))
2580 Opcode = I->getOpcode();
2581 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2582 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002583 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2584 return getConstant(CI);
2585 else if (isa<ConstantPointerNull>(V))
2586 return getIntegerSCEV(0, V->getType());
2587 else if (isa<UndefValue>(V))
2588 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002589 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002590 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591
Dan Gohman3996f472008-06-22 19:56:46 +00002592 User *U = cast<User>(V);
2593 switch (Opcode) {
2594 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002595 return getAddExpr(getSCEV(U->getOperand(0)),
2596 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002597 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002598 return getMulExpr(getSCEV(U->getOperand(0)),
2599 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002600 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002601 return getUDivExpr(getSCEV(U->getOperand(0)),
2602 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002603 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002604 return getMinusSCEV(getSCEV(U->getOperand(0)),
2605 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002606 case Instruction::And:
2607 // For an expression like x&255 that merely masks off the high bits,
2608 // use zext(trunc(x)) as the SCEV expression.
2609 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002610 if (CI->isNullValue())
2611 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002612 if (CI->isAllOnesValue())
2613 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002614 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002615
2616 // Instcombine's ShrinkDemandedConstant may strip bits out of
2617 // constants, obscuring what would otherwise be a low-bits mask.
2618 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2619 // knew about to reconstruct a low-bits mask value.
2620 unsigned LZ = A.countLeadingZeros();
2621 unsigned BitWidth = A.getBitWidth();
2622 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2623 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2624 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2625
2626 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2627
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002628 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002629 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002630 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002631 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002632 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002633 }
2634 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002635
Dan Gohman3996f472008-06-22 19:56:46 +00002636 case Instruction::Or:
2637 // If the RHS of the Or is a constant, we may have something like:
2638 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2639 // optimizations will transparently handle this case.
2640 //
2641 // In order for this transformation to be safe, the LHS must be of the
2642 // form X*(2^n) and the Or constant must be less than 2^n.
2643 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002644 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002645 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002646 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002647 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002648 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002649 }
Dan Gohman3996f472008-06-22 19:56:46 +00002650 break;
2651 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002652 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002653 // If the RHS of the xor is a signbit, then this is just an add.
2654 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002655 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002656 return getAddExpr(getSCEV(U->getOperand(0)),
2657 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002658
2659 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002660 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002661 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002662
2663 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2664 // This is a variant of the check for xor with -1, and it handles
2665 // the case where instcombine has trimmed non-demanded bits out
2666 // of an xor with -1.
2667 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2668 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2669 if (BO->getOpcode() == Instruction::And &&
2670 LCI->getValue() == CI->getValue())
2671 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002672 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002673 const Type *UTy = U->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00002674 const SCEV* Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002675 const Type *Z0Ty = Z0->getType();
2676 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2677
2678 // If C is a low-bits mask, the zero extend is zerving to
2679 // mask off the high bits. Complement the operand and
2680 // re-apply the zext.
2681 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2682 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2683
2684 // If C is a single bit, it may be in the sign-bit position
2685 // before the zero-extend. In this case, represent the xor
2686 // using an add, which is equivalent, and re-apply the zext.
2687 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2688 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2689 Trunc.isSignBit())
2690 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2691 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002692 }
Dan Gohman3996f472008-06-22 19:56:46 +00002693 }
2694 break;
2695
2696 case Instruction::Shl:
2697 // Turn shift left of a constant amount into a multiply.
2698 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2699 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2700 Constant *X = ConstantInt::get(
2701 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002702 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002703 }
2704 break;
2705
Nick Lewycky7fd27892008-07-07 06:15:49 +00002706 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002707 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002708 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2709 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2710 Constant *X = ConstantInt::get(
2711 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002712 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002713 }
2714 break;
2715
Dan Gohman53bf64a2009-04-21 02:26:00 +00002716 case Instruction::AShr:
2717 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2718 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2719 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2720 if (L->getOpcode() == Instruction::Shl &&
2721 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002722 unsigned BitWidth = getTypeSizeInBits(U->getType());
2723 uint64_t Amt = BitWidth - CI->getZExtValue();
2724 if (Amt == BitWidth)
2725 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2726 if (Amt > BitWidth)
2727 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002728 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002729 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002730 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002731 U->getType());
2732 }
2733 break;
2734
Dan Gohman3996f472008-06-22 19:56:46 +00002735 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002736 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002737
2738 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002739 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002740
2741 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002742 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002743
2744 case Instruction::BitCast:
2745 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002746 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002747 return getSCEV(U->getOperand(0));
2748 break;
2749
Dan Gohman01c2ee72009-04-16 03:18:22 +00002750 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002751 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002752 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002753 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002754
2755 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002756 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002757 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2758 U->getType());
2759
Dan Gohman509cf4d2009-05-08 20:26:55 +00002760 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002761 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002762 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002763
Dan Gohman3996f472008-06-22 19:56:46 +00002764 case Instruction::PHI:
2765 return createNodeForPHI(cast<PHINode>(U));
2766
2767 case Instruction::Select:
2768 // This could be a smax or umax that was lowered earlier.
2769 // Try to recover it.
2770 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2771 Value *LHS = ICI->getOperand(0);
2772 Value *RHS = ICI->getOperand(1);
2773 switch (ICI->getPredicate()) {
2774 case ICmpInst::ICMP_SLT:
2775 case ICmpInst::ICMP_SLE:
2776 std::swap(LHS, RHS);
2777 // fall through
2778 case ICmpInst::ICMP_SGT:
2779 case ICmpInst::ICMP_SGE:
2780 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002781 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002782 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002783 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002784 break;
2785 case ICmpInst::ICMP_ULT:
2786 case ICmpInst::ICMP_ULE:
2787 std::swap(LHS, RHS);
2788 // fall through
2789 case ICmpInst::ICMP_UGT:
2790 case ICmpInst::ICMP_UGE:
2791 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002792 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002793 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002794 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002795 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002796 case ICmpInst::ICMP_NE:
2797 // n != 0 ? n : 1 -> umax(n, 1)
2798 if (LHS == U->getOperand(1) &&
2799 isa<ConstantInt>(U->getOperand(2)) &&
2800 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2801 isa<ConstantInt>(RHS) &&
2802 cast<ConstantInt>(RHS)->isZero())
2803 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2804 break;
2805 case ICmpInst::ICMP_EQ:
2806 // n == 0 ? 1 : n -> umax(n, 1)
2807 if (LHS == U->getOperand(2) &&
2808 isa<ConstantInt>(U->getOperand(1)) &&
2809 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2810 isa<ConstantInt>(RHS) &&
2811 cast<ConstantInt>(RHS)->isZero())
2812 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2813 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002814 default:
2815 break;
2816 }
2817 }
2818
2819 default: // We cannot analyze this expression.
2820 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002821 }
2822
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002823 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002824}
2825
2826
2827
2828//===----------------------------------------------------------------------===//
2829// Iteration Count Computation Code
2830//
2831
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002832/// getBackedgeTakenCount - If the specified loop has a predictable
2833/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2834/// object. The backedge-taken count is the number of times the loop header
2835/// will be branched to from within the loop. This is one less than the
2836/// trip count of the loop, since it doesn't count the first iteration,
2837/// when the header is branched to from outside the loop.
2838///
2839/// Note that it is not valid to call this method on a loop without a
2840/// loop-invariant backedge-taken count (see
2841/// hasLoopInvariantBackedgeTakenCount).
2842///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002843const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002844 return getBackedgeTakenInfo(L).Exact;
2845}
2846
2847/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2848/// return the least SCEV value that is known never to be less than the
2849/// actual backedge taken count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002850const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002851 return getBackedgeTakenInfo(L).Max;
2852}
2853
2854const ScalarEvolution::BackedgeTakenInfo &
2855ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002856 // Initially insert a CouldNotCompute for this loop. If the insertion
2857 // succeeds, procede to actually compute a backedge-taken count and
2858 // update the value. The temporary CouldNotCompute value tells SCEV
2859 // code elsewhere that it shouldn't attempt to request a new
2860 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002861 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002862 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2863 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002864 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002865 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002866 assert(ItCount.Exact->isLoopInvariant(L) &&
2867 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 "Computed trip count isn't loop invariant for loop!");
2869 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002870
Dan Gohmana9dba962009-04-27 20:16:15 +00002871 // Update the value in the map.
2872 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002873 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002874 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002875 // Update the value in the map.
2876 Pair.first->second = ItCount;
2877 if (isa<PHINode>(L->getHeader()->begin()))
2878 // Only count loops that have phi nodes as not being computable.
2879 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002880 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002881
2882 // Now that we know more about the trip count for this loop, forget any
2883 // existing SCEV values for PHI nodes in this loop since they are only
2884 // conservative estimates made without the benefit
2885 // of trip count information.
2886 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002887 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002889 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890}
2891
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002892/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002893/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002894/// ScalarEvolution's ability to compute a trip count, or if the loop
2895/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002896void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002897 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002898 forgetLoopPHIs(L);
2899}
2900
2901/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2902/// PHI nodes in the given loop. This is used when the trip count of
2903/// the loop may have changed.
2904void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002905 BasicBlock *Header = L->getHeader();
2906
Dan Gohman9fd4a002009-05-12 01:27:58 +00002907 // Push all Loop-header PHIs onto the Worklist stack, except those
2908 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2909 // a PHI either means that it has an unrecognized structure, or it's
2910 // a PHI that's in the progress of being computed by createNodeForPHI.
2911 // In the former case, additional loop trip count information isn't
2912 // going to change anything. In the later case, createNodeForPHI will
2913 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002914 SmallVector<Instruction *, 16> Worklist;
2915 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002916 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002917 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2918 Scalars.find((Value*)I);
Dan Gohman9fd4a002009-05-12 01:27:58 +00002919 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2920 Worklist.push_back(PN);
2921 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002922
2923 while (!Worklist.empty()) {
2924 Instruction *I = Worklist.pop_back_val();
2925 if (Scalars.erase(I))
2926 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2927 UI != UE; ++UI)
2928 Worklist.push_back(cast<Instruction>(UI));
2929 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002930}
2931
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002932/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2933/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002934ScalarEvolution::BackedgeTakenInfo
2935ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002936 SmallVector<BasicBlock*, 8> ExitingBlocks;
2937 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002938
Dan Gohman8e8b5232009-06-22 00:31:57 +00002939 // Examine all exits and pick the most conservative values.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002940 const SCEV* BECount = getCouldNotCompute();
2941 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002942 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002943 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2944 BackedgeTakenInfo NewBTI =
2945 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002946
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002947 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002948 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002949 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002950 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002951 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002952 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002953 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002954 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002955 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002956 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002957 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002958 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002959 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002960 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002961 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002962 }
2963
2964 return BackedgeTakenInfo(BECount, MaxBECount);
2965}
2966
2967/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2968/// of the specified loop will execute if it exits via the specified block.
2969ScalarEvolution::BackedgeTakenInfo
2970ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2971 BasicBlock *ExitingBlock) {
2972
2973 // Okay, we've chosen an exiting block. See what condition causes us to
2974 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002975 //
2976 // FIXME: we should be able to handle switch instructions (with a single exit)
2977 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002978 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00002980
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 // At this point, we know we have a conditional branch that determines whether
2982 // the loop is exited. However, we don't know if the branch is executed each
2983 // time through the loop. If not, then the execution count of the branch will
2984 // not be equal to the trip count of the loop.
2985 //
2986 // Currently we check for this by checking to see if the Exit branch goes to
2987 // the loop header. If so, we know it will always execute the same number of
2988 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00002989 // loop header. This is common for un-rotated loops.
2990 //
2991 // If both of those tests fail, walk up the unique predecessor chain to the
2992 // header, stopping if there is an edge that doesn't exit the loop. If the
2993 // header is reached, the execution count of the branch will be equal to the
2994 // trip count of the loop.
2995 //
2996 // More extensive analysis could be done to handle more cases here.
2997 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2999 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003000 ExitBr->getParent() != L->getHeader()) {
3001 // The simple checks failed, try climbing the unique predecessor chain
3002 // up to the header.
3003 bool Ok = false;
3004 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3005 BasicBlock *Pred = BB->getUniquePredecessor();
3006 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003007 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003008 TerminatorInst *PredTerm = Pred->getTerminator();
3009 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3010 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3011 if (PredSucc == BB)
3012 continue;
3013 // If the predecessor has a successor that isn't BB and isn't
3014 // outside the loop, assume the worst.
3015 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003016 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003017 }
3018 if (Pred == L->getHeader()) {
3019 Ok = true;
3020 break;
3021 }
3022 BB = Pred;
3023 }
3024 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003025 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003026 }
3027
3028 // Procede to the next level to examine the exit condition expression.
3029 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3030 ExitBr->getSuccessor(0),
3031 ExitBr->getSuccessor(1));
3032}
3033
3034/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3035/// backedge of the specified loop will execute if its exit condition
3036/// were a conditional branch of ExitCond, TBB, and FBB.
3037ScalarEvolution::BackedgeTakenInfo
3038ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3039 Value *ExitCond,
3040 BasicBlock *TBB,
3041 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003042 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003043 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3044 if (BO->getOpcode() == Instruction::And) {
3045 // Recurse on the operands of the and.
3046 BackedgeTakenInfo BTI0 =
3047 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3048 BackedgeTakenInfo BTI1 =
3049 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003050 const SCEV* BECount = getCouldNotCompute();
3051 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003052 if (L->contains(TBB)) {
3053 // Both conditions must be true for the loop to continue executing.
3054 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003055 if (BTI0.Exact == getCouldNotCompute() ||
3056 BTI1.Exact == getCouldNotCompute())
3057 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003058 else
3059 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003060 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003061 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003062 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003063 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003064 else
3065 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003066 } else {
3067 // Both conditions must be true for the loop to exit.
3068 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003069 if (BTI0.Exact != getCouldNotCompute() &&
3070 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003071 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003072 if (BTI0.Max != getCouldNotCompute() &&
3073 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003074 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3075 }
3076
3077 return BackedgeTakenInfo(BECount, MaxBECount);
3078 }
3079 if (BO->getOpcode() == Instruction::Or) {
3080 // Recurse on the operands of the or.
3081 BackedgeTakenInfo BTI0 =
3082 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3083 BackedgeTakenInfo BTI1 =
3084 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003085 const SCEV* BECount = getCouldNotCompute();
3086 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003087 if (L->contains(FBB)) {
3088 // Both conditions must be false for the loop to continue executing.
3089 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003090 if (BTI0.Exact == getCouldNotCompute() ||
3091 BTI1.Exact == getCouldNotCompute())
3092 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003093 else
3094 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003095 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003096 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003097 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003098 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003099 else
3100 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003101 } else {
3102 // Both conditions must be false for the loop to exit.
3103 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003104 if (BTI0.Exact != getCouldNotCompute() &&
3105 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003106 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003107 if (BTI0.Max != getCouldNotCompute() &&
3108 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003109 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3110 }
3111
3112 return BackedgeTakenInfo(BECount, MaxBECount);
3113 }
3114 }
3115
3116 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3117 // Procede to the next level to examine the icmp.
3118 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3119 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120
Eli Friedman459d7292009-05-09 12:32:42 +00003121 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003122 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3123}
3124
3125/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3126/// backedge of the specified loop will execute if its exit condition
3127/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3128ScalarEvolution::BackedgeTakenInfo
3129ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3130 ICmpInst *ExitCond,
3131 BasicBlock *TBB,
3132 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003133
3134 // If the condition was exit on true, convert the condition to exit on false
3135 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003136 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137 Cond = ExitCond->getPredicate();
3138 else
3139 Cond = ExitCond->getInversePredicate();
3140
3141 // Handle common loops like: for (X = "string"; *X; ++X)
3142 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3143 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003144 const SCEV* ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003145 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003146 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3147 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3148 return BackedgeTakenInfo(ItCnt,
3149 isa<SCEVConstant>(ItCnt) ? ItCnt :
3150 getConstant(APInt::getMaxValue(BitWidth)-1));
3151 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152 }
3153
Owen Andersonecd0cd72009-06-22 21:39:50 +00003154 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3155 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156
3157 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003158 LHS = getSCEVAtScope(LHS, L);
3159 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160
Dan Gohman9bc642f2009-06-24 04:48:43 +00003161 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003163 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3164 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003165 std::swap(LHS, RHS);
3166 Cond = ICmpInst::getSwappedPredicate(Cond);
3167 }
3168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169 // If we have a comparison of a chrec against a constant, try to use value
3170 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003171 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3172 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003174 // Form the constant range.
3175 ConstantRange CompRange(
3176 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177
Owen Andersonecd0cd72009-06-22 21:39:50 +00003178 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003179 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003180 }
3181
3182 switch (Cond) {
3183 case ICmpInst::ICMP_NE: { // while (X != Y)
3184 // Convert to: while (X-Y != 0)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003185 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003186 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3187 break;
3188 }
3189 case ICmpInst::ICMP_EQ: {
3190 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003191 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3193 break;
3194 }
3195 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003196 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3197 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 break;
3199 }
3200 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003201 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3202 getNotSCEV(RHS), L, true);
3203 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003204 break;
3205 }
3206 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003207 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3208 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003209 break;
3210 }
3211 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003212 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3213 getNotSCEV(RHS), L, false);
3214 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 break;
3216 }
3217 default:
3218#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003219 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003221 errs() << "[unsigned] ";
3222 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003223 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 << " " << *RHS << "\n";
3225#endif
3226 break;
3227 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003228 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003229 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003230}
3231
3232static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003233EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3234 ScalarEvolution &SE) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003235 const SCEV* InVal = SE.getConstant(C);
3236 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003237 assert(isa<SCEVConstant>(Val) &&
3238 "Evaluation of SCEV at constant didn't fold correctly?");
3239 return cast<SCEVConstant>(Val)->getValue();
3240}
3241
3242/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3243/// and a GEP expression (missing the pointer index) indexing into it, return
3244/// the addressed element of the initializer or null if the index expression is
3245/// invalid.
3246static Constant *
3247GetAddressedElementFromGlobal(GlobalVariable *GV,
3248 const std::vector<ConstantInt*> &Indices) {
3249 Constant *Init = GV->getInitializer();
3250 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3251 uint64_t Idx = Indices[i]->getZExtValue();
3252 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3253 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3254 Init = cast<Constant>(CS->getOperand(Idx));
3255 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3256 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3257 Init = cast<Constant>(CA->getOperand(Idx));
3258 } else if (isa<ConstantAggregateZero>(Init)) {
3259 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3260 assert(Idx < STy->getNumElements() && "Bad struct index!");
3261 Init = Constant::getNullValue(STy->getElementType(Idx));
3262 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3263 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3264 Init = Constant::getNullValue(ATy->getElementType());
3265 } else {
3266 assert(0 && "Unknown constant aggregate type!");
3267 }
3268 return 0;
3269 } else {
3270 return 0; // Unknown initializer type
3271 }
3272 }
3273 return Init;
3274}
3275
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003276/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3277/// 'icmp op load X, cst', try to see if we can compute the backedge
3278/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003279const SCEV *
3280ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3281 LoadInst *LI,
3282 Constant *RHS,
3283 const Loop *L,
3284 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003285 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286
3287 // Check to see if the loaded pointer is a getelementptr of a global.
3288 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003289 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003290
3291 // Make sure that it is really a constant global we are gepping, with an
3292 // initializer, and make sure the first IDX is really 0.
3293 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3294 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3295 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3296 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003297 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003298
3299 // Okay, we allow one non-constant index into the GEP instruction.
3300 Value *VarIdx = 0;
3301 std::vector<ConstantInt*> Indexes;
3302 unsigned VarIdxNum = 0;
3303 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3304 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3305 Indexes.push_back(CI);
3306 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003307 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308 VarIdx = GEP->getOperand(i);
3309 VarIdxNum = i-2;
3310 Indexes.push_back(0);
3311 }
3312
3313 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3314 // Check to see if X is a loop variant variable value now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003315 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003316 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003317
3318 // We can only recognize very limited forms of loop index expressions, in
3319 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003320 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003321 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3322 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3323 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003324 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003325
3326 unsigned MaxSteps = MaxBruteForceIterations;
3327 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3328 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003329 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003330 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331
3332 // Form the GEP offset.
3333 Indexes[VarIdxNum] = Val;
3334
3335 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3336 if (Result == 0) break; // Cannot compute!
3337
3338 // Evaluate the condition for this iteration.
3339 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3340 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3341 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3342#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003343 errs() << "\n***\n*** Computed loop count " << *ItCst
3344 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3345 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346#endif
3347 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003348 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003349 }
3350 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003351 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003352}
3353
3354
3355/// CanConstantFold - Return true if we can constant fold an instruction of the
3356/// specified type, assuming that all operands were constants.
3357static bool CanConstantFold(const Instruction *I) {
3358 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3359 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3360 return true;
3361
3362 if (const CallInst *CI = dyn_cast<CallInst>(I))
3363 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003364 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 return false;
3366}
3367
3368/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3369/// in the loop that V is derived from. We allow arbitrary operations along the
3370/// way, but the operands of an operation must either be constants or a value
3371/// derived from a constant PHI. If this expression does not fit with these
3372/// constraints, return null.
3373static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3374 // If this is not an instruction, or if this is an instruction outside of the
3375 // loop, it can't be derived from a loop PHI.
3376 Instruction *I = dyn_cast<Instruction>(V);
3377 if (I == 0 || !L->contains(I->getParent())) return 0;
3378
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003379 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380 if (L->getHeader() == I->getParent())
3381 return PN;
3382 else
3383 // We don't currently keep track of the control flow needed to evaluate
3384 // PHIs, so we cannot handle PHIs inside of loops.
3385 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003386 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387
3388 // If we won't be able to constant fold this expression even if the operands
3389 // are constants, return early.
3390 if (!CanConstantFold(I)) return 0;
3391
3392 // Otherwise, we can evaluate this instruction if all of its operands are
3393 // constant or derived from a PHI node themselves.
3394 PHINode *PHI = 0;
3395 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3396 if (!(isa<Constant>(I->getOperand(Op)) ||
3397 isa<GlobalValue>(I->getOperand(Op)))) {
3398 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3399 if (P == 0) return 0; // Not evolving from PHI
3400 if (PHI == 0)
3401 PHI = P;
3402 else if (PHI != P)
3403 return 0; // Evolving from multiple different PHIs.
3404 }
3405
3406 // This is a expression evolving from a constant PHI!
3407 return PHI;
3408}
3409
3410/// EvaluateExpression - Given an expression that passes the
3411/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3412/// in the loop has the value PHIVal. If we can't fold this expression for some
3413/// reason, return null.
3414static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3415 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003416 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003417 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003418 Instruction *I = cast<Instruction>(V);
3419
3420 std::vector<Constant*> Operands;
3421 Operands.resize(I->getNumOperands());
3422
3423 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3424 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3425 if (Operands[i] == 0) return 0;
3426 }
3427
Chris Lattnerd6e56912007-12-10 22:53:04 +00003428 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3429 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3430 &Operands[0], Operands.size());
3431 else
3432 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3433 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003434}
3435
3436/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3437/// in the header of its containing loop, we know the loop executes a
3438/// constant number of times, and the PHI node is just a recurrence
3439/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003440Constant *
3441ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3442 const APInt& BEs,
3443 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 std::map<PHINode*, Constant*>::iterator I =
3445 ConstantEvolutionLoopExitValue.find(PN);
3446 if (I != ConstantEvolutionLoopExitValue.end())
3447 return I->second;
3448
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003449 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003450 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3451
3452 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3453
3454 // Since the loop is canonicalized, the PHI node must have two entries. One
3455 // entry must be a constant (coming in from outside of the loop), and the
3456 // second must be derived from the same PHI.
3457 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3458 Constant *StartCST =
3459 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3460 if (StartCST == 0)
3461 return RetVal = 0; // Must be a constant.
3462
3463 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3464 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3465 if (PN2 != PN)
3466 return RetVal = 0; // Not derived from same PHI.
3467
3468 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003469 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3471
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003472 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003473 unsigned IterationNum = 0;
3474 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3475 if (IterationNum == NumIterations)
3476 return RetVal = PHIVal; // Got exit value!
3477
3478 // Compute the value of the PHI node for the next iteration.
3479 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3480 if (NextPHI == PHIVal)
3481 return RetVal = NextPHI; // Stopped evolving!
3482 if (NextPHI == 0)
3483 return 0; // Couldn't evaluate!
3484 PHIVal = NextPHI;
3485 }
3486}
3487
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003488/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489/// constant number of times (the condition evolves only from constants),
3490/// try to evaluate a few iterations of the loop until we get the exit
3491/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003492/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003493const SCEV *
3494ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3495 Value *Cond,
3496 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003497 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003498 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499
3500 // Since the loop is canonicalized, the PHI node must have two entries. One
3501 // entry must be a constant (coming in from outside of the loop), and the
3502 // second must be derived from the same PHI.
3503 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3504 Constant *StartCST =
3505 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003506 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507
3508 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3509 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003510 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511
3512 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3513 // the loop symbolically to determine when the condition gets a value of
3514 // "ExitWhen".
3515 unsigned IterationNum = 0;
3516 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3517 for (Constant *PHIVal = StartCST;
3518 IterationNum != MaxIterations; ++IterationNum) {
3519 ConstantInt *CondVal =
3520 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3521
3522 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003523 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524
3525 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3526 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3527 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003528 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003529 }
3530
3531 // Compute the value of the PHI node for the next iteration.
3532 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3533 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003534 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003535 PHIVal = NextPHI;
3536 }
3537
3538 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003539 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003540}
3541
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003542/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3543/// at the specified scope in the program. The L value specifies a loop
3544/// nest to evaluate the expression at, where null is the top-level or a
3545/// specified loop is immediately inside of the loop.
3546///
3547/// This method can be used to compute the exit value for a variable defined
3548/// in a loop by querying what the value will hold in the parent loop.
3549///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003550/// In the case that a relevant loop exit value cannot be computed, the
3551/// original value V is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003552const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003553 // FIXME: this should be turned into a virtual method on SCEV!
3554
3555 if (isa<SCEVConstant>(V)) return V;
3556
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003557 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003559 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003560 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003561 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3563 if (PHINode *PN = dyn_cast<PHINode>(I))
3564 if (PN->getParent() == LI->getHeader()) {
3565 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003566 // to see if the loop that contains it has a known backedge-taken
3567 // count. If so, we may be able to force computation of the exit
3568 // value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003569 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003570 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003571 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572 // Okay, we know how many times the containing loop executes. If
3573 // this is a constant evolving PHI node, get the final value at
3574 // the specified iteration number.
3575 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003576 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003578 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579 }
3580 }
3581
3582 // Okay, this is an expression that we cannot symbolically evaluate
3583 // into a SCEV. Check to see if it's possible to symbolically evaluate
3584 // the arguments into constants, and if so, try to constant propagate the
3585 // result. This is particularly useful for computing loop exit values.
3586 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003587 // Check to see if we've folded this instruction at this loop before.
3588 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3589 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3590 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3591 if (!Pair.second)
3592 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003594 std::vector<Constant*> Operands;
3595 Operands.reserve(I->getNumOperands());
3596 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3597 Value *Op = I->getOperand(i);
3598 if (Constant *C = dyn_cast<Constant>(Op)) {
3599 Operands.push_back(C);
3600 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003601 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003602 // non-integer and non-pointer, don't even try to analyze them
3603 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003604 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003605 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003606
Owen Andersonecd0cd72009-06-22 21:39:50 +00003607 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003608 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003609 Constant *C = SC->getValue();
3610 if (C->getType() != Op->getType())
3611 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3612 Op->getType(),
3613 false),
3614 C, Op->getType());
3615 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003616 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003617 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3618 if (C->getType() != Op->getType())
3619 C =
3620 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3621 Op->getType(),
3622 false),
3623 C, Op->getType());
3624 Operands.push_back(C);
3625 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003626 return V;
3627 } else {
3628 return V;
3629 }
3630 }
3631 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003632
Chris Lattnerd6e56912007-12-10 22:53:04 +00003633 Constant *C;
3634 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3635 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3636 &Operands[0], Operands.size());
3637 else
3638 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3639 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003640 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003641 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003642 }
3643 }
3644
3645 // This is some other type of SCEVUnknown, just return it.
3646 return V;
3647 }
3648
Dan Gohmanc76b5452009-05-04 22:02:23 +00003649 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 // Avoid performing the look-up in the common case where the specified
3651 // expression has no loop-variant portions.
3652 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003653 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 // Okay, at least one of these operands is loop variant but might be
3656 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003657 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3658 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659 NewOps.push_back(OpAtScope);
3660
3661 for (++i; i != e; ++i) {
3662 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663 NewOps.push_back(OpAtScope);
3664 }
3665 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003666 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003667 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003668 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003669 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003670 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003671 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003672 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003673 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674 }
3675 }
3676 // If we got here, all operands are loop invariant.
3677 return Comm;
3678 }
3679
Dan Gohmanc76b5452009-05-04 22:02:23 +00003680 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003681 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3682 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003683 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3684 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003685 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 }
3687
3688 // If this is a loop recurrence for a loop that does not contain L, then we
3689 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003690 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3692 // To evaluate this recurrence, we need to know how many times the AddRec
3693 // loop iterates. Compute this now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003694 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003695 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696
Eli Friedman7489ec92008-08-04 23:49:06 +00003697 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003698 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003700 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003701 }
3702
Dan Gohmanc76b5452009-05-04 22:02:23 +00003703 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003704 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003705 if (Op == Cast->getOperand())
3706 return Cast; // must be loop invariant
3707 return getZeroExtendExpr(Op, Cast->getType());
3708 }
3709
Dan Gohmanc76b5452009-05-04 22:02:23 +00003710 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003711 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003712 if (Op == Cast->getOperand())
3713 return Cast; // must be loop invariant
3714 return getSignExtendExpr(Op, Cast->getType());
3715 }
3716
Dan Gohmanc76b5452009-05-04 22:02:23 +00003717 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003718 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003719 if (Op == Cast->getOperand())
3720 return Cast; // must be loop invariant
3721 return getTruncateExpr(Op, Cast->getType());
3722 }
3723
3724 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003725 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003726}
3727
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003728/// getSCEVAtScope - This is a convenience function which does
3729/// getSCEVAtScope(getSCEV(V), L).
Owen Andersonecd0cd72009-06-22 21:39:50 +00003730const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003731 return getSCEVAtScope(getSCEV(V), L);
3732}
3733
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003734/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3735/// following equation:
3736///
3737/// A * X = B (mod N)
3738///
3739/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3740/// A and B isn't important.
3741///
3742/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003743static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003744 ScalarEvolution &SE) {
3745 uint32_t BW = A.getBitWidth();
3746 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3747 assert(A != 0 && "A must be non-zero.");
3748
3749 // 1. D = gcd(A, N)
3750 //
3751 // The gcd of A and N may have only one prime factor: 2. The number of
3752 // trailing zeros in A is its multiplicity
3753 uint32_t Mult2 = A.countTrailingZeros();
3754 // D = 2^Mult2
3755
3756 // 2. Check if B is divisible by D.
3757 //
3758 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3759 // is not less than multiplicity of this prime factor for D.
3760 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003761 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003762
3763 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3764 // modulo (N / D).
3765 //
3766 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3767 // bit width during computations.
3768 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3769 APInt Mod(BW + 1, 0);
3770 Mod.set(BW - Mult2); // Mod = N / D
3771 APInt I = AD.multiplicativeInverse(Mod);
3772
3773 // 4. Compute the minimum unsigned root of the equation:
3774 // I * (B / D) mod (N / D)
3775 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3776
3777 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3778 // bits.
3779 return SE.getConstant(Result.trunc(BW));
3780}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781
3782/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3783/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3784/// might be the same) or two SCEVCouldNotCompute objects.
3785///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003786static std::pair<const SCEV*,const SCEV*>
Dan Gohman89f85052007-10-22 18:31:58 +00003787SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003788 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003789 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3790 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3791 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003792
3793 // We currently can only solve this if the coefficients are constants.
3794 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003795 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 return std::make_pair(CNC, CNC);
3797 }
3798
3799 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3800 const APInt &L = LC->getValue()->getValue();
3801 const APInt &M = MC->getValue()->getValue();
3802 const APInt &N = NC->getValue()->getValue();
3803 APInt Two(BitWidth, 2);
3804 APInt Four(BitWidth, 4);
3805
Dan Gohman9bc642f2009-06-24 04:48:43 +00003806 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 using namespace APIntOps;
3808 const APInt& C = L;
3809 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3810 // The B coefficient is M-N/2
3811 APInt B(M);
3812 B -= sdiv(N,Two);
3813
3814 // The A coefficient is N/2
3815 APInt A(N.sdiv(Two));
3816
3817 // Compute the B^2-4ac term.
3818 APInt SqrtTerm(B);
3819 SqrtTerm *= B;
3820 SqrtTerm -= Four * (A * C);
3821
3822 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3823 // integer value or else APInt::sqrt() will assert.
3824 APInt SqrtVal(SqrtTerm.sqrt());
3825
Dan Gohman9bc642f2009-06-24 04:48:43 +00003826 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003827 // The divisions must be performed as signed divisions.
3828 APInt NegB(-B);
3829 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003830 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003831 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003832 return std::make_pair(CNC, CNC);
3833 }
3834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003835 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3836 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3837
Dan Gohman9bc642f2009-06-24 04:48:43 +00003838 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003839 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 } // end APIntOps namespace
3841}
3842
3843/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003844/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003845const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003846 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003847 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003848 // If the value is already zero, the branch will execute zero times.
3849 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003850 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003851 }
3852
Dan Gohmanbff6b582009-05-04 22:30:44 +00003853 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003854 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003855 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003856
3857 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003858 // If this is an affine expression, the execution count of this branch is
3859 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003860 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003861 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003862 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003863 // equivalent to:
3864 //
3865 // Step*N = -Start (mod 2^BW)
3866 //
3867 // where BW is the common bit width of Start and Step.
3868
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003870 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3871 L->getParentLoop());
3872 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3873 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003874
Dan Gohmanc76b5452009-05-04 22:02:23 +00003875 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003876 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003878 // First, handle unitary steps.
3879 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003880 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003881 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3882 return Start; // N = Start (as unsigned)
3883
3884 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003885 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003886 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003887 -StartC->getValue()->getValue(),
3888 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003889 }
3890 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3891 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3892 // the quadratic equation to solve it.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003893 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003894 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003895 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3896 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003897 if (R1) {
3898#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003899 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3900 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003901#endif
3902 // Pick the smallest positive root value.
3903 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00003904 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003905 R1->getValue(), R2->getValue()))) {
3906 if (CB->getZExtValue() == false)
3907 std::swap(R1, R2); // R1 is the minimum root now.
3908
3909 // We can only use this value if the chrec ends up with an exact zero
3910 // value at this index. When solving for "X*X != 5", for example, we
3911 // should not accept a root of 2.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003912 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003913 if (Val->isZero())
3914 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003915 }
3916 }
3917 }
3918
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003919 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003920}
3921
3922/// HowFarToNonZero - Return the number of times a backedge checking the
3923/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003924/// CouldNotCompute
Owen Andersonecd0cd72009-06-22 21:39:50 +00003925const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003926 // Loops that look like: while (X == 0) are very strange indeed. We don't
3927 // handle them yet except for the trivial case. This could be expanded in the
3928 // future as needed.
3929
3930 // If the value is a constant, check to see if it is known to be non-zero
3931 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003932 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003933 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003934 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003935 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003936 }
3937
3938 // We could implement others, but I really doubt anyone writes loops like
3939 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003940 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003941}
3942
Dan Gohmanab157b22009-05-18 15:36:09 +00003943/// getLoopPredecessor - If the given loop's header has exactly one unique
3944/// predecessor outside the loop, return it. Otherwise return null.
3945///
3946BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3947 BasicBlock *Header = L->getHeader();
3948 BasicBlock *Pred = 0;
3949 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3950 PI != E; ++PI)
3951 if (!L->contains(*PI)) {
3952 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3953 Pred = *PI;
3954 }
3955 return Pred;
3956}
3957
Dan Gohman1cddf972008-09-15 22:18:04 +00003958/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3959/// (which may not be an immediate predecessor) which has exactly one
3960/// successor from which BB is reachable, or null if no such block is
3961/// found.
3962///
3963BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003964ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003965 // If the block has a unique predecessor, then there is no path from the
3966 // predecessor to the block that does not go through the direct edge
3967 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003968 if (BasicBlock *Pred = BB->getSinglePredecessor())
3969 return Pred;
3970
3971 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003972 // If the header has a unique predecessor outside the loop, it must be
3973 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003974 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003975 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003976
3977 return 0;
3978}
3979
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003980/// HasSameValue - SCEV structural equivalence is usually sufficient for
3981/// testing whether two expressions are equal, however for the purposes of
3982/// looking for a condition guarding a loop, it can be useful to be a little
3983/// more general, since a front-end may have replicated the controlling
3984/// expression.
3985///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003986static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003987 // Quick check to see if they are the same SCEV.
3988 if (A == B) return true;
3989
3990 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3991 // two different instructions with the same value. Check for this case.
3992 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3993 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3994 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3995 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3996 if (AI->isIdenticalTo(BI))
3997 return true;
3998
3999 // Otherwise assume they may have a different value.
4000 return false;
4001}
4002
Dan Gohmancacd2012009-02-12 22:19:27 +00004003/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00004004/// a conditional between LHS and RHS. This is used to help avoid max
4005/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004006bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00004007 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00004008 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004009 // Interpret a null as meaning no loop, where there is obviously no guard
4010 // (interprocedural conditions notwithstanding).
4011 if (!L) return false;
4012
Dan Gohmanab157b22009-05-18 15:36:09 +00004013 BasicBlock *Predecessor = getLoopPredecessor(L);
4014 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004015
Dan Gohmanab157b22009-05-18 15:36:09 +00004016 // Starting at the loop predecessor, climb up the predecessor chain, as long
4017 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004018 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004019 for (; Predecessor;
4020 PredecessorDest = Predecessor,
4021 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004022
4023 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004024 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004025 if (!LoopEntryPredicate ||
4026 LoopEntryPredicate->isUnconditional())
4027 continue;
4028
Dan Gohman423ed6c2009-06-24 01:18:18 +00004029 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4030 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004031 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004032 }
4033
Dan Gohmanab678fb2008-08-12 20:17:31 +00004034 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004035}
4036
Dan Gohman423ed6c2009-06-24 01:18:18 +00004037/// isNecessaryCond - Test whether the given CondValue value is a condition
4038/// which is at least as strict as the one described by Pred, LHS, and RHS.
4039bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4040 ICmpInst::Predicate Pred,
4041 const SCEV *LHS, const SCEV *RHS,
4042 bool Inverse) {
4043 // Recursivly handle And and Or conditions.
4044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4045 if (BO->getOpcode() == Instruction::And) {
4046 if (!Inverse)
4047 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4048 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4049 } else if (BO->getOpcode() == Instruction::Or) {
4050 if (Inverse)
4051 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4052 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4053 }
4054 }
4055
4056 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4057 if (!ICI) return false;
4058
4059 // Now that we found a conditional branch that dominates the loop, check to
4060 // see if it is the comparison we are looking for.
4061 Value *PreCondLHS = ICI->getOperand(0);
4062 Value *PreCondRHS = ICI->getOperand(1);
4063 ICmpInst::Predicate Cond;
4064 if (Inverse)
4065 Cond = ICI->getInversePredicate();
4066 else
4067 Cond = ICI->getPredicate();
4068
4069 if (Cond == Pred)
4070 ; // An exact match.
4071 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4072 ; // The actual condition is beyond sufficient.
4073 else
4074 // Check a few special cases.
4075 switch (Cond) {
4076 case ICmpInst::ICMP_UGT:
4077 if (Pred == ICmpInst::ICMP_ULT) {
4078 std::swap(PreCondLHS, PreCondRHS);
4079 Cond = ICmpInst::ICMP_ULT;
4080 break;
4081 }
4082 return false;
4083 case ICmpInst::ICMP_SGT:
4084 if (Pred == ICmpInst::ICMP_SLT) {
4085 std::swap(PreCondLHS, PreCondRHS);
4086 Cond = ICmpInst::ICMP_SLT;
4087 break;
4088 }
4089 return false;
4090 case ICmpInst::ICMP_NE:
4091 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4092 // so check for this case by checking if the NE is comparing against
4093 // a minimum or maximum constant.
4094 if (!ICmpInst::isTrueWhenEqual(Pred))
4095 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4096 const APInt &A = CI->getValue();
4097 switch (Pred) {
4098 case ICmpInst::ICMP_SLT:
4099 if (A.isMaxSignedValue()) break;
4100 return false;
4101 case ICmpInst::ICMP_SGT:
4102 if (A.isMinSignedValue()) break;
4103 return false;
4104 case ICmpInst::ICMP_ULT:
4105 if (A.isMaxValue()) break;
4106 return false;
4107 case ICmpInst::ICMP_UGT:
4108 if (A.isMinValue()) break;
4109 return false;
4110 default:
4111 return false;
4112 }
4113 Cond = ICmpInst::ICMP_NE;
4114 // NE is symmetric but the original comparison may not be. Swap
4115 // the operands if necessary so that they match below.
4116 if (isa<SCEVConstant>(LHS))
4117 std::swap(PreCondLHS, PreCondRHS);
4118 break;
4119 }
4120 return false;
4121 default:
4122 // We weren't able to reconcile the condition.
4123 return false;
4124 }
4125
4126 if (!PreCondLHS->getType()->isInteger()) return false;
4127
4128 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4129 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4130 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4131 HasSameValue(RHS, PreCondRHSSCEV)) ||
4132 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4133 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4134}
4135
Dan Gohmand2b62c42009-06-21 23:46:38 +00004136/// getBECount - Subtract the end and start values and divide by the step,
4137/// rounding up, to get the number of times the backedge is executed. Return
4138/// CouldNotCompute if an intermediate computation overflows.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004139const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
4140 const SCEV* End,
4141 const SCEV* Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004142 const Type *Ty = Start->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00004143 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
4144 const SCEV* Diff = getMinusSCEV(End, Start);
4145 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004146
4147 // Add an adjustment to the difference between End and Start so that
4148 // the division will effectively round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004149 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004150
4151 // Check Add for unsigned overflow.
4152 // TODO: More sophisticated things could be done here.
4153 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Andersonecd0cd72009-06-22 21:39:50 +00004154 const SCEV* OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004155 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4156 getZeroExtendExpr(RoundUp, WideTy));
4157 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004158 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004159
4160 return getUDivExpr(Add, Step);
4161}
4162
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163/// HowManyLessThans - Return the number of times a backedge containing the
4164/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004165/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004166ScalarEvolution::BackedgeTakenInfo
4167ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4168 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004169 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004170 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004171
Dan Gohmanbff6b582009-05-04 22:30:44 +00004172 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004173 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004174 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004175
4176 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004177 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004178 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004179 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004180
4181 // TODO: handle non-constant strides.
4182 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4183 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004184 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004185 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004186 // With unit stride, the iteration never steps past the limit value.
4187 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4188 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4189 // Test whether a positive iteration iteration can step past the limit
4190 // value and past the maximum value for its type in a single step.
4191 if (isSigned) {
4192 APInt Max = APInt::getSignedMaxValue(BitWidth);
4193 if ((Max - CStep->getValue()->getValue())
4194 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004195 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004196 } else {
4197 APInt Max = APInt::getMaxValue(BitWidth);
4198 if ((Max - CStep->getValue()->getValue())
4199 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004200 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004201 }
4202 } else
4203 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004204 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004205 } else
4206 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004207 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004209 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4210 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4211 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004212 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004214 // First, we get the value of the LHS in the first iteration: n
Owen Andersonecd0cd72009-06-22 21:39:50 +00004215 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004216
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004217 // Determine the minimum constant start value.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004218 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004219 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4220 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004221
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004222 // If we know that the condition is true in order to enter the loop,
4223 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004224 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4225 // the division must round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004226 const SCEV* End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004227 if (!isLoopGuardedByCond(L,
4228 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4229 getMinusSCEV(Start, Step), RHS))
4230 End = isSigned ? getSMaxExpr(RHS, Start)
4231 : getUMaxExpr(RHS, Start);
4232
4233 // Determine the maximum constant end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004234 const SCEV* MaxEnd =
Dan Gohman92369c32009-06-20 00:32:22 +00004235 isa<SCEVConstant>(End) ? End :
4236 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4237 .ashr(GetMinSignBits(End) - 1) :
4238 APInt::getMaxValue(BitWidth)
4239 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004240
4241 // Finally, we subtract these two values and divide, rounding up, to get
4242 // the number of times the backedge is executed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004243 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004244
4245 // The maximum backedge count is similar, except using the minimum start
4246 // value and the maximum end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004247 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004248
4249 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004250 }
4251
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004252 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253}
4254
4255/// getNumIterationsInRange - Return the number of iterations of this loop that
4256/// produce values in the specified constant range. Another way of looking at
4257/// this is that it returns the first iteration number where the value is not in
4258/// the condition, thus computing the exit count. If the iteration count can't
4259/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004260const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004261 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004262 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004263 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264
4265 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004266 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004267 if (!SC->getValue()->isZero()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00004268 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004269 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004270 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004271 if (const SCEVAddRecExpr *ShiftedAddRec =
4272 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004273 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004274 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004275 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004276 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004277 }
4278
4279 // The only time we can solve this is when we have all constant indices.
4280 // Otherwise, we cannot determine the overflow conditions.
4281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4282 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004283 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004284
4285
4286 // Okay at this point we know that all elements of the chrec are constants and
4287 // that the start element is zero.
4288
4289 // First check to see if the range contains zero. If not, the first
4290 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004291 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004292 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004293 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004294
4295 if (isAffine()) {
4296 // If this is an affine expression then we have this situation:
4297 // Solve {0,+,A} in Range === Ax in Range
4298
4299 // We know that zero is in the range. If A is positive then we know that
4300 // the upper value of the range must be the first possible exit value.
4301 // If A is negative then the lower of the range is the last possible loop
4302 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004303 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004304 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4305 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4306
4307 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004308 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004309 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4310
4311 // Evaluate at the exit value. If we really did fall out of the valid
4312 // range, then we computed our trip count, otherwise wrap around or other
4313 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004314 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004316 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004317
4318 // Ensure that the previous value is in the range. This is a sanity check.
4319 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004320 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004321 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004323 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004324 } else if (isQuadratic()) {
4325 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4326 // quadratic equation to solve it. To do this, we must frame our problem in
4327 // terms of figuring out when zero is crossed, instead of when
4328 // Range.getUpper() is crossed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004329 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004330 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Andersonecd0cd72009-06-22 21:39:50 +00004331 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004332
4333 // Next, solve the constructed addrec
Owen Andersonecd0cd72009-06-22 21:39:50 +00004334 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004335 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004336 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4337 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004338 if (R1) {
4339 // Pick the smallest positive root value.
4340 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00004341 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004342 R1->getValue(), R2->getValue()))) {
4343 if (CB->getZExtValue() == false)
4344 std::swap(R1, R2); // R1 is the minimum root now.
4345
4346 // Make sure the root is not off by one. The returned iteration should
4347 // not be in the range, but the previous one should be. When solving
4348 // for "X*X < 5", for example, we should not return a root of 2.
4349 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004350 R1->getValue(),
4351 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004352 if (Range.contains(R1Val->getValue())) {
4353 // The next iteration must be out of the range...
4354 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4355
Dan Gohman89f85052007-10-22 18:31:58 +00004356 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004358 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004359 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004360 }
4361
4362 // If R1 was not in the range, then it is a good return value. Make
4363 // sure that R1-1 WAS in the range though, just in case.
4364 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004365 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004366 if (Range.contains(R1Val->getValue()))
4367 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004368 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004369 }
4370 }
4371 }
4372
Dan Gohman0ad08b02009-04-18 17:58:19 +00004373 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004374}
4375
4376
4377
4378//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004379// SCEVCallbackVH Class Implementation
4380//===----------------------------------------------------------------------===//
4381
Dan Gohman999d14e2009-05-19 19:22:47 +00004382void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004383 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4384 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4385 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004386 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4387 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004388 SE->Scalars.erase(getValPtr());
4389 // this now dangles!
4390}
4391
Dan Gohman999d14e2009-05-19 19:22:47 +00004392void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004393 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4394
4395 // Forget all the expressions associated with users of the old value,
4396 // so that future queries will recompute the expressions using the new
4397 // value.
4398 SmallVector<User *, 16> Worklist;
4399 Value *Old = getValPtr();
4400 bool DeleteOld = false;
4401 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4402 UI != UE; ++UI)
4403 Worklist.push_back(*UI);
4404 while (!Worklist.empty()) {
4405 User *U = Worklist.pop_back_val();
4406 // Deleting the Old value will cause this to dangle. Postpone
4407 // that until everything else is done.
4408 if (U == Old) {
4409 DeleteOld = true;
4410 continue;
4411 }
4412 if (PHINode *PN = dyn_cast<PHINode>(U))
4413 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004414 if (Instruction *I = dyn_cast<Instruction>(U))
4415 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004416 if (SE->Scalars.erase(U))
4417 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4418 UI != UE; ++UI)
4419 Worklist.push_back(*UI);
4420 }
4421 if (DeleteOld) {
4422 if (PHINode *PN = dyn_cast<PHINode>(Old))
4423 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004424 if (Instruction *I = dyn_cast<Instruction>(Old))
4425 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004426 SE->Scalars.erase(Old);
4427 // this now dangles!
4428 }
4429 // this may dangle!
4430}
4431
Dan Gohman999d14e2009-05-19 19:22:47 +00004432ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004433 : CallbackVH(V), SE(se) {}
4434
4435//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436// ScalarEvolution Class Implementation
4437//===----------------------------------------------------------------------===//
4438
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004439ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004440 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004441}
4442
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004444 this->F = &F;
4445 LI = &getAnalysis<LoopInfo>();
4446 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 return false;
4448}
4449
4450void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004451 Scalars.clear();
4452 BackedgeTakenCounts.clear();
4453 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004454 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004455 UniqueSCEVs.clear();
4456 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004457}
4458
4459void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4460 AU.setPreservesAll();
4461 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004462}
4463
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004464bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004465 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004466}
4467
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004468static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004469 const Loop *L) {
4470 // Print all inner loops first
4471 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4472 PrintLoopInfo(OS, SE, *I);
4473
Nick Lewyckye5da1912008-01-02 02:49:20 +00004474 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004475
Devang Patel02451fa2007-08-21 00:31:24 +00004476 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004477 L->getExitBlocks(ExitBlocks);
4478 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004479 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004480
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004481 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4482 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004483 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004484 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004485 }
4486
Nick Lewyckye5da1912008-01-02 02:49:20 +00004487 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004488 OS << "Loop " << L->getHeader()->getName() << ": ";
4489
4490 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4491 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4492 } else {
4493 OS << "Unpredictable max backedge-taken count. ";
4494 }
4495
4496 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004497}
4498
Dan Gohman13058cc2009-04-21 00:47:46 +00004499void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004500 // ScalarEvolution's implementaiton of the print method is to print
4501 // out SCEV values of all instructions that are interesting. Doing
4502 // this potentially causes it to create new SCEV objects though,
4503 // which technically conflicts with the const qualifier. This isn't
4504 // observable from outside the class though (the hasSCEV function
4505 // notwithstanding), so casting away the const isn't dangerous.
4506 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004507
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004508 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004509 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004510 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004511 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004512 OS << " --> ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004513 const SCEV* SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004514 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004515
Dan Gohman8db598a2009-06-19 17:49:54 +00004516 const Loop *L = LI->getLoopFor((*I).getParent());
4517
Owen Andersonecd0cd72009-06-22 21:39:50 +00004518 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004519 if (AtUse != SV) {
4520 OS << " --> ";
4521 AtUse->print(OS);
4522 }
4523
4524 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004525 OS << "\t\t" "Exits: ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004526 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004527 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004528 OS << "<<Unknown>>";
4529 } else {
4530 OS << *ExitValue;
4531 }
4532 }
4533
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534 OS << "\n";
4535 }
4536
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004537 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4538 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4539 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004540}
Dan Gohman13058cc2009-04-21 00:47:46 +00004541
4542void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4543 raw_os_ostream OS(o);
4544 print(OS, M);
4545}