blob: e38b24c0b5763850d62bec91ca9bfdf1a4eaeaec [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 Gohman3bf01f02009-06-29 18:25:52 +00001051 M.insert(std::make_pair(Key, NewScale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001052 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001053 NewOps.push_back(Pair.first->first);
1054 } else {
1055 Pair.first->second += NewScale;
1056 // The map already had an entry for this value, which may indicate
1057 // a folding opportunity.
1058 Interesting = true;
1059 }
1060 }
1061 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1062 // Pull a buried constant out to the outside.
1063 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1064 Interesting = true;
1065 AccumulatedConstant += Scale * C->getValue()->getValue();
1066 } else {
1067 // An ordinary operand. Update the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001068 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001069 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001070 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001071 NewOps.push_back(Pair.first->first);
1072 } else {
1073 Pair.first->second += Scale;
1074 // The map already had an entry for this value, which may indicate
1075 // a folding opportunity.
1076 Interesting = true;
1077 }
1078 }
1079 }
1080
1081 return Interesting;
1082}
1083
1084namespace {
1085 struct APIntCompare {
1086 bool operator()(const APInt &LHS, const APInt &RHS) const {
1087 return LHS.ult(RHS);
1088 }
1089 };
1090}
1091
Dan Gohmanc8a29272009-05-24 23:45:28 +00001092/// getAddExpr - Get a canonical add expression, or something simpler if
1093/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001094const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 assert(!Ops.empty() && "Cannot get empty add!");
1096 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001097#ifndef NDEBUG
1098 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1099 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1100 getEffectiveSCEVType(Ops[0]->getType()) &&
1101 "SCEVAddExpr operand types don't match!");
1102#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103
1104 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001105 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106
1107 // If there are any constants, fold them together.
1108 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001109 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 ++Idx;
1111 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001112 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001114 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1115 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001116 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001117 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001118 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 }
1120
1121 // If we are left with a constant zero being added, strip it off.
1122 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1123 Ops.erase(Ops.begin());
1124 --Idx;
1125 }
1126 }
1127
1128 if (Ops.size() == 1) return Ops[0];
1129
1130 // Okay, check to see if the same value occurs in the operand list twice. If
1131 // so, merge them together into an multiply expression. Since we sorted the
1132 // list, these values are required to be adjacent.
1133 const Type *Ty = Ops[0]->getType();
1134 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1135 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1136 // Found a match, merge the two values into a multiply, and add any
1137 // remaining values to the result.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001138 const SCEV* Two = getIntegerSCEV(2, Ty);
1139 const SCEV* Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 if (Ops.size() == 2)
1141 return Mul;
1142 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1143 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001144 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 }
1146
Dan Gohman45b3b542009-05-08 21:03:19 +00001147 // Check for truncates. If all the operands are truncated from the same
1148 // type, see if factoring out the truncate would permit the result to be
1149 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1150 // if the contents of the resulting outer trunc fold to something simple.
1151 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1152 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1153 const Type *DstType = Trunc->getType();
1154 const Type *SrcType = Trunc->getOperand()->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00001155 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001156 bool Ok = true;
1157 // Check all the operands to see if they can be represented in the
1158 // source type of the truncate.
1159 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1160 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1161 if (T->getOperand()->getType() != SrcType) {
1162 Ok = false;
1163 break;
1164 }
1165 LargeOps.push_back(T->getOperand());
1166 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1167 // This could be either sign or zero extension, but sign extension
1168 // is much more likely to be foldable here.
1169 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1170 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001171 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001172 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1173 if (const SCEVTruncateExpr *T =
1174 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1175 if (T->getOperand()->getType() != SrcType) {
1176 Ok = false;
1177 break;
1178 }
1179 LargeMulOps.push_back(T->getOperand());
1180 } else if (const SCEVConstant *C =
1181 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1182 // This could be either sign or zero extension, but sign extension
1183 // is much more likely to be foldable here.
1184 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1185 } else {
1186 Ok = false;
1187 break;
1188 }
1189 }
1190 if (Ok)
1191 LargeOps.push_back(getMulExpr(LargeMulOps));
1192 } else {
1193 Ok = false;
1194 break;
1195 }
1196 }
1197 if (Ok) {
1198 // Evaluate the expression in the larger type.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001199 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001200 // If it folds to something simple, use it. Otherwise, don't.
1201 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1202 return getTruncateExpr(Fold, DstType);
1203 }
1204 }
1205
1206 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1208 ++Idx;
1209
1210 // If there are add operands they would be next.
1211 if (Idx < Ops.size()) {
1212 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001213 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 // If we have an add, expand the add operands onto the end of the operands
1215 // list.
1216 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1217 Ops.erase(Ops.begin()+Idx);
1218 DeletedAdd = true;
1219 }
1220
1221 // If we deleted at least one add, we added operands to the end of the list,
1222 // and they are not necessarily sorted. Recurse to resort and resimplify
1223 // any operands we just aquired.
1224 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001225 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 }
1227
1228 // Skip over the add expression until we get to a multiply.
1229 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1230 ++Idx;
1231
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001232 // Check to see if there are any folding opportunities present with
1233 // operands multiplied by constant values.
1234 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1235 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001236 DenseMap<const SCEV*, APInt> M;
1237 SmallVector<const SCEV*, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001238 APInt AccumulatedConstant(BitWidth, 0);
1239 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1240 Ops, APInt(BitWidth, 1), *this)) {
1241 // Some interesting folding opportunity is present, so its worthwhile to
1242 // re-generate the operands list. Group the operands by constant scale,
1243 // to avoid multiplying by the same constant scale multiple times.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001244 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1245 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001246 E = NewOps.end(); I != E; ++I)
1247 MulOpLists[M.find(*I)->second].push_back(*I);
1248 // Re-generate the operands list.
1249 Ops.clear();
1250 if (AccumulatedConstant != 0)
1251 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001252 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1253 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001254 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001255 Ops.push_back(getMulExpr(getConstant(I->first),
1256 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001257 if (Ops.empty())
1258 return getIntegerSCEV(0, Ty);
1259 if (Ops.size() == 1)
1260 return Ops[0];
1261 return getAddExpr(Ops);
1262 }
1263 }
1264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 // If we are adding something to a multiply expression, make sure the
1266 // something is not already an operand of the multiply. If so, merge it into
1267 // the multiply.
1268 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001269 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001271 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001273 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001275 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 if (Mul->getNumOperands() != 2) {
1277 // If the multiply has more than two operands, we must get the
1278 // Y*Z term.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001279 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001281 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001283 const SCEV* One = getIntegerSCEV(1, Ty);
1284 const SCEV* AddOne = getAddExpr(InnerMul, One);
1285 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 if (Ops.size() == 2) return OuterMul;
1287 if (AddOp < Idx) {
1288 Ops.erase(Ops.begin()+AddOp);
1289 Ops.erase(Ops.begin()+Idx-1);
1290 } else {
1291 Ops.erase(Ops.begin()+Idx);
1292 Ops.erase(Ops.begin()+AddOp-1);
1293 }
1294 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001295 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 }
1297
1298 // Check this multiply against other multiplies being added together.
1299 for (unsigned OtherMulIdx = Idx+1;
1300 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1301 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001302 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 // If MulOp occurs in OtherMul, we can fold the two multiplies
1304 // together.
1305 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1306 OMulOp != e; ++OMulOp)
1307 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1308 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001309 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001311 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1312 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001314 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001316 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001318 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1319 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001321 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001323 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1324 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 if (Ops.size() == 2) return OuterMul;
1326 Ops.erase(Ops.begin()+Idx);
1327 Ops.erase(Ops.begin()+OtherMulIdx-1);
1328 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001329 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 }
1331 }
1332 }
1333 }
1334
1335 // If there are any add recurrences in the operands list, see if any other
1336 // added values are loop invariant. If so, we can fold them into the
1337 // recurrence.
1338 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1339 ++Idx;
1340
1341 // Scan over all recurrences, trying to fold loop invariants into them.
1342 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1343 // Scan all of the other operands to this add and add them to the vector if
1344 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001345 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001346 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1348 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1349 LIOps.push_back(Ops[i]);
1350 Ops.erase(Ops.begin()+i);
1351 --i; --e;
1352 }
1353
1354 // If we found some loop invariants, fold them into the recurrence.
1355 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001356 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 LIOps.push_back(AddRec->getStart());
1358
Owen Andersonecd0cd72009-06-22 21:39:50 +00001359 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001360 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001361 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362
Owen Andersonecd0cd72009-06-22 21:39:50 +00001363 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 // If all of the other operands were loop invariant, we are done.
1365 if (Ops.size() == 1) return NewRec;
1366
1367 // Otherwise, add the folded AddRec by the non-liv parts.
1368 for (unsigned i = 0;; ++i)
1369 if (Ops[i] == AddRec) {
1370 Ops[i] = NewRec;
1371 break;
1372 }
Dan Gohman89f85052007-10-22 18:31:58 +00001373 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 }
1375
1376 // Okay, if there weren't any loop invariants to be folded, check to see if
1377 // there are multiple AddRec's with the same loop induction variable being
1378 // added together. If so, we can fold them.
1379 for (unsigned OtherIdx = Idx+1;
1380 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1381 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001382 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1384 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001385 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1386 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1388 if (i >= NewOps.size()) {
1389 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1390 OtherAddRec->op_end());
1391 break;
1392 }
Dan Gohman89f85052007-10-22 18:31:58 +00001393 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001395 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396
1397 if (Ops.size() == 2) return NewAddRec;
1398
1399 Ops.erase(Ops.begin()+Idx);
1400 Ops.erase(Ops.begin()+OtherIdx-1);
1401 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001402 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 }
1404 }
1405
1406 // Otherwise couldn't fold anything into this recurrence. Move onto the
1407 // next one.
1408 }
1409
1410 // Okay, it looks like we really DO need an add expr. Check to see if we
1411 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001412 FoldingSetNodeID ID;
1413 ID.AddInteger(scAddExpr);
1414 ID.AddInteger(Ops.size());
1415 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1416 ID.AddPointer(Ops[i]);
1417 void *IP = 0;
1418 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1419 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1420 new (S) SCEVAddExpr(Ops);
1421 UniqueSCEVs.InsertNode(S, IP);
1422 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423}
1424
1425
Dan Gohmanc8a29272009-05-24 23:45:28 +00001426/// getMulExpr - Get a canonical multiply expression, or something simpler if
1427/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001428const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001430#ifndef NDEBUG
1431 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1432 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1433 getEffectiveSCEVType(Ops[0]->getType()) &&
1434 "SCEVMulExpr operand types don't match!");
1435#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436
1437 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001438 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439
1440 // If there are any constants, fold them together.
1441 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001442 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443
1444 // C1*(C2+V) -> C1*C2 + C1*V
1445 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001446 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 if (Add->getNumOperands() == 2 &&
1448 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001449 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1450 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451
1452
1453 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001454 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001456 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001457 RHSC->getValue()->getValue());
1458 Ops[0] = getConstant(Fold);
1459 Ops.erase(Ops.begin()+1); // Erase the folded element
1460 if (Ops.size() == 1) return Ops[0];
1461 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462 }
1463
1464 // If we are left with a constant one being multiplied, strip it off.
1465 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1466 Ops.erase(Ops.begin());
1467 --Idx;
1468 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1469 // If we have a multiply of zero, it will always be zero.
1470 return Ops[0];
1471 }
1472 }
1473
1474 // Skip over the add expression until we get to a multiply.
1475 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1476 ++Idx;
1477
1478 if (Ops.size() == 1)
1479 return Ops[0];
1480
1481 // If there are mul operands inline them all into this expression.
1482 if (Idx < Ops.size()) {
1483 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001484 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485 // If we have an mul, expand the mul operands onto the end of the operands
1486 // list.
1487 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1488 Ops.erase(Ops.begin()+Idx);
1489 DeletedMul = true;
1490 }
1491
1492 // If we deleted at least one mul, we added operands to the end of the list,
1493 // and they are not necessarily sorted. Recurse to resort and resimplify
1494 // any operands we just aquired.
1495 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001496 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001497 }
1498
1499 // If there are any add recurrences in the operands list, see if any other
1500 // added values are loop invariant. If so, we can fold them into the
1501 // recurrence.
1502 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1503 ++Idx;
1504
1505 // Scan over all recurrences, trying to fold loop invariants into them.
1506 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1507 // Scan all of the other operands to this mul and add them to the vector if
1508 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001509 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001510 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1512 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1513 LIOps.push_back(Ops[i]);
1514 Ops.erase(Ops.begin()+i);
1515 --i; --e;
1516 }
1517
1518 // If we found some loop invariants, fold them into the recurrence.
1519 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001520 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Andersonecd0cd72009-06-22 21:39:50 +00001521 SmallVector<const SCEV*, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522 NewOps.reserve(AddRec->getNumOperands());
1523 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001524 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001526 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001527 } else {
1528 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001529 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001531 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 }
1533 }
1534
Owen Andersonecd0cd72009-06-22 21:39:50 +00001535 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536
1537 // If all of the other operands were loop invariant, we are done.
1538 if (Ops.size() == 1) return NewRec;
1539
1540 // Otherwise, multiply the folded AddRec by the non-liv parts.
1541 for (unsigned i = 0;; ++i)
1542 if (Ops[i] == AddRec) {
1543 Ops[i] = NewRec;
1544 break;
1545 }
Dan Gohman89f85052007-10-22 18:31:58 +00001546 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 }
1548
1549 // Okay, if there weren't any loop invariants to be folded, check to see if
1550 // there are multiple AddRec's with the same loop induction variable being
1551 // multiplied together. If so, we can fold them.
1552 for (unsigned OtherIdx = Idx+1;
1553 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1554 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001555 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1557 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001558 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001559 const SCEV* NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 G->getStart());
Owen Andersonecd0cd72009-06-22 21:39:50 +00001561 const SCEV* B = F->getStepRecurrence(*this);
1562 const SCEV* D = G->getStepRecurrence(*this);
1563 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001564 getMulExpr(G, B),
1565 getMulExpr(B, D));
Owen Andersonecd0cd72009-06-22 21:39:50 +00001566 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001567 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001568 if (Ops.size() == 2) return NewAddRec;
1569
1570 Ops.erase(Ops.begin()+Idx);
1571 Ops.erase(Ops.begin()+OtherIdx-1);
1572 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001573 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001574 }
1575 }
1576
1577 // Otherwise couldn't fold anything into this recurrence. Move onto the
1578 // next one.
1579 }
1580
1581 // Okay, it looks like we really DO need an mul expr. Check to see if we
1582 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001583 FoldingSetNodeID ID;
1584 ID.AddInteger(scMulExpr);
1585 ID.AddInteger(Ops.size());
1586 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1587 ID.AddPointer(Ops[i]);
1588 void *IP = 0;
1589 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1590 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1591 new (S) SCEVMulExpr(Ops);
1592 UniqueSCEVs.InsertNode(S, IP);
1593 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594}
1595
Dan Gohmanc8a29272009-05-24 23:45:28 +00001596/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1597/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001598const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1599 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001600 assert(getEffectiveSCEVType(LHS->getType()) ==
1601 getEffectiveSCEVType(RHS->getType()) &&
1602 "SCEVUDivExpr operand types don't match!");
1603
Dan Gohmanc76b5452009-05-04 22:02:23 +00001604 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001606 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001607 if (RHSC->isZero())
1608 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001609
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001610 // Determine if the division can be folded into the operands of
1611 // its operands.
1612 // TODO: Generalize this to non-constants by using known-bits information.
1613 const Type *Ty = LHS->getType();
1614 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1615 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1616 // For non-power-of-two values, effectively round the value up to the
1617 // nearest power of two.
1618 if (!RHSC->getValue()->getValue().isPowerOf2())
1619 ++MaxShiftAmt;
1620 const IntegerType *ExtTy =
1621 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1622 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1623 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1624 if (const SCEVConstant *Step =
1625 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1626 if (!Step->getValue()->getValue()
1627 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001628 getZeroExtendExpr(AR, ExtTy) ==
1629 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1630 getZeroExtendExpr(Step, ExtTy),
1631 AR->getLoop())) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001632 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001633 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1634 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1635 return getAddRecExpr(Operands, AR->getLoop());
1636 }
1637 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001638 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001639 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001640 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1641 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1642 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001643 // Find an operand that's safely divisible.
1644 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001645 const SCEV* Op = M->getOperand(i);
1646 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001647 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001648 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1649 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001650 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001651 Operands[i] = Div;
1652 return getMulExpr(Operands);
1653 }
1654 }
Dan Gohman14374d32009-05-08 23:11:16 +00001655 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001656 // (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 +00001657 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001658 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001659 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1660 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1661 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1662 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001663 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001664 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001665 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1666 break;
1667 Operands.push_back(Op);
1668 }
1669 if (Operands.size() == A->getNumOperands())
1670 return getAddExpr(Operands);
1671 }
Dan Gohman14374d32009-05-08 23:11:16 +00001672 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001673
1674 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001675 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 Constant *LHSCV = LHSC->getValue();
1677 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001678 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1679 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 }
1681 }
1682
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001683 FoldingSetNodeID ID;
1684 ID.AddInteger(scUDivExpr);
1685 ID.AddPointer(LHS);
1686 ID.AddPointer(RHS);
1687 void *IP = 0;
1688 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1689 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1690 new (S) SCEVUDivExpr(LHS, RHS);
1691 UniqueSCEVs.InsertNode(S, IP);
1692 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693}
1694
1695
Dan Gohmanc8a29272009-05-24 23:45:28 +00001696/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1697/// Simplify the expression as much as possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001698const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1699 const SCEV* Step, const Loop *L) {
1700 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001702 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 if (StepChrec->getLoop() == L) {
1704 Operands.insert(Operands.end(), StepChrec->op_begin(),
1705 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001706 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001707 }
1708
1709 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001710 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001711}
1712
Dan Gohmanc8a29272009-05-24 23:45:28 +00001713/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1714/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001715const SCEV *
1716ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
1717 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001718 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001719#ifndef NDEBUG
1720 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1721 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1722 getEffectiveSCEVType(Operands[0]->getType()) &&
1723 "SCEVAddRecExpr operand types don't match!");
1724#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725
Dan Gohman7b560c42008-06-18 16:23:07 +00001726 if (Operands.back()->isZero()) {
1727 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001728 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001729 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001730
Dan Gohman42936882008-08-08 18:33:12 +00001731 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001732 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001733 const Loop* NestedLoop = NestedAR->getLoop();
1734 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001735 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001736 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001737 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001738 // AddRecs require their operands be loop-invariant with respect to their
1739 // loops. Don't perform this transformation if it would break this
1740 // requirement.
1741 bool AllInvariant = true;
1742 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1743 if (!Operands[i]->isLoopInvariant(L)) {
1744 AllInvariant = false;
1745 break;
1746 }
1747 if (AllInvariant) {
1748 NestedOperands[0] = getAddRecExpr(Operands, L);
1749 AllInvariant = true;
1750 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1751 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1752 AllInvariant = false;
1753 break;
1754 }
1755 if (AllInvariant)
1756 // Ok, both add recurrences are valid after the transformation.
1757 return getAddRecExpr(NestedOperands, NestedLoop);
1758 }
1759 // Reset Operands to its original state.
1760 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001761 }
1762 }
1763
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001764 FoldingSetNodeID ID;
1765 ID.AddInteger(scAddRecExpr);
1766 ID.AddInteger(Operands.size());
1767 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1768 ID.AddPointer(Operands[i]);
1769 ID.AddPointer(L);
1770 void *IP = 0;
1771 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1772 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1773 new (S) SCEVAddRecExpr(Operands, L);
1774 UniqueSCEVs.InsertNode(S, IP);
1775 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776}
1777
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001778const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1779 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001780 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001781 Ops.push_back(LHS);
1782 Ops.push_back(RHS);
1783 return getSMaxExpr(Ops);
1784}
1785
Owen Andersonecd0cd72009-06-22 21:39:50 +00001786const SCEV*
1787ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001788 assert(!Ops.empty() && "Cannot get empty smax!");
1789 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001790#ifndef NDEBUG
1791 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1792 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1793 getEffectiveSCEVType(Ops[0]->getType()) &&
1794 "SCEVSMaxExpr operand types don't match!");
1795#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001796
1797 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001798 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001799
1800 // If there are any constants, fold them together.
1801 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001802 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001803 ++Idx;
1804 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001805 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001806 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001807 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001808 APIntOps::smax(LHSC->getValue()->getValue(),
1809 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001810 Ops[0] = getConstant(Fold);
1811 Ops.erase(Ops.begin()+1); // Erase the folded element
1812 if (Ops.size() == 1) return Ops[0];
1813 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001814 }
1815
Dan Gohmand156c092009-06-24 14:46:22 +00001816 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001817 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1818 Ops.erase(Ops.begin());
1819 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001820 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1821 // If we have an smax with a constant maximum-int, it will always be
1822 // maximum-int.
1823 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001824 }
1825 }
1826
1827 if (Ops.size() == 1) return Ops[0];
1828
1829 // Find the first SMax
1830 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1831 ++Idx;
1832
1833 // Check to see if one of the operands is an SMax. If so, expand its operands
1834 // onto our operand list, and recurse to simplify.
1835 if (Idx < Ops.size()) {
1836 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001837 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001838 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1839 Ops.erase(Ops.begin()+Idx);
1840 DeletedSMax = true;
1841 }
1842
1843 if (DeletedSMax)
1844 return getSMaxExpr(Ops);
1845 }
1846
1847 // Okay, check to see if the same value occurs in the operand list twice. If
1848 // so, delete one. Since we sorted the list, these values are required to
1849 // be adjacent.
1850 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1851 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1852 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1853 --i; --e;
1854 }
1855
1856 if (Ops.size() == 1) return Ops[0];
1857
1858 assert(!Ops.empty() && "Reduced smax down to nothing!");
1859
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001860 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001861 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001862 FoldingSetNodeID ID;
1863 ID.AddInteger(scSMaxExpr);
1864 ID.AddInteger(Ops.size());
1865 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1866 ID.AddPointer(Ops[i]);
1867 void *IP = 0;
1868 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1869 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1870 new (S) SCEVSMaxExpr(Ops);
1871 UniqueSCEVs.InsertNode(S, IP);
1872 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001873}
1874
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001875const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1876 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001877 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001878 Ops.push_back(LHS);
1879 Ops.push_back(RHS);
1880 return getUMaxExpr(Ops);
1881}
1882
Owen Andersonecd0cd72009-06-22 21:39:50 +00001883const SCEV*
1884ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001885 assert(!Ops.empty() && "Cannot get empty umax!");
1886 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001887#ifndef NDEBUG
1888 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1889 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1890 getEffectiveSCEVType(Ops[0]->getType()) &&
1891 "SCEVUMaxExpr operand types don't match!");
1892#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001893
1894 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001895 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001896
1897 // If there are any constants, fold them together.
1898 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001899 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001900 ++Idx;
1901 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001902 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001903 // We found two constants, fold them together!
1904 ConstantInt *Fold = ConstantInt::get(
1905 APIntOps::umax(LHSC->getValue()->getValue(),
1906 RHSC->getValue()->getValue()));
1907 Ops[0] = getConstant(Fold);
1908 Ops.erase(Ops.begin()+1); // Erase the folded element
1909 if (Ops.size() == 1) return Ops[0];
1910 LHSC = cast<SCEVConstant>(Ops[0]);
1911 }
1912
Dan Gohmand156c092009-06-24 14:46:22 +00001913 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001914 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1915 Ops.erase(Ops.begin());
1916 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001917 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1918 // If we have an umax with a constant maximum-int, it will always be
1919 // maximum-int.
1920 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001921 }
1922 }
1923
1924 if (Ops.size() == 1) return Ops[0];
1925
1926 // Find the first UMax
1927 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1928 ++Idx;
1929
1930 // Check to see if one of the operands is a UMax. If so, expand its operands
1931 // onto our operand list, and recurse to simplify.
1932 if (Idx < Ops.size()) {
1933 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001934 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001935 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1936 Ops.erase(Ops.begin()+Idx);
1937 DeletedUMax = true;
1938 }
1939
1940 if (DeletedUMax)
1941 return getUMaxExpr(Ops);
1942 }
1943
1944 // Okay, check to see if the same value occurs in the operand list twice. If
1945 // so, delete one. Since we sorted the list, these values are required to
1946 // be adjacent.
1947 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1948 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1949 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1950 --i; --e;
1951 }
1952
1953 if (Ops.size() == 1) return Ops[0];
1954
1955 assert(!Ops.empty() && "Reduced umax down to nothing!");
1956
1957 // Okay, it looks like we really DO need a umax expr. Check to see if we
1958 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001959 FoldingSetNodeID ID;
1960 ID.AddInteger(scUMaxExpr);
1961 ID.AddInteger(Ops.size());
1962 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1963 ID.AddPointer(Ops[i]);
1964 void *IP = 0;
1965 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1966 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1967 new (S) SCEVUMaxExpr(Ops);
1968 UniqueSCEVs.InsertNode(S, IP);
1969 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001970}
1971
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001972const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1973 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001974 // ~smax(~x, ~y) == smin(x, y).
1975 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1976}
1977
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001978const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1979 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001980 // ~umax(~x, ~y) == umin(x, y)
1981 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1982}
1983
Owen Andersonecd0cd72009-06-22 21:39:50 +00001984const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001985 // Don't attempt to do anything other than create a SCEVUnknown object
1986 // here. createSCEV only calls getUnknown after checking for all other
1987 // interesting possibilities, and any other code that calls getUnknown
1988 // is doing so in order to hide a value from SCEV canonicalization.
1989
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001990 FoldingSetNodeID ID;
1991 ID.AddInteger(scUnknown);
1992 ID.AddPointer(V);
1993 void *IP = 0;
1994 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1995 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
1996 new (S) SCEVUnknown(V);
1997 UniqueSCEVs.InsertNode(S, IP);
1998 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001999}
2000
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002002// Basic SCEV Analysis and PHI Idiom Recognition Code
2003//
2004
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002005/// isSCEVable - Test if values of the given type are analyzable within
2006/// the SCEV framework. This primarily includes integer types, and it
2007/// can optionally include pointer types if the ScalarEvolution class
2008/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002009bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002010 // Integers are always SCEVable.
2011 if (Ty->isInteger())
2012 return true;
2013
2014 // Pointers are SCEVable if TargetData information is available
2015 // to provide pointer size information.
2016 if (isa<PointerType>(Ty))
2017 return TD != NULL;
2018
2019 // Otherwise it's not SCEVable.
2020 return false;
2021}
2022
2023/// getTypeSizeInBits - Return the size in bits of the specified type,
2024/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002025uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002026 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2027
2028 // If we have a TargetData, use it!
2029 if (TD)
2030 return TD->getTypeSizeInBits(Ty);
2031
2032 // Otherwise, we support only integer types.
2033 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2034 return Ty->getPrimitiveSizeInBits();
2035}
2036
2037/// getEffectiveSCEVType - Return a type with the same bitwidth as
2038/// the given type and which represents how SCEV will treat the given
2039/// type, for which isSCEVable must return true. For pointer types,
2040/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002041const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002042 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2043
2044 if (Ty->isInteger())
2045 return Ty;
2046
2047 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2048 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002049}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050
Owen Andersonecd0cd72009-06-22 21:39:50 +00002051const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002052 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002053}
2054
Dan Gohmand83d4af2009-05-04 22:20:30 +00002055/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00002056/// computed.
2057bool ScalarEvolution::hasSCEV(Value *V) const {
2058 return Scalars.count(V);
2059}
2060
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2062/// expression and create a new one.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002063const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002064 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065
Owen Andersonecd0cd72009-06-22 21:39:50 +00002066 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067 if (I != Scalars.end()) return I->second;
Owen Andersonecd0cd72009-06-22 21:39:50 +00002068 const SCEV* S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002069 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070 return S;
2071}
2072
Dan Gohman984c78a2009-06-24 00:54:57 +00002073/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002074/// specified signed integer value and return a SCEV for the constant.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002075const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002076 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2077 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002078}
2079
2080/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2081///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002082const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002083 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002084 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002085
2086 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002087 Ty = getEffectiveSCEVType(Ty);
2088 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002089}
2090
2091/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Andersonecd0cd72009-06-22 21:39:50 +00002092const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002093 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002094 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002095
2096 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002097 Ty = getEffectiveSCEVType(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002098 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002099 return getMinusSCEV(AllOnes, V);
2100}
2101
2102/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2103///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002104const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2105 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002106 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002107 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002108}
2109
2110/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2111/// input value to the specified type. If the type must be extended, it is zero
2112/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002113const SCEV*
2114ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002115 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002116 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002117 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2118 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002119 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002120 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002121 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002122 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002123 return getTruncateExpr(V, Ty);
2124 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002125}
2126
2127/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2128/// input value to the specified type. If the type must be extended, it is sign
2129/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002130const SCEV*
2131ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002132 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002133 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002134 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2135 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002136 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002138 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002139 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002140 return getTruncateExpr(V, Ty);
2141 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002142}
2143
Dan Gohmanac959332009-05-13 03:46:30 +00002144/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2145/// input value to the specified type. If the type must be extended, it is zero
2146/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002147const SCEV*
2148ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002149 const Type *SrcTy = V->getType();
2150 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2151 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2152 "Cannot noop or zero extend with non-integer arguments!");
2153 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2154 "getNoopOrZeroExtend cannot truncate!");
2155 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2156 return V; // No conversion
2157 return getZeroExtendExpr(V, Ty);
2158}
2159
2160/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2161/// input value to the specified type. If the type must be extended, it is sign
2162/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002163const SCEV*
2164ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002165 const Type *SrcTy = V->getType();
2166 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2167 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2168 "Cannot noop or sign extend with non-integer arguments!");
2169 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2170 "getNoopOrSignExtend cannot truncate!");
2171 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2172 return V; // No conversion
2173 return getSignExtendExpr(V, Ty);
2174}
2175
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002176/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2177/// the input value to the specified type. If the type must be extended,
2178/// it is extended with unspecified bits. The conversion must not be
2179/// narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002180const SCEV*
2181ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002182 const Type *SrcTy = V->getType();
2183 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2184 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2185 "Cannot noop or any extend with non-integer arguments!");
2186 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2187 "getNoopOrAnyExtend cannot truncate!");
2188 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2189 return V; // No conversion
2190 return getAnyExtendExpr(V, Ty);
2191}
2192
Dan Gohmanac959332009-05-13 03:46:30 +00002193/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2194/// input value to the specified type. The conversion must not be widening.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002195const SCEV*
2196ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002197 const Type *SrcTy = V->getType();
2198 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2199 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2200 "Cannot truncate or noop with non-integer arguments!");
2201 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2202 "getTruncateOrNoop cannot extend!");
2203 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2204 return V; // No conversion
2205 return getTruncateExpr(V, Ty);
2206}
2207
Dan Gohman8e8b5232009-06-22 00:31:57 +00002208/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2209/// the types using zero-extension, and then perform a umax operation
2210/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002211const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2212 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002213 const SCEV* PromotedLHS = LHS;
2214 const SCEV* PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002215
2216 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2217 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2218 else
2219 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2220
2221 return getUMaxExpr(PromotedLHS, PromotedRHS);
2222}
2223
Dan Gohman9e62bb02009-06-22 15:03:27 +00002224/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2225/// the types using zero-extension, and then perform a umin operation
2226/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002227const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2228 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002229 const SCEV* PromotedLHS = LHS;
2230 const SCEV* PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002231
2232 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2233 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2234 else
2235 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2236
2237 return getUMinExpr(PromotedLHS, PromotedRHS);
2238}
2239
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2241/// the specified instruction and replaces any references to the symbolic value
2242/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002243void
2244ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2245 const SCEV *SymName,
2246 const SCEV *NewVal) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002247 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002248 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249 if (SI == Scalars.end()) return;
2250
Owen Andersonecd0cd72009-06-22 21:39:50 +00002251 const SCEV* NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002252 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 if (NV == SI->second) return; // No change.
2254
2255 SI->second = NV; // Update the scalars map!
2256
2257 // Any instruction values that use this instruction might also need to be
2258 // updated!
2259 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2260 UI != E; ++UI)
2261 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2262}
2263
2264/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2265/// a loop header, making it a potential recurrence, or it doesn't.
2266///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002267const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002269 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 if (L->getHeader() == PN->getParent()) {
2271 // If it lives in the loop header, it has two incoming values, one
2272 // from outside the loop, and one from inside.
2273 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2274 unsigned BackEdge = IncomingEdge^1;
2275
2276 // While we are analyzing this PHI node, handle its value symbolically.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002277 const SCEV* SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002278 assert(Scalars.find(PN) == Scalars.end() &&
2279 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002280 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281
2282 // Using this symbolic name for the PHI, analyze the value coming around
2283 // the back-edge.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002284 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002285
2286 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2287 // has a special value for the first iteration of the loop.
2288
2289 // If the value coming around the backedge is an add with the symbolic
2290 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002291 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002292 // If there is a single occurrence of the symbolic value, replace it
2293 // with a recurrence.
2294 unsigned FoundIndex = Add->getNumOperands();
2295 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2296 if (Add->getOperand(i) == SymbolicName)
2297 if (FoundIndex == e) {
2298 FoundIndex = i;
2299 break;
2300 }
2301
2302 if (FoundIndex != Add->getNumOperands()) {
2303 // Create an add with everything but the specified operand.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002304 SmallVector<const SCEV*, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2306 if (i != FoundIndex)
2307 Ops.push_back(Add->getOperand(i));
Owen Andersonecd0cd72009-06-22 21:39:50 +00002308 const SCEV* Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309
2310 // This is not a valid addrec if the step amount is varying each
2311 // loop iteration, but is not itself an addrec in this loop.
2312 if (Accum->isLoopInvariant(L) ||
2313 (isa<SCEVAddRecExpr>(Accum) &&
2314 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002315 const SCEV *StartVal =
2316 getSCEV(PN->getIncomingValue(IncomingEdge));
2317 const SCEV *PHISCEV =
2318 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319
2320 // Okay, for the entire analysis of this edge we assumed the PHI
2321 // to be symbolic. We now need to go back and update all of the
2322 // entries for the scalars that use the PHI (except for the PHI
2323 // itself) to use the new analyzed value instead of the "symbolic"
2324 // value.
2325 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2326 return PHISCEV;
2327 }
2328 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002329 } else if (const SCEVAddRecExpr *AddRec =
2330 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002331 // Otherwise, this could be a loop like this:
2332 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2333 // In this case, j = {1,+,1} and BEValue is j.
2334 // Because the other in-value of i (0) fits the evolution of BEValue
2335 // i really is an addrec evolution.
2336 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002337 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338
2339 // If StartVal = j.start - j.stride, we can use StartVal as the
2340 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002341 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002342 AddRec->getOperand(1))) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002343 const SCEV* PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002344 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002345
2346 // Okay, for the entire analysis of this edge we assumed the PHI
2347 // to be symbolic. We now need to go back and update all of the
2348 // entries for the scalars that use the PHI (except for the PHI
2349 // itself) to use the new analyzed value instead of the "symbolic"
2350 // value.
2351 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2352 return PHISCEV;
2353 }
2354 }
2355 }
2356
2357 return SymbolicName;
2358 }
2359
2360 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002361 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002362}
2363
Dan Gohman509cf4d2009-05-08 20:26:55 +00002364/// createNodeForGEP - Expand GEP instructions into add and multiply
2365/// operations. This allows them to be analyzed by regular SCEV code.
2366///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002367const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002368
2369 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002370 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002371 // Don't attempt to analyze GEPs over unsized objects.
2372 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2373 return getUnknown(GEP);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002374 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002375 gep_type_iterator GTI = gep_type_begin(GEP);
2376 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2377 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002378 I != E; ++I) {
2379 Value *Index = *I;
2380 // Compute the (potentially symbolic) offset in bytes for this index.
2381 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2382 // For a struct, add the member offset.
2383 const StructLayout &SL = *TD->getStructLayout(STy);
2384 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2385 uint64_t Offset = SL.getElementOffset(FieldNo);
2386 TotalOffset = getAddExpr(TotalOffset,
2387 getIntegerSCEV(Offset, IntPtrTy));
2388 } else {
2389 // For an array, add the element offset, explicitly scaled.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002390 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002391 if (!isa<PointerType>(LocalOffset->getType()))
2392 // Getelementptr indicies are signed.
2393 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2394 IntPtrTy);
2395 LocalOffset =
2396 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002397 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002398 IntPtrTy));
2399 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2400 }
2401 }
2402 return getAddExpr(getSCEV(Base), TotalOffset);
2403}
2404
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002405/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2406/// guaranteed to end in (at every loop iteration). It is, at the same time,
2407/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2408/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002409uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002410ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002411 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002412 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413
Dan Gohmanc76b5452009-05-04 22:02:23 +00002414 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002415 return std::min(GetMinTrailingZeros(T->getOperand()),
2416 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002417
Dan Gohmanc76b5452009-05-04 22:02:23 +00002418 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002419 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2420 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2421 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002422 }
2423
Dan Gohmanc76b5452009-05-04 22:02:23 +00002424 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002425 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2426 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2427 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002428 }
2429
Dan Gohmanc76b5452009-05-04 22:02:23 +00002430 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002431 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002432 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002433 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002434 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002435 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436 }
2437
Dan Gohmanc76b5452009-05-04 22:02:23 +00002438 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002439 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002440 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2441 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002442 for (unsigned i = 1, e = M->getNumOperands();
2443 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002444 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002445 BitWidth);
2446 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002447 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002448
Dan Gohmanc76b5452009-05-04 22:02:23 +00002449 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002450 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002451 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002452 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002453 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002454 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002456
Dan Gohmanc76b5452009-05-04 22:02:23 +00002457 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002458 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002459 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002460 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002461 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002462 return MinOpRes;
2463 }
2464
Dan Gohmanc76b5452009-05-04 22:02:23 +00002465 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002466 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002467 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002468 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002469 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002470 return MinOpRes;
2471 }
2472
Dan Gohman6e923a72009-06-19 23:29:04 +00002473 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2474 // For a SCEVUnknown, ask ValueTracking.
2475 unsigned BitWidth = getTypeSizeInBits(U->getType());
2476 APInt Mask = APInt::getAllOnesValue(BitWidth);
2477 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2478 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2479 return Zeros.countTrailingOnes();
2480 }
2481
2482 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002483 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002484}
2485
Dan Gohman6e923a72009-06-19 23:29:04 +00002486uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002487ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002488 // TODO: Handle other SCEV expression types here.
2489
2490 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2491 return C->getValue()->getValue().countLeadingZeros();
2492
2493 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2494 // A zero-extension cast adds zero bits.
2495 return GetMinLeadingZeros(C->getOperand()) +
2496 (getTypeSizeInBits(C->getType()) -
2497 getTypeSizeInBits(C->getOperand()->getType()));
2498 }
2499
2500 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2501 // For a SCEVUnknown, ask ValueTracking.
2502 unsigned BitWidth = getTypeSizeInBits(U->getType());
2503 APInt Mask = APInt::getAllOnesValue(BitWidth);
2504 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2505 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2506 return Zeros.countLeadingOnes();
2507 }
2508
2509 return 1;
2510}
2511
2512uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002513ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002514 // TODO: Handle other SCEV expression types here.
2515
2516 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2517 const APInt &A = C->getValue()->getValue();
2518 return A.isNegative() ? A.countLeadingOnes() :
2519 A.countLeadingZeros();
2520 }
2521
2522 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2523 // A sign-extension cast adds sign bits.
2524 return GetMinSignBits(C->getOperand()) +
2525 (getTypeSizeInBits(C->getType()) -
2526 getTypeSizeInBits(C->getOperand()->getType()));
2527 }
2528
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002529 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2530 unsigned BitWidth = getTypeSizeInBits(A->getType());
2531
2532 // Special case decrementing a value (ADD X, -1):
2533 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2534 if (CRHS->isAllOnesValue()) {
2535 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2536 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2537 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2538
2539 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2540 // sign bits set.
2541 if (LZ == BitWidth - 1)
2542 return BitWidth;
2543
2544 // If we are subtracting one from a positive number, there is no carry
2545 // out of the result.
2546 if (LZ > 0)
2547 return GetMinSignBits(OtherOpsAdd);
2548 }
2549
2550 // Add can have at most one carry bit. Thus we know that the output
2551 // is, at worst, one more bit than the inputs.
2552 unsigned Min = BitWidth;
2553 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2554 unsigned N = GetMinSignBits(A->getOperand(i));
2555 Min = std::min(Min, N) - 1;
2556 if (Min == 0) return 1;
2557 }
2558 return 1;
2559 }
2560
Dan Gohman6e923a72009-06-19 23:29:04 +00002561 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2562 // For a SCEVUnknown, ask ValueTracking.
2563 return ComputeNumSignBits(U->getValue(), TD);
2564 }
2565
2566 return 1;
2567}
2568
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569/// createSCEV - We know that there is no SCEV for the specified value.
2570/// Analyze the expression.
2571///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002572const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002573 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002574 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002575
Dan Gohman3996f472008-06-22 19:56:46 +00002576 unsigned Opcode = Instruction::UserOp1;
2577 if (Instruction *I = dyn_cast<Instruction>(V))
2578 Opcode = I->getOpcode();
2579 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2580 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002581 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2582 return getConstant(CI);
2583 else if (isa<ConstantPointerNull>(V))
2584 return getIntegerSCEV(0, V->getType());
2585 else if (isa<UndefValue>(V))
2586 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002587 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002588 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589
Dan Gohman3996f472008-06-22 19:56:46 +00002590 User *U = cast<User>(V);
2591 switch (Opcode) {
2592 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002593 return getAddExpr(getSCEV(U->getOperand(0)),
2594 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002595 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002596 return getMulExpr(getSCEV(U->getOperand(0)),
2597 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002598 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002599 return getUDivExpr(getSCEV(U->getOperand(0)),
2600 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002601 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002602 return getMinusSCEV(getSCEV(U->getOperand(0)),
2603 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002604 case Instruction::And:
2605 // For an expression like x&255 that merely masks off the high bits,
2606 // use zext(trunc(x)) as the SCEV expression.
2607 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002608 if (CI->isNullValue())
2609 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002610 if (CI->isAllOnesValue())
2611 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002612 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002613
2614 // Instcombine's ShrinkDemandedConstant may strip bits out of
2615 // constants, obscuring what would otherwise be a low-bits mask.
2616 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2617 // knew about to reconstruct a low-bits mask value.
2618 unsigned LZ = A.countLeadingZeros();
2619 unsigned BitWidth = A.getBitWidth();
2620 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2621 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2622 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2623
2624 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2625
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002626 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002627 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002628 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002629 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002630 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002631 }
2632 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002633
Dan Gohman3996f472008-06-22 19:56:46 +00002634 case Instruction::Or:
2635 // If the RHS of the Or is a constant, we may have something like:
2636 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2637 // optimizations will transparently handle this case.
2638 //
2639 // In order for this transformation to be safe, the LHS must be of the
2640 // form X*(2^n) and the Or constant must be less than 2^n.
2641 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002642 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002643 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002644 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002645 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002646 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002647 }
Dan Gohman3996f472008-06-22 19:56:46 +00002648 break;
2649 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002650 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002651 // If the RHS of the xor is a signbit, then this is just an add.
2652 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002653 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002654 return getAddExpr(getSCEV(U->getOperand(0)),
2655 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002656
2657 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002658 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002659 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002660
2661 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2662 // This is a variant of the check for xor with -1, and it handles
2663 // the case where instcombine has trimmed non-demanded bits out
2664 // of an xor with -1.
2665 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2666 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2667 if (BO->getOpcode() == Instruction::And &&
2668 LCI->getValue() == CI->getValue())
2669 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002670 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002671 const Type *UTy = U->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00002672 const SCEV* Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002673 const Type *Z0Ty = Z0->getType();
2674 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2675
2676 // If C is a low-bits mask, the zero extend is zerving to
2677 // mask off the high bits. Complement the operand and
2678 // re-apply the zext.
2679 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2680 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2681
2682 // If C is a single bit, it may be in the sign-bit position
2683 // before the zero-extend. In this case, represent the xor
2684 // using an add, which is equivalent, and re-apply the zext.
2685 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2686 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2687 Trunc.isSignBit())
2688 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2689 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002690 }
Dan Gohman3996f472008-06-22 19:56:46 +00002691 }
2692 break;
2693
2694 case Instruction::Shl:
2695 // Turn shift left of a constant amount into a multiply.
2696 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2697 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2698 Constant *X = ConstantInt::get(
2699 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002700 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002701 }
2702 break;
2703
Nick Lewycky7fd27892008-07-07 06:15:49 +00002704 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002705 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002706 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2707 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2708 Constant *X = ConstantInt::get(
2709 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002710 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002711 }
2712 break;
2713
Dan Gohman53bf64a2009-04-21 02:26:00 +00002714 case Instruction::AShr:
2715 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2716 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2717 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2718 if (L->getOpcode() == Instruction::Shl &&
2719 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002720 unsigned BitWidth = getTypeSizeInBits(U->getType());
2721 uint64_t Amt = BitWidth - CI->getZExtValue();
2722 if (Amt == BitWidth)
2723 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2724 if (Amt > BitWidth)
2725 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002726 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002727 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002728 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002729 U->getType());
2730 }
2731 break;
2732
Dan Gohman3996f472008-06-22 19:56:46 +00002733 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002734 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002735
2736 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002737 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002738
2739 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002740 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002741
2742 case Instruction::BitCast:
2743 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002744 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002745 return getSCEV(U->getOperand(0));
2746 break;
2747
Dan Gohman01c2ee72009-04-16 03:18:22 +00002748 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002749 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002750 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002751 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002752
2753 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002754 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002755 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2756 U->getType());
2757
Dan Gohman509cf4d2009-05-08 20:26:55 +00002758 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002759 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002760 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002761
Dan Gohman3996f472008-06-22 19:56:46 +00002762 case Instruction::PHI:
2763 return createNodeForPHI(cast<PHINode>(U));
2764
2765 case Instruction::Select:
2766 // This could be a smax or umax that was lowered earlier.
2767 // Try to recover it.
2768 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2769 Value *LHS = ICI->getOperand(0);
2770 Value *RHS = ICI->getOperand(1);
2771 switch (ICI->getPredicate()) {
2772 case ICmpInst::ICMP_SLT:
2773 case ICmpInst::ICMP_SLE:
2774 std::swap(LHS, RHS);
2775 // fall through
2776 case ICmpInst::ICMP_SGT:
2777 case ICmpInst::ICMP_SGE:
2778 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002779 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002780 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002781 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002782 break;
2783 case ICmpInst::ICMP_ULT:
2784 case ICmpInst::ICMP_ULE:
2785 std::swap(LHS, RHS);
2786 // fall through
2787 case ICmpInst::ICMP_UGT:
2788 case ICmpInst::ICMP_UGE:
2789 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002790 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002791 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002792 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002793 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002794 case ICmpInst::ICMP_NE:
2795 // n != 0 ? n : 1 -> umax(n, 1)
2796 if (LHS == U->getOperand(1) &&
2797 isa<ConstantInt>(U->getOperand(2)) &&
2798 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2799 isa<ConstantInt>(RHS) &&
2800 cast<ConstantInt>(RHS)->isZero())
2801 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2802 break;
2803 case ICmpInst::ICMP_EQ:
2804 // n == 0 ? 1 : n -> umax(n, 1)
2805 if (LHS == U->getOperand(2) &&
2806 isa<ConstantInt>(U->getOperand(1)) &&
2807 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2808 isa<ConstantInt>(RHS) &&
2809 cast<ConstantInt>(RHS)->isZero())
2810 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2811 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002812 default:
2813 break;
2814 }
2815 }
2816
2817 default: // We cannot analyze this expression.
2818 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002819 }
2820
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002821 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822}
2823
2824
2825
2826//===----------------------------------------------------------------------===//
2827// Iteration Count Computation Code
2828//
2829
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002830/// getBackedgeTakenCount - If the specified loop has a predictable
2831/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2832/// object. The backedge-taken count is the number of times the loop header
2833/// will be branched to from within the loop. This is one less than the
2834/// trip count of the loop, since it doesn't count the first iteration,
2835/// when the header is branched to from outside the loop.
2836///
2837/// Note that it is not valid to call this method on a loop without a
2838/// loop-invariant backedge-taken count (see
2839/// hasLoopInvariantBackedgeTakenCount).
2840///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002841const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002842 return getBackedgeTakenInfo(L).Exact;
2843}
2844
2845/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2846/// return the least SCEV value that is known never to be less than the
2847/// actual backedge taken count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002848const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002849 return getBackedgeTakenInfo(L).Max;
2850}
2851
2852const ScalarEvolution::BackedgeTakenInfo &
2853ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002854 // Initially insert a CouldNotCompute for this loop. If the insertion
2855 // succeeds, procede to actually compute a backedge-taken count and
2856 // update the value. The temporary CouldNotCompute value tells SCEV
2857 // code elsewhere that it shouldn't attempt to request a new
2858 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002859 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002860 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2861 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002862 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002863 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002864 assert(ItCount.Exact->isLoopInvariant(L) &&
2865 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 "Computed trip count isn't loop invariant for loop!");
2867 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002868
Dan Gohmana9dba962009-04-27 20:16:15 +00002869 // Update the value in the map.
2870 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002871 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002872 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002873 // Update the value in the map.
2874 Pair.first->second = ItCount;
2875 if (isa<PHINode>(L->getHeader()->begin()))
2876 // Only count loops that have phi nodes as not being computable.
2877 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002878 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002879
2880 // Now that we know more about the trip count for this loop, forget any
2881 // existing SCEV values for PHI nodes in this loop since they are only
2882 // conservative estimates made without the benefit
2883 // of trip count information.
2884 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002885 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002887 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888}
2889
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002890/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002891/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002892/// ScalarEvolution's ability to compute a trip count, or if the loop
2893/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002894void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002895 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002896 forgetLoopPHIs(L);
2897}
2898
2899/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2900/// PHI nodes in the given loop. This is used when the trip count of
2901/// the loop may have changed.
2902void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002903 BasicBlock *Header = L->getHeader();
2904
Dan Gohman9fd4a002009-05-12 01:27:58 +00002905 // Push all Loop-header PHIs onto the Worklist stack, except those
2906 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2907 // a PHI either means that it has an unrecognized structure, or it's
2908 // a PHI that's in the progress of being computed by createNodeForPHI.
2909 // In the former case, additional loop trip count information isn't
2910 // going to change anything. In the later case, createNodeForPHI will
2911 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002912 SmallVector<Instruction *, 16> Worklist;
2913 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002914 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002915 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2916 Scalars.find((Value*)I);
Dan Gohman9fd4a002009-05-12 01:27:58 +00002917 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2918 Worklist.push_back(PN);
2919 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002920
2921 while (!Worklist.empty()) {
2922 Instruction *I = Worklist.pop_back_val();
2923 if (Scalars.erase(I))
2924 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2925 UI != UE; ++UI)
2926 Worklist.push_back(cast<Instruction>(UI));
2927 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002928}
2929
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002930/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2931/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002932ScalarEvolution::BackedgeTakenInfo
2933ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002934 SmallVector<BasicBlock*, 8> ExitingBlocks;
2935 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002936
Dan Gohman8e8b5232009-06-22 00:31:57 +00002937 // Examine all exits and pick the most conservative values.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002938 const SCEV* BECount = getCouldNotCompute();
2939 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002940 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002941 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2942 BackedgeTakenInfo NewBTI =
2943 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002945 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002946 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002947 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002948 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002949 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002950 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002951 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002952 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002953 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002954 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002955 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002956 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002957 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002958 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002959 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002960 }
2961
2962 return BackedgeTakenInfo(BECount, MaxBECount);
2963}
2964
2965/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2966/// of the specified loop will execute if it exits via the specified block.
2967ScalarEvolution::BackedgeTakenInfo
2968ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2969 BasicBlock *ExitingBlock) {
2970
2971 // Okay, we've chosen an exiting block. See what condition causes us to
2972 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973 //
2974 // FIXME: we should be able to handle switch instructions (with a single exit)
2975 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002976 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00002978
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 // At this point, we know we have a conditional branch that determines whether
2980 // the loop is exited. However, we don't know if the branch is executed each
2981 // time through the loop. If not, then the execution count of the branch will
2982 // not be equal to the trip count of the loop.
2983 //
2984 // Currently we check for this by checking to see if the Exit branch goes to
2985 // the loop header. If so, we know it will always execute the same number of
2986 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00002987 // loop header. This is common for un-rotated loops.
2988 //
2989 // If both of those tests fail, walk up the unique predecessor chain to the
2990 // header, stopping if there is an edge that doesn't exit the loop. If the
2991 // header is reached, the execution count of the branch will be equal to the
2992 // trip count of the loop.
2993 //
2994 // More extensive analysis could be done to handle more cases here.
2995 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002996 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2997 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00002998 ExitBr->getParent() != L->getHeader()) {
2999 // The simple checks failed, try climbing the unique predecessor chain
3000 // up to the header.
3001 bool Ok = false;
3002 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3003 BasicBlock *Pred = BB->getUniquePredecessor();
3004 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003005 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003006 TerminatorInst *PredTerm = Pred->getTerminator();
3007 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3008 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3009 if (PredSucc == BB)
3010 continue;
3011 // If the predecessor has a successor that isn't BB and isn't
3012 // outside the loop, assume the worst.
3013 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003014 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003015 }
3016 if (Pred == L->getHeader()) {
3017 Ok = true;
3018 break;
3019 }
3020 BB = Pred;
3021 }
3022 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003023 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003024 }
3025
3026 // Procede to the next level to examine the exit condition expression.
3027 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3028 ExitBr->getSuccessor(0),
3029 ExitBr->getSuccessor(1));
3030}
3031
3032/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3033/// backedge of the specified loop will execute if its exit condition
3034/// were a conditional branch of ExitCond, TBB, and FBB.
3035ScalarEvolution::BackedgeTakenInfo
3036ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3037 Value *ExitCond,
3038 BasicBlock *TBB,
3039 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003040 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3042 if (BO->getOpcode() == Instruction::And) {
3043 // Recurse on the operands of the and.
3044 BackedgeTakenInfo BTI0 =
3045 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3046 BackedgeTakenInfo BTI1 =
3047 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003048 const SCEV* BECount = getCouldNotCompute();
3049 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003050 if (L->contains(TBB)) {
3051 // Both conditions must be true for the loop to continue executing.
3052 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003053 if (BTI0.Exact == getCouldNotCompute() ||
3054 BTI1.Exact == getCouldNotCompute())
3055 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003056 else
3057 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003058 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003059 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003060 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003061 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003062 else
3063 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003064 } else {
3065 // Both conditions must be true for the loop to exit.
3066 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003067 if (BTI0.Exact != getCouldNotCompute() &&
3068 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003069 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003070 if (BTI0.Max != getCouldNotCompute() &&
3071 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003072 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3073 }
3074
3075 return BackedgeTakenInfo(BECount, MaxBECount);
3076 }
3077 if (BO->getOpcode() == Instruction::Or) {
3078 // Recurse on the operands of the or.
3079 BackedgeTakenInfo BTI0 =
3080 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3081 BackedgeTakenInfo BTI1 =
3082 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003083 const SCEV* BECount = getCouldNotCompute();
3084 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003085 if (L->contains(FBB)) {
3086 // Both conditions must be false for the loop to continue executing.
3087 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003088 if (BTI0.Exact == getCouldNotCompute() ||
3089 BTI1.Exact == getCouldNotCompute())
3090 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003091 else
3092 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003093 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003094 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003095 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003096 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003097 else
3098 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003099 } else {
3100 // Both conditions must be false for the loop to exit.
3101 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003102 if (BTI0.Exact != getCouldNotCompute() &&
3103 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003104 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003105 if (BTI0.Max != getCouldNotCompute() &&
3106 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003107 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3108 }
3109
3110 return BackedgeTakenInfo(BECount, MaxBECount);
3111 }
3112 }
3113
3114 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3115 // Procede to the next level to examine the icmp.
3116 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3117 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118
Eli Friedman459d7292009-05-09 12:32:42 +00003119 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003120 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3121}
3122
3123/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3124/// backedge of the specified loop will execute if its exit condition
3125/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3126ScalarEvolution::BackedgeTakenInfo
3127ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3128 ICmpInst *ExitCond,
3129 BasicBlock *TBB,
3130 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131
3132 // If the condition was exit on true, convert the condition to exit on false
3133 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003134 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003135 Cond = ExitCond->getPredicate();
3136 else
3137 Cond = ExitCond->getInversePredicate();
3138
3139 // Handle common loops like: for (X = "string"; *X; ++X)
3140 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3141 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003142 const SCEV* ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003143 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003144 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3145 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3146 return BackedgeTakenInfo(ItCnt,
3147 isa<SCEVConstant>(ItCnt) ? ItCnt :
3148 getConstant(APInt::getMaxValue(BitWidth)-1));
3149 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003150 }
3151
Owen Andersonecd0cd72009-06-22 21:39:50 +00003152 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3153 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154
3155 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003156 LHS = getSCEVAtScope(LHS, L);
3157 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158
Dan Gohman9bc642f2009-06-24 04:48:43 +00003159 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003161 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3162 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163 std::swap(LHS, RHS);
3164 Cond = ICmpInst::getSwappedPredicate(Cond);
3165 }
3166
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003167 // If we have a comparison of a chrec against a constant, try to use value
3168 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003169 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3170 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003172 // Form the constant range.
3173 ConstantRange CompRange(
3174 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175
Owen Andersonecd0cd72009-06-22 21:39:50 +00003176 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003177 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003178 }
3179
3180 switch (Cond) {
3181 case ICmpInst::ICMP_NE: { // while (X != Y)
3182 // Convert to: while (X-Y != 0)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003183 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3185 break;
3186 }
3187 case ICmpInst::ICMP_EQ: {
3188 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003189 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3191 break;
3192 }
3193 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003194 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3195 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196 break;
3197 }
3198 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003199 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3200 getNotSCEV(RHS), L, true);
3201 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003202 break;
3203 }
3204 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003205 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3206 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003207 break;
3208 }
3209 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003210 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3211 getNotSCEV(RHS), L, false);
3212 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213 break;
3214 }
3215 default:
3216#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003217 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003219 errs() << "[unsigned] ";
3220 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003221 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003222 << " " << *RHS << "\n";
3223#endif
3224 break;
3225 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003226 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003227 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228}
3229
3230static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003231EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3232 ScalarEvolution &SE) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003233 const SCEV* InVal = SE.getConstant(C);
3234 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003235 assert(isa<SCEVConstant>(Val) &&
3236 "Evaluation of SCEV at constant didn't fold correctly?");
3237 return cast<SCEVConstant>(Val)->getValue();
3238}
3239
3240/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3241/// and a GEP expression (missing the pointer index) indexing into it, return
3242/// the addressed element of the initializer or null if the index expression is
3243/// invalid.
3244static Constant *
3245GetAddressedElementFromGlobal(GlobalVariable *GV,
3246 const std::vector<ConstantInt*> &Indices) {
3247 Constant *Init = GV->getInitializer();
3248 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3249 uint64_t Idx = Indices[i]->getZExtValue();
3250 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3251 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3252 Init = cast<Constant>(CS->getOperand(Idx));
3253 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3254 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3255 Init = cast<Constant>(CA->getOperand(Idx));
3256 } else if (isa<ConstantAggregateZero>(Init)) {
3257 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3258 assert(Idx < STy->getNumElements() && "Bad struct index!");
3259 Init = Constant::getNullValue(STy->getElementType(Idx));
3260 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3261 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3262 Init = Constant::getNullValue(ATy->getElementType());
3263 } else {
3264 assert(0 && "Unknown constant aggregate type!");
3265 }
3266 return 0;
3267 } else {
3268 return 0; // Unknown initializer type
3269 }
3270 }
3271 return Init;
3272}
3273
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003274/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3275/// 'icmp op load X, cst', try to see if we can compute the backedge
3276/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003277const SCEV *
3278ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3279 LoadInst *LI,
3280 Constant *RHS,
3281 const Loop *L,
3282 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003283 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284
3285 // Check to see if the loaded pointer is a getelementptr of a global.
3286 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003287 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003288
3289 // Make sure that it is really a constant global we are gepping, with an
3290 // initializer, and make sure the first IDX is really 0.
3291 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3292 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3293 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3294 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003295 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296
3297 // Okay, we allow one non-constant index into the GEP instruction.
3298 Value *VarIdx = 0;
3299 std::vector<ConstantInt*> Indexes;
3300 unsigned VarIdxNum = 0;
3301 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3302 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3303 Indexes.push_back(CI);
3304 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003305 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 VarIdx = GEP->getOperand(i);
3307 VarIdxNum = i-2;
3308 Indexes.push_back(0);
3309 }
3310
3311 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3312 // Check to see if X is a loop variant variable value now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003313 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003314 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003315
3316 // We can only recognize very limited forms of loop index expressions, in
3317 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003318 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003319 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3320 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3321 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003322 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003323
3324 unsigned MaxSteps = MaxBruteForceIterations;
3325 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3326 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003327 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003328 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329
3330 // Form the GEP offset.
3331 Indexes[VarIdxNum] = Val;
3332
3333 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3334 if (Result == 0) break; // Cannot compute!
3335
3336 // Evaluate the condition for this iteration.
3337 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3338 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3339 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3340#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003341 errs() << "\n***\n*** Computed loop count " << *ItCst
3342 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3343 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344#endif
3345 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003346 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003347 }
3348 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003349 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350}
3351
3352
3353/// CanConstantFold - Return true if we can constant fold an instruction of the
3354/// specified type, assuming that all operands were constants.
3355static bool CanConstantFold(const Instruction *I) {
3356 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3357 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3358 return true;
3359
3360 if (const CallInst *CI = dyn_cast<CallInst>(I))
3361 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003362 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363 return false;
3364}
3365
3366/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3367/// in the loop that V is derived from. We allow arbitrary operations along the
3368/// way, but the operands of an operation must either be constants or a value
3369/// derived from a constant PHI. If this expression does not fit with these
3370/// constraints, return null.
3371static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3372 // If this is not an instruction, or if this is an instruction outside of the
3373 // loop, it can't be derived from a loop PHI.
3374 Instruction *I = dyn_cast<Instruction>(V);
3375 if (I == 0 || !L->contains(I->getParent())) return 0;
3376
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003377 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 if (L->getHeader() == I->getParent())
3379 return PN;
3380 else
3381 // We don't currently keep track of the control flow needed to evaluate
3382 // PHIs, so we cannot handle PHIs inside of loops.
3383 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003384 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385
3386 // If we won't be able to constant fold this expression even if the operands
3387 // are constants, return early.
3388 if (!CanConstantFold(I)) return 0;
3389
3390 // Otherwise, we can evaluate this instruction if all of its operands are
3391 // constant or derived from a PHI node themselves.
3392 PHINode *PHI = 0;
3393 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3394 if (!(isa<Constant>(I->getOperand(Op)) ||
3395 isa<GlobalValue>(I->getOperand(Op)))) {
3396 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3397 if (P == 0) return 0; // Not evolving from PHI
3398 if (PHI == 0)
3399 PHI = P;
3400 else if (PHI != P)
3401 return 0; // Evolving from multiple different PHIs.
3402 }
3403
3404 // This is a expression evolving from a constant PHI!
3405 return PHI;
3406}
3407
3408/// EvaluateExpression - Given an expression that passes the
3409/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3410/// in the loop has the value PHIVal. If we can't fold this expression for some
3411/// reason, return null.
3412static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3413 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003415 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003416 Instruction *I = cast<Instruction>(V);
3417
3418 std::vector<Constant*> Operands;
3419 Operands.resize(I->getNumOperands());
3420
3421 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3422 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3423 if (Operands[i] == 0) return 0;
3424 }
3425
Chris Lattnerd6e56912007-12-10 22:53:04 +00003426 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3427 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3428 &Operands[0], Operands.size());
3429 else
3430 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3431 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003432}
3433
3434/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3435/// in the header of its containing loop, we know the loop executes a
3436/// constant number of times, and the PHI node is just a recurrence
3437/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003438Constant *
3439ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3440 const APInt& BEs,
3441 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 std::map<PHINode*, Constant*>::iterator I =
3443 ConstantEvolutionLoopExitValue.find(PN);
3444 if (I != ConstantEvolutionLoopExitValue.end())
3445 return I->second;
3446
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003447 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003448 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3449
3450 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3451
3452 // Since the loop is canonicalized, the PHI node must have two entries. One
3453 // entry must be a constant (coming in from outside of the loop), and the
3454 // second must be derived from the same PHI.
3455 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3456 Constant *StartCST =
3457 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3458 if (StartCST == 0)
3459 return RetVal = 0; // Must be a constant.
3460
3461 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3462 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3463 if (PN2 != PN)
3464 return RetVal = 0; // Not derived from same PHI.
3465
3466 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003467 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003468 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3469
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003470 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003471 unsigned IterationNum = 0;
3472 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3473 if (IterationNum == NumIterations)
3474 return RetVal = PHIVal; // Got exit value!
3475
3476 // Compute the value of the PHI node for the next iteration.
3477 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3478 if (NextPHI == PHIVal)
3479 return RetVal = NextPHI; // Stopped evolving!
3480 if (NextPHI == 0)
3481 return 0; // Couldn't evaluate!
3482 PHIVal = NextPHI;
3483 }
3484}
3485
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003486/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487/// constant number of times (the condition evolves only from constants),
3488/// try to evaluate a few iterations of the loop until we get the exit
3489/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003490/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003491const SCEV *
3492ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3493 Value *Cond,
3494 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003496 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003497
3498 // Since the loop is canonicalized, the PHI node must have two entries. One
3499 // entry must be a constant (coming in from outside of the loop), and the
3500 // second must be derived from the same PHI.
3501 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3502 Constant *StartCST =
3503 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003504 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505
3506 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3507 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003508 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509
3510 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3511 // the loop symbolically to determine when the condition gets a value of
3512 // "ExitWhen".
3513 unsigned IterationNum = 0;
3514 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3515 for (Constant *PHIVal = StartCST;
3516 IterationNum != MaxIterations; ++IterationNum) {
3517 ConstantInt *CondVal =
3518 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3519
3520 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003521 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522
3523 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003525 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003526 }
3527
3528 // Compute the value of the PHI node for the next iteration.
3529 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3530 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003531 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532 PHIVal = NextPHI;
3533 }
3534
3535 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003536 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003537}
3538
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003539/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3540/// at the specified scope in the program. The L value specifies a loop
3541/// nest to evaluate the expression at, where null is the top-level or a
3542/// specified loop is immediately inside of the loop.
3543///
3544/// This method can be used to compute the exit value for a variable defined
3545/// in a loop by querying what the value will hold in the parent loop.
3546///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003547/// In the case that a relevant loop exit value cannot be computed, the
3548/// original value V is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003549const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 // FIXME: this should be turned into a virtual method on SCEV!
3551
3552 if (isa<SCEVConstant>(V)) return V;
3553
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003554 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003556 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003558 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3560 if (PHINode *PN = dyn_cast<PHINode>(I))
3561 if (PN->getParent() == LI->getHeader()) {
3562 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003563 // to see if the loop that contains it has a known backedge-taken
3564 // count. If so, we may be able to force computation of the exit
3565 // value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003566 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003567 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003568 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003569 // Okay, we know how many times the containing loop executes. If
3570 // this is a constant evolving PHI node, get the final value at
3571 // the specified iteration number.
3572 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003573 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003574 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003575 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003576 }
3577 }
3578
3579 // Okay, this is an expression that we cannot symbolically evaluate
3580 // into a SCEV. Check to see if it's possible to symbolically evaluate
3581 // the arguments into constants, and if so, try to constant propagate the
3582 // result. This is particularly useful for computing loop exit values.
3583 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003584 // Check to see if we've folded this instruction at this loop before.
3585 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3586 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3587 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3588 if (!Pair.second)
3589 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3590
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003591 std::vector<Constant*> Operands;
3592 Operands.reserve(I->getNumOperands());
3593 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3594 Value *Op = I->getOperand(i);
3595 if (Constant *C = dyn_cast<Constant>(Op)) {
3596 Operands.push_back(C);
3597 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003598 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003599 // non-integer and non-pointer, don't even try to analyze them
3600 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003601 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003602 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003603
Owen Andersonecd0cd72009-06-22 21:39:50 +00003604 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003605 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003606 Constant *C = SC->getValue();
3607 if (C->getType() != Op->getType())
3608 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3609 Op->getType(),
3610 false),
3611 C, Op->getType());
3612 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003613 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003614 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3615 if (C->getType() != Op->getType())
3616 C =
3617 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3618 Op->getType(),
3619 false),
3620 C, Op->getType());
3621 Operands.push_back(C);
3622 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003623 return V;
3624 } else {
3625 return V;
3626 }
3627 }
3628 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003629
Chris Lattnerd6e56912007-12-10 22:53:04 +00003630 Constant *C;
3631 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3632 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3633 &Operands[0], Operands.size());
3634 else
3635 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3636 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003637 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003638 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003639 }
3640 }
3641
3642 // This is some other type of SCEVUnknown, just return it.
3643 return V;
3644 }
3645
Dan Gohmanc76b5452009-05-04 22:02:23 +00003646 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647 // Avoid performing the look-up in the common case where the specified
3648 // expression has no loop-variant portions.
3649 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003650 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003651 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003652 // Okay, at least one of these operands is loop variant but might be
3653 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003654 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3655 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003656 NewOps.push_back(OpAtScope);
3657
3658 for (++i; i != e; ++i) {
3659 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003660 NewOps.push_back(OpAtScope);
3661 }
3662 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003663 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003664 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003665 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003666 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003667 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003668 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003669 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003670 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003671 }
3672 }
3673 // If we got here, all operands are loop invariant.
3674 return Comm;
3675 }
3676
Dan Gohmanc76b5452009-05-04 22:02:23 +00003677 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003678 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3679 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003680 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3681 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003682 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003683 }
3684
3685 // If this is a loop recurrence for a loop that does not contain L, then we
3686 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003687 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003688 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3689 // To evaluate this recurrence, we need to know how many times the AddRec
3690 // loop iterates. Compute this now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003691 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003692 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693
Eli Friedman7489ec92008-08-04 23:49:06 +00003694 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003695 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003697 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 }
3699
Dan Gohmanc76b5452009-05-04 22:02:23 +00003700 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003701 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003702 if (Op == Cast->getOperand())
3703 return Cast; // must be loop invariant
3704 return getZeroExtendExpr(Op, Cast->getType());
3705 }
3706
Dan Gohmanc76b5452009-05-04 22:02:23 +00003707 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003708 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003709 if (Op == Cast->getOperand())
3710 return Cast; // must be loop invariant
3711 return getSignExtendExpr(Op, Cast->getType());
3712 }
3713
Dan Gohmanc76b5452009-05-04 22:02:23 +00003714 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003715 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003716 if (Op == Cast->getOperand())
3717 return Cast; // must be loop invariant
3718 return getTruncateExpr(Op, Cast->getType());
3719 }
3720
3721 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003722 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003723}
3724
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003725/// getSCEVAtScope - This is a convenience function which does
3726/// getSCEVAtScope(getSCEV(V), L).
Owen Andersonecd0cd72009-06-22 21:39:50 +00003727const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003728 return getSCEVAtScope(getSCEV(V), L);
3729}
3730
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003731/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3732/// following equation:
3733///
3734/// A * X = B (mod N)
3735///
3736/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3737/// A and B isn't important.
3738///
3739/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003740static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003741 ScalarEvolution &SE) {
3742 uint32_t BW = A.getBitWidth();
3743 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3744 assert(A != 0 && "A must be non-zero.");
3745
3746 // 1. D = gcd(A, N)
3747 //
3748 // The gcd of A and N may have only one prime factor: 2. The number of
3749 // trailing zeros in A is its multiplicity
3750 uint32_t Mult2 = A.countTrailingZeros();
3751 // D = 2^Mult2
3752
3753 // 2. Check if B is divisible by D.
3754 //
3755 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3756 // is not less than multiplicity of this prime factor for D.
3757 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003758 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003759
3760 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3761 // modulo (N / D).
3762 //
3763 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3764 // bit width during computations.
3765 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3766 APInt Mod(BW + 1, 0);
3767 Mod.set(BW - Mult2); // Mod = N / D
3768 APInt I = AD.multiplicativeInverse(Mod);
3769
3770 // 4. Compute the minimum unsigned root of the equation:
3771 // I * (B / D) mod (N / D)
3772 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3773
3774 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3775 // bits.
3776 return SE.getConstant(Result.trunc(BW));
3777}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003778
3779/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3780/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3781/// might be the same) or two SCEVCouldNotCompute objects.
3782///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003783static std::pair<const SCEV*,const SCEV*>
Dan Gohman89f85052007-10-22 18:31:58 +00003784SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003785 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003786 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3787 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3788 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003789
3790 // We currently can only solve this if the coefficients are constants.
3791 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003792 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003793 return std::make_pair(CNC, CNC);
3794 }
3795
3796 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3797 const APInt &L = LC->getValue()->getValue();
3798 const APInt &M = MC->getValue()->getValue();
3799 const APInt &N = NC->getValue()->getValue();
3800 APInt Two(BitWidth, 2);
3801 APInt Four(BitWidth, 4);
3802
Dan Gohman9bc642f2009-06-24 04:48:43 +00003803 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003804 using namespace APIntOps;
3805 const APInt& C = L;
3806 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3807 // The B coefficient is M-N/2
3808 APInt B(M);
3809 B -= sdiv(N,Two);
3810
3811 // The A coefficient is N/2
3812 APInt A(N.sdiv(Two));
3813
3814 // Compute the B^2-4ac term.
3815 APInt SqrtTerm(B);
3816 SqrtTerm *= B;
3817 SqrtTerm -= Four * (A * C);
3818
3819 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3820 // integer value or else APInt::sqrt() will assert.
3821 APInt SqrtVal(SqrtTerm.sqrt());
3822
Dan Gohman9bc642f2009-06-24 04:48:43 +00003823 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003824 // The divisions must be performed as signed divisions.
3825 APInt NegB(-B);
3826 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003827 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003828 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003829 return std::make_pair(CNC, CNC);
3830 }
3831
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3833 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3834
Dan Gohman9bc642f2009-06-24 04:48:43 +00003835 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003836 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003837 } // end APIntOps namespace
3838}
3839
3840/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003841/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003842const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003843 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003844 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845 // If the value is already zero, the branch will execute zero times.
3846 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003847 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003848 }
3849
Dan Gohmanbff6b582009-05-04 22:30:44 +00003850 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003851 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003852 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003853
3854 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003855 // If this is an affine expression, the execution count of this branch is
3856 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003857 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003858 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003859 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003860 // equivalent to:
3861 //
3862 // Step*N = -Start (mod 2^BW)
3863 //
3864 // where BW is the common bit width of Start and Step.
3865
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003867 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3868 L->getParentLoop());
3869 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3870 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003871
Dan Gohmanc76b5452009-05-04 22:02:23 +00003872 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003873 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003874
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003875 // First, handle unitary steps.
3876 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003877 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003878 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3879 return Start; // N = Start (as unsigned)
3880
3881 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003882 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003883 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003884 -StartC->getValue()->getValue(),
3885 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003886 }
3887 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3888 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3889 // the quadratic equation to solve it.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003890 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003891 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003892 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3893 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894 if (R1) {
3895#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003896 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3897 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003898#endif
3899 // Pick the smallest positive root value.
3900 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00003901 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 R1->getValue(), R2->getValue()))) {
3903 if (CB->getZExtValue() == false)
3904 std::swap(R1, R2); // R1 is the minimum root now.
3905
3906 // We can only use this value if the chrec ends up with an exact zero
3907 // value at this index. When solving for "X*X != 5", for example, we
3908 // should not accept a root of 2.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003909 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003910 if (Val->isZero())
3911 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003912 }
3913 }
3914 }
3915
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003916 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003917}
3918
3919/// HowFarToNonZero - Return the number of times a backedge checking the
3920/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003921/// CouldNotCompute
Owen Andersonecd0cd72009-06-22 21:39:50 +00003922const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003923 // Loops that look like: while (X == 0) are very strange indeed. We don't
3924 // handle them yet except for the trivial case. This could be expanded in the
3925 // future as needed.
3926
3927 // If the value is a constant, check to see if it is known to be non-zero
3928 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003929 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003930 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003931 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003932 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003933 }
3934
3935 // We could implement others, but I really doubt anyone writes loops like
3936 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003937 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003938}
3939
Dan Gohmanab157b22009-05-18 15:36:09 +00003940/// getLoopPredecessor - If the given loop's header has exactly one unique
3941/// predecessor outside the loop, return it. Otherwise return null.
3942///
3943BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3944 BasicBlock *Header = L->getHeader();
3945 BasicBlock *Pred = 0;
3946 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3947 PI != E; ++PI)
3948 if (!L->contains(*PI)) {
3949 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3950 Pred = *PI;
3951 }
3952 return Pred;
3953}
3954
Dan Gohman1cddf972008-09-15 22:18:04 +00003955/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3956/// (which may not be an immediate predecessor) which has exactly one
3957/// successor from which BB is reachable, or null if no such block is
3958/// found.
3959///
3960BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003961ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003962 // If the block has a unique predecessor, then there is no path from the
3963 // predecessor to the block that does not go through the direct edge
3964 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003965 if (BasicBlock *Pred = BB->getSinglePredecessor())
3966 return Pred;
3967
3968 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003969 // If the header has a unique predecessor outside the loop, it must be
3970 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003971 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003972 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003973
3974 return 0;
3975}
3976
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003977/// HasSameValue - SCEV structural equivalence is usually sufficient for
3978/// testing whether two expressions are equal, however for the purposes of
3979/// looking for a condition guarding a loop, it can be useful to be a little
3980/// more general, since a front-end may have replicated the controlling
3981/// expression.
3982///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003983static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003984 // Quick check to see if they are the same SCEV.
3985 if (A == B) return true;
3986
3987 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3988 // two different instructions with the same value. Check for this case.
3989 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3990 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3991 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3992 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3993 if (AI->isIdenticalTo(BI))
3994 return true;
3995
3996 // Otherwise assume they may have a different value.
3997 return false;
3998}
3999
Dan Gohmancacd2012009-02-12 22:19:27 +00004000/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00004001/// a conditional between LHS and RHS. This is used to help avoid max
4002/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004003bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00004004 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00004005 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004006 // Interpret a null as meaning no loop, where there is obviously no guard
4007 // (interprocedural conditions notwithstanding).
4008 if (!L) return false;
4009
Dan Gohmanab157b22009-05-18 15:36:09 +00004010 BasicBlock *Predecessor = getLoopPredecessor(L);
4011 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004012
Dan Gohmanab157b22009-05-18 15:36:09 +00004013 // Starting at the loop predecessor, climb up the predecessor chain, as long
4014 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004015 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004016 for (; Predecessor;
4017 PredecessorDest = Predecessor,
4018 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004019
4020 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004021 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004022 if (!LoopEntryPredicate ||
4023 LoopEntryPredicate->isUnconditional())
4024 continue;
4025
Dan Gohman423ed6c2009-06-24 01:18:18 +00004026 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4027 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004028 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004029 }
4030
Dan Gohmanab678fb2008-08-12 20:17:31 +00004031 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004032}
4033
Dan Gohman423ed6c2009-06-24 01:18:18 +00004034/// isNecessaryCond - Test whether the given CondValue value is a condition
4035/// which is at least as strict as the one described by Pred, LHS, and RHS.
4036bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4037 ICmpInst::Predicate Pred,
4038 const SCEV *LHS, const SCEV *RHS,
4039 bool Inverse) {
4040 // Recursivly handle And and Or conditions.
4041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4042 if (BO->getOpcode() == Instruction::And) {
4043 if (!Inverse)
4044 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4045 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4046 } else if (BO->getOpcode() == Instruction::Or) {
4047 if (Inverse)
4048 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4049 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4050 }
4051 }
4052
4053 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4054 if (!ICI) return false;
4055
4056 // Now that we found a conditional branch that dominates the loop, check to
4057 // see if it is the comparison we are looking for.
4058 Value *PreCondLHS = ICI->getOperand(0);
4059 Value *PreCondRHS = ICI->getOperand(1);
4060 ICmpInst::Predicate Cond;
4061 if (Inverse)
4062 Cond = ICI->getInversePredicate();
4063 else
4064 Cond = ICI->getPredicate();
4065
4066 if (Cond == Pred)
4067 ; // An exact match.
4068 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4069 ; // The actual condition is beyond sufficient.
4070 else
4071 // Check a few special cases.
4072 switch (Cond) {
4073 case ICmpInst::ICMP_UGT:
4074 if (Pred == ICmpInst::ICMP_ULT) {
4075 std::swap(PreCondLHS, PreCondRHS);
4076 Cond = ICmpInst::ICMP_ULT;
4077 break;
4078 }
4079 return false;
4080 case ICmpInst::ICMP_SGT:
4081 if (Pred == ICmpInst::ICMP_SLT) {
4082 std::swap(PreCondLHS, PreCondRHS);
4083 Cond = ICmpInst::ICMP_SLT;
4084 break;
4085 }
4086 return false;
4087 case ICmpInst::ICMP_NE:
4088 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4089 // so check for this case by checking if the NE is comparing against
4090 // a minimum or maximum constant.
4091 if (!ICmpInst::isTrueWhenEqual(Pred))
4092 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4093 const APInt &A = CI->getValue();
4094 switch (Pred) {
4095 case ICmpInst::ICMP_SLT:
4096 if (A.isMaxSignedValue()) break;
4097 return false;
4098 case ICmpInst::ICMP_SGT:
4099 if (A.isMinSignedValue()) break;
4100 return false;
4101 case ICmpInst::ICMP_ULT:
4102 if (A.isMaxValue()) break;
4103 return false;
4104 case ICmpInst::ICMP_UGT:
4105 if (A.isMinValue()) break;
4106 return false;
4107 default:
4108 return false;
4109 }
4110 Cond = ICmpInst::ICMP_NE;
4111 // NE is symmetric but the original comparison may not be. Swap
4112 // the operands if necessary so that they match below.
4113 if (isa<SCEVConstant>(LHS))
4114 std::swap(PreCondLHS, PreCondRHS);
4115 break;
4116 }
4117 return false;
4118 default:
4119 // We weren't able to reconcile the condition.
4120 return false;
4121 }
4122
4123 if (!PreCondLHS->getType()->isInteger()) return false;
4124
4125 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4126 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4127 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4128 HasSameValue(RHS, PreCondRHSSCEV)) ||
4129 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4130 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4131}
4132
Dan Gohmand2b62c42009-06-21 23:46:38 +00004133/// getBECount - Subtract the end and start values and divide by the step,
4134/// rounding up, to get the number of times the backedge is executed. Return
4135/// CouldNotCompute if an intermediate computation overflows.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004136const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
4137 const SCEV* End,
4138 const SCEV* Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004139 const Type *Ty = Start->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00004140 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
4141 const SCEV* Diff = getMinusSCEV(End, Start);
4142 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004143
4144 // Add an adjustment to the difference between End and Start so that
4145 // the division will effectively round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004146 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004147
4148 // Check Add for unsigned overflow.
4149 // TODO: More sophisticated things could be done here.
4150 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Andersonecd0cd72009-06-22 21:39:50 +00004151 const SCEV* OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004152 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4153 getZeroExtendExpr(RoundUp, WideTy));
4154 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004155 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004156
4157 return getUDivExpr(Add, Step);
4158}
4159
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160/// HowManyLessThans - Return the number of times a backedge containing the
4161/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004162/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004163ScalarEvolution::BackedgeTakenInfo
4164ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4165 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004167 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004168
Dan Gohmanbff6b582009-05-04 22:30:44 +00004169 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004171 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004172
4173 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004174 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004175 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004176 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004177
4178 // TODO: handle non-constant strides.
4179 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4180 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004181 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004182 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004183 // With unit stride, the iteration never steps past the limit value.
4184 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4185 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4186 // Test whether a positive iteration iteration can step past the limit
4187 // value and past the maximum value for its type in a single step.
4188 if (isSigned) {
4189 APInt Max = APInt::getSignedMaxValue(BitWidth);
4190 if ((Max - CStep->getValue()->getValue())
4191 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004192 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004193 } else {
4194 APInt Max = APInt::getMaxValue(BitWidth);
4195 if ((Max - CStep->getValue()->getValue())
4196 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004197 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004198 }
4199 } else
4200 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004201 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004202 } else
4203 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004204 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004205
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004206 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4207 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4208 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004209 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004211 // First, we get the value of the LHS in the first iteration: n
Owen Andersonecd0cd72009-06-22 21:39:50 +00004212 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004213
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004214 // Determine the minimum constant start value.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004215 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004216 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4217 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004218
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004219 // If we know that the condition is true in order to enter the loop,
4220 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004221 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4222 // the division must round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004223 const SCEV* End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004224 if (!isLoopGuardedByCond(L,
4225 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4226 getMinusSCEV(Start, Step), RHS))
4227 End = isSigned ? getSMaxExpr(RHS, Start)
4228 : getUMaxExpr(RHS, Start);
4229
4230 // Determine the maximum constant end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004231 const SCEV* MaxEnd =
Dan Gohman92369c32009-06-20 00:32:22 +00004232 isa<SCEVConstant>(End) ? End :
4233 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4234 .ashr(GetMinSignBits(End) - 1) :
4235 APInt::getMaxValue(BitWidth)
4236 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004237
4238 // Finally, we subtract these two values and divide, rounding up, to get
4239 // the number of times the backedge is executed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004240 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004241
4242 // The maximum backedge count is similar, except using the minimum start
4243 // value and the maximum end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004244 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004245
4246 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004247 }
4248
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004249 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004250}
4251
4252/// getNumIterationsInRange - Return the number of iterations of this loop that
4253/// produce values in the specified constant range. Another way of looking at
4254/// this is that it returns the first iteration number where the value is not in
4255/// the condition, thus computing the exit count. If the iteration count can't
4256/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004257const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004258 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004259 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004260 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004261
4262 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004263 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264 if (!SC->getValue()->isZero()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00004265 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004266 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004267 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004268 if (const SCEVAddRecExpr *ShiftedAddRec =
4269 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004270 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004271 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004272 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004273 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004274 }
4275
4276 // The only time we can solve this is when we have all constant indices.
4277 // Otherwise, we cannot determine the overflow conditions.
4278 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4279 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004280 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004281
4282
4283 // Okay at this point we know that all elements of the chrec are constants and
4284 // that the start element is zero.
4285
4286 // First check to see if the range contains zero. If not, the first
4287 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004288 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004289 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004290 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004291
4292 if (isAffine()) {
4293 // If this is an affine expression then we have this situation:
4294 // Solve {0,+,A} in Range === Ax in Range
4295
4296 // We know that zero is in the range. If A is positive then we know that
4297 // the upper value of the range must be the first possible exit value.
4298 // If A is negative then the lower of the range is the last possible loop
4299 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004300 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004301 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4302 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4303
4304 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004305 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004306 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4307
4308 // Evaluate at the exit value. If we really did fall out of the valid
4309 // range, then we computed our trip count, otherwise wrap around or other
4310 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004311 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004312 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004313 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004314
4315 // Ensure that the previous value is in the range. This is a sanity check.
4316 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004317 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004318 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004319 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004320 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 } else if (isQuadratic()) {
4322 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4323 // quadratic equation to solve it. To do this, we must frame our problem in
4324 // terms of figuring out when zero is crossed, instead of when
4325 // Range.getUpper() is crossed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004326 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004327 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Andersonecd0cd72009-06-22 21:39:50 +00004328 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329
4330 // Next, solve the constructed addrec
Owen Andersonecd0cd72009-06-22 21:39:50 +00004331 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004332 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004333 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4334 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004335 if (R1) {
4336 // Pick the smallest positive root value.
4337 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00004338 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004339 R1->getValue(), R2->getValue()))) {
4340 if (CB->getZExtValue() == false)
4341 std::swap(R1, R2); // R1 is the minimum root now.
4342
4343 // Make sure the root is not off by one. The returned iteration should
4344 // not be in the range, but the previous one should be. When solving
4345 // for "X*X < 5", for example, we should not return a root of 2.
4346 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004347 R1->getValue(),
4348 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004349 if (Range.contains(R1Val->getValue())) {
4350 // The next iteration must be out of the range...
4351 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4352
Dan Gohman89f85052007-10-22 18:31:58 +00004353 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004354 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004355 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004356 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357 }
4358
4359 // If R1 was not in the range, then it is a good return value. Make
4360 // sure that R1-1 WAS in the range though, just in case.
4361 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004362 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363 if (Range.contains(R1Val->getValue()))
4364 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004365 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004366 }
4367 }
4368 }
4369
Dan Gohman0ad08b02009-04-18 17:58:19 +00004370 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371}
4372
4373
4374
4375//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004376// SCEVCallbackVH Class Implementation
4377//===----------------------------------------------------------------------===//
4378
Dan Gohman999d14e2009-05-19 19:22:47 +00004379void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004380 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4381 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4382 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004383 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4384 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004385 SE->Scalars.erase(getValPtr());
4386 // this now dangles!
4387}
4388
Dan Gohman999d14e2009-05-19 19:22:47 +00004389void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004390 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4391
4392 // Forget all the expressions associated with users of the old value,
4393 // so that future queries will recompute the expressions using the new
4394 // value.
4395 SmallVector<User *, 16> Worklist;
4396 Value *Old = getValPtr();
4397 bool DeleteOld = false;
4398 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4399 UI != UE; ++UI)
4400 Worklist.push_back(*UI);
4401 while (!Worklist.empty()) {
4402 User *U = Worklist.pop_back_val();
4403 // Deleting the Old value will cause this to dangle. Postpone
4404 // that until everything else is done.
4405 if (U == Old) {
4406 DeleteOld = true;
4407 continue;
4408 }
4409 if (PHINode *PN = dyn_cast<PHINode>(U))
4410 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004411 if (Instruction *I = dyn_cast<Instruction>(U))
4412 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004413 if (SE->Scalars.erase(U))
4414 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4415 UI != UE; ++UI)
4416 Worklist.push_back(*UI);
4417 }
4418 if (DeleteOld) {
4419 if (PHINode *PN = dyn_cast<PHINode>(Old))
4420 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004421 if (Instruction *I = dyn_cast<Instruction>(Old))
4422 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004423 SE->Scalars.erase(Old);
4424 // this now dangles!
4425 }
4426 // this may dangle!
4427}
4428
Dan Gohman999d14e2009-05-19 19:22:47 +00004429ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004430 : CallbackVH(V), SE(se) {}
4431
4432//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433// ScalarEvolution Class Implementation
4434//===----------------------------------------------------------------------===//
4435
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004436ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004437 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004438}
4439
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004440bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004441 this->F = &F;
4442 LI = &getAnalysis<LoopInfo>();
4443 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004444 return false;
4445}
4446
4447void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004448 Scalars.clear();
4449 BackedgeTakenCounts.clear();
4450 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004451 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004452 UniqueSCEVs.clear();
4453 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004454}
4455
4456void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4457 AU.setPreservesAll();
4458 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004459}
4460
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004461bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004462 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004463}
4464
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004465static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004466 const Loop *L) {
4467 // Print all inner loops first
4468 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4469 PrintLoopInfo(OS, SE, *I);
4470
Nick Lewyckye5da1912008-01-02 02:49:20 +00004471 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472
Devang Patel02451fa2007-08-21 00:31:24 +00004473 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004474 L->getExitBlocks(ExitBlocks);
4475 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004476 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004477
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004478 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4479 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004480 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004481 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004482 }
4483
Nick Lewyckye5da1912008-01-02 02:49:20 +00004484 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004485 OS << "Loop " << L->getHeader()->getName() << ": ";
4486
4487 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4488 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4489 } else {
4490 OS << "Unpredictable max backedge-taken count. ";
4491 }
4492
4493 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494}
4495
Dan Gohman13058cc2009-04-21 00:47:46 +00004496void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004497 // ScalarEvolution's implementaiton of the print method is to print
4498 // out SCEV values of all instructions that are interesting. Doing
4499 // this potentially causes it to create new SCEV objects though,
4500 // which technically conflicts with the const qualifier. This isn't
4501 // observable from outside the class though (the hasSCEV function
4502 // notwithstanding), so casting away the const isn't dangerous.
4503 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004504
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004505 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004506 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004507 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004508 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004509 OS << " --> ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004510 const SCEV* SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004511 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512
Dan Gohman8db598a2009-06-19 17:49:54 +00004513 const Loop *L = LI->getLoopFor((*I).getParent());
4514
Owen Andersonecd0cd72009-06-22 21:39:50 +00004515 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004516 if (AtUse != SV) {
4517 OS << " --> ";
4518 AtUse->print(OS);
4519 }
4520
4521 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004522 OS << "\t\t" "Exits: ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004523 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004524 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004525 OS << "<<Unknown>>";
4526 } else {
4527 OS << *ExitValue;
4528 }
4529 }
4530
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004531 OS << "\n";
4532 }
4533
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004534 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4535 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4536 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004537}
Dan Gohman13058cc2009-04-21 00:47:46 +00004538
4539void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4540 raw_os_ostream OS(o);
4541 print(OS, M);
4542}