blob: 7c68f8920e098ca20c8e8f08d8f76795fa30590b [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
Dan Gohman161ea032009-07-07 17:06:11 +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"
Owen Andersone755b092009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000070#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000074#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Edwin Török675d5622009-07-11 20:10:48 +000078#include "llvm/Support/ErrorHandling.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000079#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080#include "llvm/Support/InstIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanb7d04aa2009-07-08 19:23:34 +000085#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087using namespace llvm;
88
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman089efff2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman9bc642f2009-06-24 04:48:43 +0000101 "symbolically execute a constant "
102 "derived loop"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000116
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117SCEV::~SCEV() {}
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000118
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000120 print(errs());
121 errs() << '\n';
122}
123
124void SCEV::print(std::ostream &o) const {
125 raw_os_ostream OS(o);
126 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127}
128
Dan Gohman7b560c42008-06-18 16:23:07 +0000129bool SCEV::isZero() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isZero();
132 return false;
133}
134
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000135bool SCEV::isOne() const {
136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
137 return SC->getValue()->isOne();
138 return false;
139}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
Dan Gohmanf05118e2009-06-24 00:30:26 +0000141bool SCEV::isAllOnesValue() const {
142 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
143 return SC->getValue()->isAllOnesValue();
144 return false;
145}
146
Owen Andersonb70139d2009-06-22 21:57:23 +0000147SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmand43a8282009-07-13 20:50:19 +0000148 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000149
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Edwin Törökbd448e32009-07-14 16:55:14 +0000151 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 return false;
153}
154
155const Type *SCEVCouldNotCompute::getType() const {
Edwin Törökbd448e32009-07-14 16:55:14 +0000156 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 return 0;
158}
159
160bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Edwin Törökbd448e32009-07-14 16:55:14 +0000161 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 return false;
163}
164
Dan Gohman9bc642f2009-06-24 04:48:43 +0000165const SCEV *
166SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
167 const SCEV *Sym,
168 const SCEV *Conc,
169 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 return this;
171}
172
Dan Gohman13058cc2009-04-21 00:47:46 +0000173void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 OS << "***COULDNOTCOMPUTE***";
175}
176
177bool SCEVCouldNotCompute::classof(const SCEV *S) {
178 return S->getSCEVType() == scCouldNotCompute;
179}
180
Dan Gohman161ea032009-07-07 17:06:11 +0000181const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000182 FoldingSetNodeID ID;
183 ID.AddInteger(scConstant);
184 ID.AddPointer(V);
185 void *IP = 0;
186 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
187 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000188 new (S) SCEVConstant(ID, V);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000189 UniqueSCEVs.InsertNode(S, IP);
190 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191}
192
Dan Gohman161ea032009-07-07 17:06:11 +0000193const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000194 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195}
196
Dan Gohman161ea032009-07-07 17:06:11 +0000197const SCEV *
Dan Gohman8fd520a2009-06-15 22:12:54 +0000198ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9f5b2aa2009-07-14 23:09:55 +0000199 return getConstant(
200 Context->getConstantInt(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman8fd520a2009-06-15 22:12:54 +0000201}
202
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203const Type *SCEVConstant::getType() const { return V->getType(); }
204
Dan Gohman13058cc2009-04-21 00:47:46 +0000205void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 WriteAsOperand(OS, V, false);
207}
208
Dan Gohmand43a8282009-07-13 20:50:19 +0000209SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
210 unsigned SCEVTy, const SCEV *op, const Type *ty)
211 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000212
Dan Gohman2a381532009-04-21 01:25:57 +0000213bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
214 return Op->dominates(BB, DT);
215}
216
Dan Gohmand43a8282009-07-13 20:50:19 +0000217SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
218 const SCEV *op, const Type *ty)
219 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000220 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
221 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223}
224
Dan Gohman13058cc2009-04-21 00:47:46 +0000225void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000226 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227}
228
Dan Gohmand43a8282009-07-13 20:50:19 +0000229SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
230 const SCEV *op, const Type *ty)
231 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000232 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
233 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235}
236
Dan Gohman13058cc2009-04-21 00:47:46 +0000237void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000238 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239}
240
Dan Gohmand43a8282009-07-13 20:50:19 +0000241SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
242 const SCEV *op, const Type *ty)
243 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000244 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
245 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247}
248
Dan Gohman13058cc2009-04-21 00:47:46 +0000249void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000250 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251}
252
Dan Gohman13058cc2009-04-21 00:47:46 +0000253void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
255 const char *OpStr = getOperationStr();
256 OS << "(" << *Operands[0];
257 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
258 OS << OpStr << *Operands[i];
259 OS << ")";
260}
261
Dan Gohman9bc642f2009-06-24 04:48:43 +0000262const SCEV *
263SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
264 const SCEV *Sym,
265 const SCEV *Conc,
266 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000268 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000269 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000271 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 NewOps.reserve(getNumOperands());
273 for (unsigned j = 0; j != i; ++j)
274 NewOps.push_back(getOperand(j));
275 NewOps.push_back(H);
276 for (++i; i != e; ++i)
277 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000278 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279
280 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000281 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000283 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000284 else if (isa<SCEVSMaxExpr>(this))
285 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000286 else if (isa<SCEVUMaxExpr>(this))
287 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000289 llvm_unreachable("Unknown commutative expr!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 }
291 }
292 return this;
293}
294
Dan Gohman72a8a022009-05-07 14:00:19 +0000295bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000296 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
297 if (!getOperand(i)->dominates(BB, DT))
298 return false;
299 }
300 return true;
301}
302
Evan Cheng98c073b2009-02-17 00:13:06 +0000303bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
304 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
305}
306
Dan Gohman13058cc2009-04-21 00:47:46 +0000307void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000308 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309}
310
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000311const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000312 // In most cases the types of LHS and RHS will be the same, but in some
313 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
314 // depend on the type for correctness, but handling types carefully can
315 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
316 // a pointer type than the RHS, so use the RHS' type here.
317 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318}
319
Dan Gohman9bc642f2009-06-24 04:48:43 +0000320const SCEV *
321SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
322 const SCEV *Conc,
323 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000325 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000326 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000328 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 NewOps.reserve(getNumOperands());
330 for (unsigned j = 0; j != i; ++j)
331 NewOps.push_back(getOperand(j));
332 NewOps.push_back(H);
333 for (++i; i != e; ++i)
334 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000335 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
Dan Gohman89f85052007-10-22 18:31:58 +0000337 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 }
339 }
340 return this;
341}
342
343
344bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000345 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000346 if (!QueryLoop)
347 return false;
348
349 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
350 if (QueryLoop->contains(L->getHeader()))
351 return false;
352
353 // This recurrence is variant w.r.t. QueryLoop if any of its operands
354 // are variant.
355 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
356 if (!getOperand(i)->isLoopInvariant(QueryLoop))
357 return false;
358
359 // Otherwise it's loop-invariant.
360 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361}
362
Dan Gohman13058cc2009-04-21 00:47:46 +0000363void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 OS << "{" << *Operands[0];
365 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
366 OS << ",+," << *Operands[i];
367 OS << "}<" << L->getHeader()->getName() + ">";
368}
369
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
371 // All non-instruction values are loop invariant. All instructions are loop
372 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000373 // Instructions are never considered invariant in the function body
374 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000376 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 return true;
378}
379
Evan Cheng98c073b2009-02-17 00:13:06 +0000380bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
381 if (Instruction *I = dyn_cast<Instruction>(getValue()))
382 return DT->dominates(I->getParent(), BB);
383 return true;
384}
385
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386const Type *SCEVUnknown::getType() const {
387 return V->getType();
388}
389
Dan Gohman13058cc2009-04-21 00:47:46 +0000390void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 WriteAsOperand(OS, V, false);
392}
393
394//===----------------------------------------------------------------------===//
395// SCEV Utilities
396//===----------------------------------------------------------------------===//
397
398namespace {
399 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
400 /// than the complexity of the RHS. This comparator is used to canonicalize
401 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000402 class VISIBILITY_HIDDEN SCEVComplexityCompare {
403 LoopInfo *LI;
404 public:
405 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
406
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000407 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000408 // Primarily, sort the SCEVs by their getSCEVType().
409 if (LHS->getSCEVType() != RHS->getSCEVType())
410 return LHS->getSCEVType() < RHS->getSCEVType();
411
412 // Aside from the getSCEVType() ordering, the particular ordering
413 // isn't very important except that it's beneficial to be consistent,
414 // so that (a + b) and (b + a) don't end up as different expressions.
415
416 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
417 // not as complete as it could be.
418 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
419 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
420
Dan Gohmand0c01232009-05-19 02:15:55 +0000421 // Order pointer values after integer values. This helps SCEVExpander
422 // form GEPs.
423 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
424 return false;
425 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
426 return true;
427
Dan Gohman5d486452009-05-07 14:39:04 +0000428 // Compare getValueID values.
429 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
430 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
431
432 // Sort arguments by their position.
433 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
434 const Argument *RA = cast<Argument>(RU->getValue());
435 return LA->getArgNo() < RA->getArgNo();
436 }
437
438 // For instructions, compare their loop depth, and their opcode.
439 // This is pretty loose.
440 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
441 Instruction *RV = cast<Instruction>(RU->getValue());
442
443 // Compare loop depths.
444 if (LI->getLoopDepth(LV->getParent()) !=
445 LI->getLoopDepth(RV->getParent()))
446 return LI->getLoopDepth(LV->getParent()) <
447 LI->getLoopDepth(RV->getParent());
448
449 // Compare opcodes.
450 if (LV->getOpcode() != RV->getOpcode())
451 return LV->getOpcode() < RV->getOpcode();
452
453 // Compare the number of operands.
454 if (LV->getNumOperands() != RV->getNumOperands())
455 return LV->getNumOperands() < RV->getNumOperands();
456 }
457
458 return false;
459 }
460
Dan Gohman56fc8f12009-06-14 22:51:25 +0000461 // Compare constant values.
462 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
463 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewycky9bb14052009-07-04 17:24:52 +0000464 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
465 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman56fc8f12009-06-14 22:51:25 +0000466 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
467 }
468
469 // Compare addrec loop depths.
470 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
471 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
472 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
473 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
474 }
Dan Gohman5d486452009-05-07 14:39:04 +0000475
476 // Lexicographically compare n-ary expressions.
477 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
478 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
479 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
480 if (i >= RC->getNumOperands())
481 return false;
482 if (operator()(LC->getOperand(i), RC->getOperand(i)))
483 return true;
484 if (operator()(RC->getOperand(i), LC->getOperand(i)))
485 return false;
486 }
487 return LC->getNumOperands() < RC->getNumOperands();
488 }
489
Dan Gohman6e10db12009-05-07 19:23:21 +0000490 // Lexicographically compare udiv expressions.
491 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
492 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
493 if (operator()(LC->getLHS(), RC->getLHS()))
494 return true;
495 if (operator()(RC->getLHS(), LC->getLHS()))
496 return false;
497 if (operator()(LC->getRHS(), RC->getRHS()))
498 return true;
499 if (operator()(RC->getRHS(), LC->getRHS()))
500 return false;
501 return false;
502 }
503
Dan Gohman5d486452009-05-07 14:39:04 +0000504 // Compare cast expressions by operand.
505 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
506 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
507 return operator()(LC->getOperand(), RC->getOperand());
508 }
509
Edwin Törökbd448e32009-07-14 16:55:14 +0000510 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman5d486452009-05-07 14:39:04 +0000511 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 }
513 };
514}
515
516/// GroupByComplexity - Given a list of SCEV objects, order them by their
517/// complexity, and group objects of the same complexity together by value.
518/// When this routine is finished, we know that any duplicates in the vector are
519/// consecutive and that complexity is monotonically increasing.
520///
521/// Note that we go take special precautions to ensure that we get determinstic
522/// results from this routine. In other words, we don't want the results of
523/// this to depend on where the addresses of various SCEV objects happened to
524/// land in memory.
525///
Dan Gohman161ea032009-07-07 17:06:11 +0000526static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000527 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 if (Ops.size() < 2) return; // Noop
529 if (Ops.size() == 2) {
530 // This is the common case, which also happens to be trivially simple.
531 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000532 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 std::swap(Ops[0], Ops[1]);
534 return;
535 }
536
537 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000538 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539
540 // Now that we are sorted by complexity, group elements of the same
541 // complexity. Note that this is, at worst, N^2, but the vector is likely to
542 // be extremely short in practice. Note that we take this approach because we
543 // do not want to depend on the addresses of the objects we are grouping.
544 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000545 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 unsigned Complexity = S->getSCEVType();
547
548 // If there are any objects of the same complexity and same value as this
549 // one, group them.
550 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
551 if (Ops[j] == S) { // Found a duplicate.
552 // Move it to immediately after i'th element.
553 std::swap(Ops[i+1], Ops[j]);
554 ++i; // no need to rescan it.
555 if (i == e-2) return; // Done!
556 }
557 }
558 }
559}
560
561
562
563//===----------------------------------------------------------------------===//
564// Simple SCEV method implementations
565//===----------------------------------------------------------------------===//
566
Eli Friedman7489ec92008-08-04 23:49:06 +0000567/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000568/// Assume, K > 0.
Dan Gohman161ea032009-07-07 17:06:11 +0000569static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000570 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000571 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000572 // Handle the simplest case efficiently.
573 if (K == 1)
574 return SE.getTruncateOrZeroExtend(It, ResultTy);
575
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000576 // We are using the following formula for BC(It, K):
577 //
578 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
579 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000580 // Suppose, W is the bitwidth of the return value. We must be prepared for
581 // overflow. Hence, we must assure that the result of our computation is
582 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
583 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000584 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000585 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000586 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000587 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
588 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000589 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000590 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000591 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000592 // This formula is trivially equivalent to the previous formula. However,
593 // this formula can be implemented much more efficiently. The trick is that
594 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
595 // arithmetic. To do exact division in modular arithmetic, all we have
596 // to do is multiply by the inverse. Therefore, this step can be done at
597 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000598 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000599 // The next issue is how to safely do the division by 2^T. The way this
600 // is done is by doing the multiplication step at a width of at least W + T
601 // bits. This way, the bottom W+T bits of the product are accurate. Then,
602 // when we perform the division by 2^T (which is equivalent to a right shift
603 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
604 // truncated out after the division by 2^T.
605 //
606 // In comparison to just directly using the first formula, this technique
607 // is much more efficient; using the first formula requires W * K bits,
608 // but this formula less than W + K bits. Also, the first formula requires
609 // a division step, whereas this formula only requires multiplies and shifts.
610 //
611 // It doesn't matter whether the subtraction step is done in the calculation
612 // width or the input iteration count's width; if the subtraction overflows,
613 // the result must be zero anyway. We prefer here to do it in the width of
614 // the induction variable because it helps a lot for certain cases; CodeGen
615 // isn't smart enough to ignore the overflow, which leads to much less
616 // efficient code if the width of the subtraction is wider than the native
617 // register width.
618 //
619 // (It's possible to not widen at all by pulling out factors of 2 before
620 // the multiplication; for example, K=2 can be calculated as
621 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
622 // extra arithmetic, so it's not an obvious win, and it gets
623 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000624
Eli Friedman7489ec92008-08-04 23:49:06 +0000625 // Protection from insane SCEVs; this bound is conservative,
626 // but it probably doesn't matter.
627 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000628 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000629
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000630 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000631
Eli Friedman7489ec92008-08-04 23:49:06 +0000632 // Calculate K! / 2^T and T; we divide out the factors of two before
633 // multiplying for calculating K! / 2^T to avoid overflow.
634 // Other overflow doesn't matter because we only care about the bottom
635 // W bits of the result.
636 APInt OddFactorial(W, 1);
637 unsigned T = 1;
638 for (unsigned i = 3; i <= K; ++i) {
639 APInt Mult(W, i);
640 unsigned TwoFactors = Mult.countTrailingZeros();
641 T += TwoFactors;
642 Mult = Mult.lshr(TwoFactors);
643 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000645
Eli Friedman7489ec92008-08-04 23:49:06 +0000646 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000647 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000648
649 // Calcuate 2^T, at width T+W.
650 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
651
652 // Calculate the multiplicative inverse of K! / 2^T;
653 // this multiplication factor will perform the exact division by
654 // K! / 2^T.
655 APInt Mod = APInt::getSignedMinValue(W+1);
656 APInt MultiplyFactor = OddFactorial.zext(W+1);
657 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
658 MultiplyFactor = MultiplyFactor.trunc(W);
659
660 // Calculate the product, at width T+W
661 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman161ea032009-07-07 17:06:11 +0000662 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000663 for (unsigned i = 1; i != K; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000664 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000665 Dividend = SE.getMulExpr(Dividend,
666 SE.getTruncateOrZeroExtend(S, CalculationTy));
667 }
668
669 // Divide by 2^T
Dan Gohman161ea032009-07-07 17:06:11 +0000670 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000671
672 // Truncate the result, and divide by K! / 2^T.
673
674 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
675 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676}
677
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678/// evaluateAtIteration - Return the value of this chain of recurrences at
679/// the specified iteration number. We can evaluate this recurrence by
680/// multiplying each element in the chain by the binomial coefficient
681/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
682///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000683/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000685/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686///
Dan Gohman161ea032009-07-07 17:06:11 +0000687const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman89f85052007-10-22 18:31:58 +0000688 ScalarEvolution &SE) const {
Dan Gohman161ea032009-07-07 17:06:11 +0000689 const SCEV *Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000691 // The computation is correct in the face of overflow provided that the
692 // multiplication is performed _after_ the evaluation of the binomial
693 // coefficient.
Dan Gohman161ea032009-07-07 17:06:11 +0000694 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000695 if (isa<SCEVCouldNotCompute>(Coeff))
696 return Coeff;
697
698 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 }
700 return Result;
701}
702
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703//===----------------------------------------------------------------------===//
704// SCEV Expression folder implementations
705//===----------------------------------------------------------------------===//
706
Dan Gohman161ea032009-07-07 17:06:11 +0000707const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohman69eacc72009-07-13 22:05:32 +0000708 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000709 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000710 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000711 assert(isSCEVable(Ty) &&
712 "This is not a conversion to a SCEVable type!");
713 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000714
Dan Gohmand43a8282009-07-13 20:50:19 +0000715 FoldingSetNodeID ID;
716 ID.AddInteger(scTruncate);
717 ID.AddPointer(Op);
718 ID.AddPointer(Ty);
719 void *IP = 0;
720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
721
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000722 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000724 return getConstant(
725 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726
Dan Gohman1a5c4992009-04-22 16:20:48 +0000727 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000728 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000729 return getTruncateExpr(ST->getOperand(), Ty);
730
Nick Lewycky37d04642009-04-23 05:15:08 +0000731 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000732 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000733 return getTruncateOrSignExtend(SS->getOperand(), Ty);
734
735 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000736 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000737 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
738
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000739 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000741 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000743 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
744 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 }
746
Dan Gohmand43a8282009-07-13 20:50:19 +0000747 // The cast wasn't folded; create an explicit cast node.
748 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000749 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
750 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000751 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000752 UniqueSCEVs.InsertNode(S, IP);
753 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754}
755
Dan Gohman161ea032009-07-07 17:06:11 +0000756const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohman69eacc72009-07-13 22:05:32 +0000757 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000758 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000759 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000760 assert(isSCEVable(Ty) &&
761 "This is not a conversion to a SCEVable type!");
762 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000763
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000764 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000766 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000767 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
768 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000769 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771
Dan Gohman1a5c4992009-04-22 16:20:48 +0000772 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000773 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000774 return getZeroExtendExpr(SZ->getOperand(), Ty);
775
Dan Gohmandb888422009-07-13 20:55:53 +0000776 // Before doing any expensive analysis, check to see if we've already
777 // computed a SCEV for this Op and Ty.
778 FoldingSetNodeID ID;
779 ID.AddInteger(scZeroExtend);
780 ID.AddPointer(Op);
781 ID.AddPointer(Ty);
782 void *IP = 0;
783 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
784
Dan Gohmana9dba962009-04-27 20:16:15 +0000785 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000787 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000790 if (AR->isAffine()) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000791 const SCEV *Start = AR->getStart();
792 const SCEV *Step = AR->getStepRecurrence(*this);
793 unsigned BitWidth = getTypeSizeInBits(AR->getType());
794 const Loop *L = AR->getLoop();
795
Dan Gohmana9dba962009-04-27 20:16:15 +0000796 // Check whether the backedge-taken count is SCEVCouldNotCompute.
797 // Note that this serves two purposes: It filters out loops that are
798 // simply not analyzable, and it covers the case where this code is
799 // being called from within backedge-taken count analysis, such that
800 // attempting to ask for the backedge-taken count would likely result
801 // in infinite recursion. In the later case, the analysis code will
802 // cope with a conservative value, and it will take care to purge
803 // that value once it has finished.
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000804 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000805 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000806 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000807 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000808
809 // Check whether the backedge-taken count can be losslessly casted to
810 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000811 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000812 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000813 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000814 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
815 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000816 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000817 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000818 const SCEV *ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000819 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000820 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000821 const SCEV *Add = getAddExpr(Start, ZMul);
822 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000823 getAddExpr(getZeroExtendExpr(Start, WideTy),
824 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
825 getZeroExtendExpr(Step, WideTy)));
826 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000827 // Return the expression with the addrec on the outside.
828 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
829 getZeroExtendExpr(Step, Ty),
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000830 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000831
832 // Similar to above, only this time treat the step value as signed.
833 // This covers loops that count down.
Dan Gohman161ea032009-07-07 17:06:11 +0000834 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000835 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000836 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000837 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000838 OperandExtendedAdd =
839 getAddExpr(getZeroExtendExpr(Start, WideTy),
840 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
841 getSignExtendExpr(Step, WideTy)));
842 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000843 // Return the expression with the addrec on the outside.
844 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
845 getSignExtendExpr(Step, Ty),
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000846 L);
847 }
848
849 // If the backedge is guarded by a comparison with the pre-inc value
850 // the addrec is safe. Also, if the entry is guarded by a comparison
851 // with the start value and the backedge is guarded by a comparison
852 // with the post-inc value, the addrec is safe.
853 if (isKnownPositive(Step)) {
854 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
855 getUnsignedRange(Step).getUnsignedMax());
856 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
857 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
858 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
859 AR->getPostIncExpr(*this), N)))
860 // Return the expression with the addrec on the outside.
861 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
862 getZeroExtendExpr(Step, Ty),
863 L);
864 } else if (isKnownNegative(Step)) {
865 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
866 getSignedRange(Step).getSignedMin());
867 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
868 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
869 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
870 AR->getPostIncExpr(*this), N)))
871 // Return the expression with the addrec on the outside.
872 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
873 getSignExtendExpr(Step, Ty),
874 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000875 }
876 }
877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878
Dan Gohmandb888422009-07-13 20:55:53 +0000879 // The cast wasn't folded; create an explicit cast node.
880 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000881 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
882 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000883 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000884 UniqueSCEVs.InsertNode(S, IP);
885 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886}
887
Dan Gohman161ea032009-07-07 17:06:11 +0000888const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohman69eacc72009-07-13 22:05:32 +0000889 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000890 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000891 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000892 assert(isSCEVable(Ty) &&
893 "This is not a conversion to a SCEVable type!");
894 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000895
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000896 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000897 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000898 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000899 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
900 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000901 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000902 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903
Dan Gohman1a5c4992009-04-22 16:20:48 +0000904 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000905 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000906 return getSignExtendExpr(SS->getOperand(), Ty);
907
Dan Gohmandb888422009-07-13 20:55:53 +0000908 // Before doing any expensive analysis, check to see if we've already
909 // computed a SCEV for this Op and Ty.
910 FoldingSetNodeID ID;
911 ID.AddInteger(scSignExtend);
912 ID.AddPointer(Op);
913 ID.AddPointer(Ty);
914 void *IP = 0;
915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
916
Dan Gohmana9dba962009-04-27 20:16:15 +0000917 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000918 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000919 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000921 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000922 if (AR->isAffine()) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000923 const SCEV *Start = AR->getStart();
924 const SCEV *Step = AR->getStepRecurrence(*this);
925 unsigned BitWidth = getTypeSizeInBits(AR->getType());
926 const Loop *L = AR->getLoop();
927
Dan Gohmana9dba962009-04-27 20:16:15 +0000928 // Check whether the backedge-taken count is SCEVCouldNotCompute.
929 // Note that this serves two purposes: It filters out loops that are
930 // simply not analyzable, and it covers the case where this code is
931 // being called from within backedge-taken count analysis, such that
932 // attempting to ask for the backedge-taken count would likely result
933 // in infinite recursion. In the later case, the analysis code will
934 // cope with a conservative value, and it will take care to purge
935 // that value once it has finished.
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000936 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000937 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000938 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000939 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000940
941 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000942 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000943 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000944 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000945 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000946 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
947 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000948 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000949 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000950 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000951 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000952 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000953 const SCEV *Add = getAddExpr(Start, SMul);
954 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000955 getAddExpr(getSignExtendExpr(Start, WideTy),
956 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
957 getSignExtendExpr(Step, WideTy)));
958 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000959 // Return the expression with the addrec on the outside.
960 return getAddRecExpr(getSignExtendExpr(Start, Ty),
961 getSignExtendExpr(Step, Ty),
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000962 L);
963 }
964
965 // If the backedge is guarded by a comparison with the pre-inc value
966 // the addrec is safe. Also, if the entry is guarded by a comparison
967 // with the start value and the backedge is guarded by a comparison
968 // with the post-inc value, the addrec is safe.
969 if (isKnownPositive(Step)) {
970 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
971 getSignedRange(Step).getSignedMax());
972 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
973 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
974 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
975 AR->getPostIncExpr(*this), N)))
976 // Return the expression with the addrec on the outside.
977 return getAddRecExpr(getSignExtendExpr(Start, Ty),
978 getSignExtendExpr(Step, Ty),
979 L);
980 } else if (isKnownNegative(Step)) {
981 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
982 getSignedRange(Step).getSignedMin());
983 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
984 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
985 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
986 AR->getPostIncExpr(*this), N)))
987 // Return the expression with the addrec on the outside.
988 return getAddRecExpr(getSignExtendExpr(Start, Ty),
989 getSignExtendExpr(Step, Ty),
990 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000991 }
992 }
993 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994
Dan Gohmandb888422009-07-13 20:55:53 +0000995 // The cast wasn't folded; create an explicit cast node.
996 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000997 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
998 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000999 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001000 UniqueSCEVs.InsertNode(S, IP);
1001 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002}
1003
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001004/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1005/// unspecified bits out to the given type.
1006///
Dan Gohman161ea032009-07-07 17:06:11 +00001007const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001008 const Type *Ty) {
1009 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1010 "This is not an extending conversion!");
1011 assert(isSCEVable(Ty) &&
1012 "This is not a conversion to a SCEVable type!");
1013 Ty = getEffectiveSCEVType(Ty);
1014
1015 // Sign-extend negative constants.
1016 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1017 if (SC->getValue()->getValue().isNegative())
1018 return getSignExtendExpr(Op, Ty);
1019
1020 // Peel off a truncate cast.
1021 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001022 const SCEV *NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001023 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1024 return getAnyExtendExpr(NewOp, Ty);
1025 return getTruncateOrNoop(NewOp, Ty);
1026 }
1027
1028 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +00001029 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001030 if (!isa<SCEVZeroExtendExpr>(ZExt))
1031 return ZExt;
1032
1033 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +00001034 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001035 if (!isa<SCEVSignExtendExpr>(SExt))
1036 return SExt;
1037
1038 // If the expression is obviously signed, use the sext cast value.
1039 if (isa<SCEVSMaxExpr>(Op))
1040 return SExt;
1041
1042 // Absent any other information, use the zext cast value.
1043 return ZExt;
1044}
1045
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001046/// CollectAddOperandsWithScales - Process the given Ops list, which is
1047/// a list of operands to be added under the given scale, update the given
1048/// map. This is a helper function for getAddRecExpr. As an example of
1049/// what it does, given a sequence of operands that would form an add
1050/// expression like this:
1051///
1052/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1053///
1054/// where A and B are constants, update the map with these values:
1055///
1056/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1057///
1058/// and add 13 + A*B*29 to AccumulatedConstant.
1059/// This will allow getAddRecExpr to produce this:
1060///
1061/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1062///
1063/// This form often exposes folding opportunities that are hidden in
1064/// the original operand list.
1065///
1066/// Return true iff it appears that any interesting folding opportunities
1067/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1068/// the common case where no interesting opportunities are present, and
1069/// is also used as a check to avoid infinite recursion.
1070///
1071static bool
Dan Gohman161ea032009-07-07 17:06:11 +00001072CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1073 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001074 APInt &AccumulatedConstant,
Dan Gohman161ea032009-07-07 17:06:11 +00001075 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001076 const APInt &Scale,
1077 ScalarEvolution &SE) {
1078 bool Interesting = false;
1079
1080 // Iterate over the add operands.
1081 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1082 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1083 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1084 APInt NewScale =
1085 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1086 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1087 // A multiplication of a constant with another add; recurse.
1088 Interesting |=
1089 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1090 cast<SCEVAddExpr>(Mul->getOperand(1))
1091 ->getOperands(),
1092 NewScale, SE);
1093 } else {
1094 // A multiplication of a constant with some other value. Update
1095 // the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001096 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1097 const SCEV *Key = SE.getMulExpr(MulOps);
1098 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001099 M.insert(std::make_pair(Key, NewScale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001100 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001101 NewOps.push_back(Pair.first->first);
1102 } else {
1103 Pair.first->second += NewScale;
1104 // The map already had an entry for this value, which may indicate
1105 // a folding opportunity.
1106 Interesting = true;
1107 }
1108 }
1109 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1110 // Pull a buried constant out to the outside.
1111 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1112 Interesting = true;
1113 AccumulatedConstant += Scale * C->getValue()->getValue();
1114 } else {
1115 // An ordinary operand. Update the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001116 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001117 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001118 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001119 NewOps.push_back(Pair.first->first);
1120 } else {
1121 Pair.first->second += Scale;
1122 // The map already had an entry for this value, which may indicate
1123 // a folding opportunity.
1124 Interesting = true;
1125 }
1126 }
1127 }
1128
1129 return Interesting;
1130}
1131
1132namespace {
1133 struct APIntCompare {
1134 bool operator()(const APInt &LHS, const APInt &RHS) const {
1135 return LHS.ult(RHS);
1136 }
1137 };
1138}
1139
Dan Gohmanc8a29272009-05-24 23:45:28 +00001140/// getAddExpr - Get a canonical add expression, or something simpler if
1141/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001142const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 assert(!Ops.empty() && "Cannot get empty add!");
1144 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001145#ifndef NDEBUG
1146 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1147 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1148 getEffectiveSCEVType(Ops[0]->getType()) &&
1149 "SCEVAddExpr operand types don't match!");
1150#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151
1152 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001153 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154
1155 // If there are any constants, fold them together.
1156 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001157 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 ++Idx;
1159 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001160 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001162 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1163 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001164 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001165 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001166 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 }
1168
1169 // If we are left with a constant zero being added, strip it off.
1170 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1171 Ops.erase(Ops.begin());
1172 --Idx;
1173 }
1174 }
1175
1176 if (Ops.size() == 1) return Ops[0];
1177
1178 // Okay, check to see if the same value occurs in the operand list twice. If
1179 // so, merge them together into an multiply expression. Since we sorted the
1180 // list, these values are required to be adjacent.
1181 const Type *Ty = Ops[0]->getType();
1182 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1183 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1184 // Found a match, merge the two values into a multiply, and add any
1185 // remaining values to the result.
Dan Gohman161ea032009-07-07 17:06:11 +00001186 const SCEV *Two = getIntegerSCEV(2, Ty);
1187 const SCEV *Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 if (Ops.size() == 2)
1189 return Mul;
1190 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1191 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001192 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 }
1194
Dan Gohman45b3b542009-05-08 21:03:19 +00001195 // Check for truncates. If all the operands are truncated from the same
1196 // type, see if factoring out the truncate would permit the result to be
1197 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1198 // if the contents of the resulting outer trunc fold to something simple.
1199 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1200 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1201 const Type *DstType = Trunc->getType();
1202 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00001203 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001204 bool Ok = true;
1205 // Check all the operands to see if they can be represented in the
1206 // source type of the truncate.
1207 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1208 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1209 if (T->getOperand()->getType() != SrcType) {
1210 Ok = false;
1211 break;
1212 }
1213 LargeOps.push_back(T->getOperand());
1214 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1215 // This could be either sign or zero extension, but sign extension
1216 // is much more likely to be foldable here.
1217 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1218 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman161ea032009-07-07 17:06:11 +00001219 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001220 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1221 if (const SCEVTruncateExpr *T =
1222 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1223 if (T->getOperand()->getType() != SrcType) {
1224 Ok = false;
1225 break;
1226 }
1227 LargeMulOps.push_back(T->getOperand());
1228 } else if (const SCEVConstant *C =
1229 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1230 // This could be either sign or zero extension, but sign extension
1231 // is much more likely to be foldable here.
1232 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1233 } else {
1234 Ok = false;
1235 break;
1236 }
1237 }
1238 if (Ok)
1239 LargeOps.push_back(getMulExpr(LargeMulOps));
1240 } else {
1241 Ok = false;
1242 break;
1243 }
1244 }
1245 if (Ok) {
1246 // Evaluate the expression in the larger type.
Dan Gohman161ea032009-07-07 17:06:11 +00001247 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001248 // If it folds to something simple, use it. Otherwise, don't.
1249 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1250 return getTruncateExpr(Fold, DstType);
1251 }
1252 }
1253
1254 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1256 ++Idx;
1257
1258 // If there are add operands they would be next.
1259 if (Idx < Ops.size()) {
1260 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001261 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 // If we have an add, expand the add operands onto the end of the operands
1263 // list.
1264 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1265 Ops.erase(Ops.begin()+Idx);
1266 DeletedAdd = true;
1267 }
1268
1269 // If we deleted at least one add, we added operands to the end of the list,
1270 // and they are not necessarily sorted. Recurse to resort and resimplify
1271 // any operands we just aquired.
1272 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001273 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 }
1275
1276 // Skip over the add expression until we get to a multiply.
1277 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1278 ++Idx;
1279
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001280 // Check to see if there are any folding opportunities present with
1281 // operands multiplied by constant values.
1282 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1283 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00001284 DenseMap<const SCEV *, APInt> M;
1285 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001286 APInt AccumulatedConstant(BitWidth, 0);
1287 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1288 Ops, APInt(BitWidth, 1), *this)) {
1289 // Some interesting folding opportunity is present, so its worthwhile to
1290 // re-generate the operands list. Group the operands by constant scale,
1291 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman161ea032009-07-07 17:06:11 +00001292 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1293 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001294 E = NewOps.end(); I != E; ++I)
1295 MulOpLists[M.find(*I)->second].push_back(*I);
1296 // Re-generate the operands list.
1297 Ops.clear();
1298 if (AccumulatedConstant != 0)
1299 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001300 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1301 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001302 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001303 Ops.push_back(getMulExpr(getConstant(I->first),
1304 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001305 if (Ops.empty())
1306 return getIntegerSCEV(0, Ty);
1307 if (Ops.size() == 1)
1308 return Ops[0];
1309 return getAddExpr(Ops);
1310 }
1311 }
1312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 // If we are adding something to a multiply expression, make sure the
1314 // something is not already an operand of the multiply. If so, merge it into
1315 // the multiply.
1316 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001317 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001319 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001321 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman161ea032009-07-07 17:06:11 +00001323 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 if (Mul->getNumOperands() != 2) {
1325 // If the multiply has more than two operands, we must get the
1326 // Y*Z term.
Dan Gohman161ea032009-07-07 17:06:11 +00001327 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001329 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 }
Dan Gohman161ea032009-07-07 17:06:11 +00001331 const SCEV *One = getIntegerSCEV(1, Ty);
1332 const SCEV *AddOne = getAddExpr(InnerMul, One);
1333 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 if (Ops.size() == 2) return OuterMul;
1335 if (AddOp < Idx) {
1336 Ops.erase(Ops.begin()+AddOp);
1337 Ops.erase(Ops.begin()+Idx-1);
1338 } else {
1339 Ops.erase(Ops.begin()+Idx);
1340 Ops.erase(Ops.begin()+AddOp-1);
1341 }
1342 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001343 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 }
1345
1346 // Check this multiply against other multiplies being added together.
1347 for (unsigned OtherMulIdx = Idx+1;
1348 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1349 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001350 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 // If MulOp occurs in OtherMul, we can fold the two multiplies
1352 // together.
1353 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1354 OMulOp != e; ++OMulOp)
1355 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1356 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman161ea032009-07-07 17:06:11 +00001357 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001359 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1360 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001362 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 }
Dan Gohman161ea032009-07-07 17:06:11 +00001364 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001366 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1367 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001369 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 }
Dan Gohman161ea032009-07-07 17:06:11 +00001371 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1372 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 if (Ops.size() == 2) return OuterMul;
1374 Ops.erase(Ops.begin()+Idx);
1375 Ops.erase(Ops.begin()+OtherMulIdx-1);
1376 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001377 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001378 }
1379 }
1380 }
1381 }
1382
1383 // If there are any add recurrences in the operands list, see if any other
1384 // added values are loop invariant. If so, we can fold them into the
1385 // recurrence.
1386 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1387 ++Idx;
1388
1389 // Scan over all recurrences, trying to fold loop invariants into them.
1390 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1391 // Scan all of the other operands to this add and add them to the vector if
1392 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001393 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001394 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1396 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1397 LIOps.push_back(Ops[i]);
1398 Ops.erase(Ops.begin()+i);
1399 --i; --e;
1400 }
1401
1402 // If we found some loop invariants, fold them into the recurrence.
1403 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001404 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 LIOps.push_back(AddRec->getStart());
1406
Dan Gohman161ea032009-07-07 17:06:11 +00001407 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001408 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001409 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410
Dan Gohman161ea032009-07-07 17:06:11 +00001411 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 // If all of the other operands were loop invariant, we are done.
1413 if (Ops.size() == 1) return NewRec;
1414
1415 // Otherwise, add the folded AddRec by the non-liv parts.
1416 for (unsigned i = 0;; ++i)
1417 if (Ops[i] == AddRec) {
1418 Ops[i] = NewRec;
1419 break;
1420 }
Dan Gohman89f85052007-10-22 18:31:58 +00001421 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 }
1423
1424 // Okay, if there weren't any loop invariants to be folded, check to see if
1425 // there are multiple AddRec's with the same loop induction variable being
1426 // added together. If so, we can fold them.
1427 for (unsigned OtherIdx = Idx+1;
1428 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1429 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001430 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1432 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001433 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1434 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1436 if (i >= NewOps.size()) {
1437 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1438 OtherAddRec->op_end());
1439 break;
1440 }
Dan Gohman89f85052007-10-22 18:31:58 +00001441 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 }
Dan Gohman161ea032009-07-07 17:06:11 +00001443 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444
1445 if (Ops.size() == 2) return NewAddRec;
1446
1447 Ops.erase(Ops.begin()+Idx);
1448 Ops.erase(Ops.begin()+OtherIdx-1);
1449 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001450 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 }
1452 }
1453
1454 // Otherwise couldn't fold anything into this recurrence. Move onto the
1455 // next one.
1456 }
1457
1458 // Okay, it looks like we really DO need an add expr. Check to see if we
1459 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001460 FoldingSetNodeID ID;
1461 ID.AddInteger(scAddExpr);
1462 ID.AddInteger(Ops.size());
1463 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1464 ID.AddPointer(Ops[i]);
1465 void *IP = 0;
1466 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1467 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001468 new (S) SCEVAddExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001469 UniqueSCEVs.InsertNode(S, IP);
1470 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471}
1472
1473
Dan Gohmanc8a29272009-05-24 23:45:28 +00001474/// getMulExpr - Get a canonical multiply expression, or something simpler if
1475/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001476const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001478#ifndef NDEBUG
1479 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1480 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1481 getEffectiveSCEVType(Ops[0]->getType()) &&
1482 "SCEVMulExpr operand types don't match!");
1483#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484
1485 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001486 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487
1488 // If there are any constants, fold them together.
1489 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001490 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491
1492 // C1*(C2+V) -> C1*C2 + C1*V
1493 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001494 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001495 if (Add->getNumOperands() == 2 &&
1496 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001497 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1498 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499
1500
1501 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001502 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001504 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001505 RHSC->getValue()->getValue());
1506 Ops[0] = getConstant(Fold);
1507 Ops.erase(Ops.begin()+1); // Erase the folded element
1508 if (Ops.size() == 1) return Ops[0];
1509 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001510 }
1511
1512 // If we are left with a constant one being multiplied, strip it off.
1513 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1514 Ops.erase(Ops.begin());
1515 --Idx;
1516 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1517 // If we have a multiply of zero, it will always be zero.
1518 return Ops[0];
1519 }
1520 }
1521
1522 // Skip over the add expression until we get to a multiply.
1523 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1524 ++Idx;
1525
1526 if (Ops.size() == 1)
1527 return Ops[0];
1528
1529 // If there are mul operands inline them all into this expression.
1530 if (Idx < Ops.size()) {
1531 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001532 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 // If we have an mul, expand the mul operands onto the end of the operands
1534 // list.
1535 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1536 Ops.erase(Ops.begin()+Idx);
1537 DeletedMul = true;
1538 }
1539
1540 // If we deleted at least one mul, we added operands to the end of the list,
1541 // and they are not necessarily sorted. Recurse to resort and resimplify
1542 // any operands we just aquired.
1543 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001544 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 }
1546
1547 // If there are any add recurrences in the operands list, see if any other
1548 // added values are loop invariant. If so, we can fold them into the
1549 // recurrence.
1550 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1551 ++Idx;
1552
1553 // Scan over all recurrences, trying to fold loop invariants into them.
1554 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1555 // Scan all of the other operands to this mul and add them to the vector if
1556 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001557 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001558 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1560 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1561 LIOps.push_back(Ops[i]);
1562 Ops.erase(Ops.begin()+i);
1563 --i; --e;
1564 }
1565
1566 // If we found some loop invariants, fold them into the recurrence.
1567 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001568 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman161ea032009-07-07 17:06:11 +00001569 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570 NewOps.reserve(AddRec->getNumOperands());
1571 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001572 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001573 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001574 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575 } else {
1576 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001577 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001578 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001579 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 }
1581 }
1582
Dan Gohman161ea032009-07-07 17:06:11 +00001583 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584
1585 // If all of the other operands were loop invariant, we are done.
1586 if (Ops.size() == 1) return NewRec;
1587
1588 // Otherwise, multiply the folded AddRec by the non-liv parts.
1589 for (unsigned i = 0;; ++i)
1590 if (Ops[i] == AddRec) {
1591 Ops[i] = NewRec;
1592 break;
1593 }
Dan Gohman89f85052007-10-22 18:31:58 +00001594 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001595 }
1596
1597 // Okay, if there weren't any loop invariants to be folded, check to see if
1598 // there are multiple AddRec's with the same loop induction variable being
1599 // multiplied together. If so, we can fold them.
1600 for (unsigned OtherIdx = Idx+1;
1601 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1602 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001603 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001604 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1605 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001606 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman161ea032009-07-07 17:06:11 +00001607 const SCEV *NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 G->getStart());
Dan Gohman161ea032009-07-07 17:06:11 +00001609 const SCEV *B = F->getStepRecurrence(*this);
1610 const SCEV *D = G->getStepRecurrence(*this);
1611 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001612 getMulExpr(G, B),
1613 getMulExpr(B, D));
Dan Gohman161ea032009-07-07 17:06:11 +00001614 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001615 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616 if (Ops.size() == 2) return NewAddRec;
1617
1618 Ops.erase(Ops.begin()+Idx);
1619 Ops.erase(Ops.begin()+OtherIdx-1);
1620 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001621 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622 }
1623 }
1624
1625 // Otherwise couldn't fold anything into this recurrence. Move onto the
1626 // next one.
1627 }
1628
1629 // Okay, it looks like we really DO need an mul expr. Check to see if we
1630 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001631 FoldingSetNodeID ID;
1632 ID.AddInteger(scMulExpr);
1633 ID.AddInteger(Ops.size());
1634 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1635 ID.AddPointer(Ops[i]);
1636 void *IP = 0;
1637 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1638 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001639 new (S) SCEVMulExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001640 UniqueSCEVs.InsertNode(S, IP);
1641 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642}
1643
Dan Gohmanc8a29272009-05-24 23:45:28 +00001644/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1645/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001646const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1647 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001648 assert(getEffectiveSCEVType(LHS->getType()) ==
1649 getEffectiveSCEVType(RHS->getType()) &&
1650 "SCEVUDivExpr operand types don't match!");
1651
Dan Gohmanc76b5452009-05-04 22:02:23 +00001652 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001654 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001655 if (RHSC->isZero())
1656 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001658 // Determine if the division can be folded into the operands of
1659 // its operands.
1660 // TODO: Generalize this to non-constants by using known-bits information.
1661 const Type *Ty = LHS->getType();
1662 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1663 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1664 // For non-power-of-two values, effectively round the value up to the
1665 // nearest power of two.
1666 if (!RHSC->getValue()->getValue().isPowerOf2())
1667 ++MaxShiftAmt;
1668 const IntegerType *ExtTy =
1669 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1670 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1671 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1672 if (const SCEVConstant *Step =
1673 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1674 if (!Step->getValue()->getValue()
1675 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001676 getZeroExtendExpr(AR, ExtTy) ==
1677 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1678 getZeroExtendExpr(Step, ExtTy),
1679 AR->getLoop())) {
Dan Gohman161ea032009-07-07 17:06:11 +00001680 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001681 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1682 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1683 return getAddRecExpr(Operands, AR->getLoop());
1684 }
1685 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001686 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001687 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001688 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1689 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1690 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001691 // Find an operand that's safely divisible.
1692 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001693 const SCEV *Op = M->getOperand(i);
1694 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001695 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman161ea032009-07-07 17:06:11 +00001696 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1697 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001698 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001699 Operands[i] = Div;
1700 return getMulExpr(Operands);
1701 }
1702 }
Dan Gohman14374d32009-05-08 23:11:16 +00001703 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001704 // (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 +00001705 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001706 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001707 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1708 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1709 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1710 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001711 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001712 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001713 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1714 break;
1715 Operands.push_back(Op);
1716 }
1717 if (Operands.size() == A->getNumOperands())
1718 return getAddExpr(Operands);
1719 }
Dan Gohman14374d32009-05-08 23:11:16 +00001720 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001721
1722 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001723 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724 Constant *LHSCV = LHSC->getValue();
1725 Constant *RHSCV = RHSC->getValue();
Owen Anderson8be68a32009-07-13 23:50:59 +00001726 return getConstant(cast<ConstantInt>(Context->getConstantExprUDiv(LHSCV,
Dan Gohman55788cf2009-06-24 00:38:39 +00001727 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728 }
1729 }
1730
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001731 FoldingSetNodeID ID;
1732 ID.AddInteger(scUDivExpr);
1733 ID.AddPointer(LHS);
1734 ID.AddPointer(RHS);
1735 void *IP = 0;
1736 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1737 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001738 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001739 UniqueSCEVs.InsertNode(S, IP);
1740 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741}
1742
1743
Dan Gohmanc8a29272009-05-24 23:45:28 +00001744/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1745/// Simplify the expression as much as possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001746const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1747 const SCEV *Step, const Loop *L) {
1748 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001750 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001751 if (StepChrec->getLoop() == L) {
1752 Operands.insert(Operands.end(), StepChrec->op_begin(),
1753 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001754 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755 }
1756
1757 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001758 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759}
1760
Dan Gohmanc8a29272009-05-24 23:45:28 +00001761/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1762/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001763const SCEV *
Dan Gohman161ea032009-07-07 17:06:11 +00001764ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman9bc642f2009-06-24 04:48:43 +00001765 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001766 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001767#ifndef NDEBUG
1768 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1769 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1770 getEffectiveSCEVType(Operands[0]->getType()) &&
1771 "SCEVAddRecExpr operand types don't match!");
1772#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773
Dan Gohman7b560c42008-06-18 16:23:07 +00001774 if (Operands.back()->isZero()) {
1775 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001776 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001777 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778
Dan Gohman42936882008-08-08 18:33:12 +00001779 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001780 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001781 const Loop* NestedLoop = NestedAR->getLoop();
1782 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman161ea032009-07-07 17:06:11 +00001783 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001784 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001785 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001786 // AddRecs require their operands be loop-invariant with respect to their
1787 // loops. Don't perform this transformation if it would break this
1788 // requirement.
1789 bool AllInvariant = true;
1790 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1791 if (!Operands[i]->isLoopInvariant(L)) {
1792 AllInvariant = false;
1793 break;
1794 }
1795 if (AllInvariant) {
1796 NestedOperands[0] = getAddRecExpr(Operands, L);
1797 AllInvariant = true;
1798 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1799 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1800 AllInvariant = false;
1801 break;
1802 }
1803 if (AllInvariant)
1804 // Ok, both add recurrences are valid after the transformation.
1805 return getAddRecExpr(NestedOperands, NestedLoop);
1806 }
1807 // Reset Operands to its original state.
1808 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001809 }
1810 }
1811
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001812 FoldingSetNodeID ID;
1813 ID.AddInteger(scAddRecExpr);
1814 ID.AddInteger(Operands.size());
1815 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1816 ID.AddPointer(Operands[i]);
1817 ID.AddPointer(L);
1818 void *IP = 0;
1819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1820 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001821 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001822 UniqueSCEVs.InsertNode(S, IP);
1823 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001824}
1825
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001826const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1827 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001828 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001829 Ops.push_back(LHS);
1830 Ops.push_back(RHS);
1831 return getSMaxExpr(Ops);
1832}
1833
Dan Gohman161ea032009-07-07 17:06:11 +00001834const SCEV *
1835ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001836 assert(!Ops.empty() && "Cannot get empty smax!");
1837 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001838#ifndef NDEBUG
1839 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1840 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1841 getEffectiveSCEVType(Ops[0]->getType()) &&
1842 "SCEVSMaxExpr operand types don't match!");
1843#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001844
1845 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001846 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001847
1848 // If there are any constants, fold them together.
1849 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001850 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001851 ++Idx;
1852 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001853 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001854 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001855 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001856 APIntOps::smax(LHSC->getValue()->getValue(),
1857 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001858 Ops[0] = getConstant(Fold);
1859 Ops.erase(Ops.begin()+1); // Erase the folded element
1860 if (Ops.size() == 1) return Ops[0];
1861 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001862 }
1863
Dan Gohmand156c092009-06-24 14:46:22 +00001864 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001865 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1866 Ops.erase(Ops.begin());
1867 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001868 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1869 // If we have an smax with a constant maximum-int, it will always be
1870 // maximum-int.
1871 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001872 }
1873 }
1874
1875 if (Ops.size() == 1) return Ops[0];
1876
1877 // Find the first SMax
1878 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1879 ++Idx;
1880
1881 // Check to see if one of the operands is an SMax. If so, expand its operands
1882 // onto our operand list, and recurse to simplify.
1883 if (Idx < Ops.size()) {
1884 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001885 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001886 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1887 Ops.erase(Ops.begin()+Idx);
1888 DeletedSMax = true;
1889 }
1890
1891 if (DeletedSMax)
1892 return getSMaxExpr(Ops);
1893 }
1894
1895 // Okay, check to see if the same value occurs in the operand list twice. If
1896 // so, delete one. Since we sorted the list, these values are required to
1897 // be adjacent.
1898 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1899 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1900 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1901 --i; --e;
1902 }
1903
1904 if (Ops.size() == 1) return Ops[0];
1905
1906 assert(!Ops.empty() && "Reduced smax down to nothing!");
1907
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001908 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001909 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001910 FoldingSetNodeID ID;
1911 ID.AddInteger(scSMaxExpr);
1912 ID.AddInteger(Ops.size());
1913 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1914 ID.AddPointer(Ops[i]);
1915 void *IP = 0;
1916 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1917 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001918 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001919 UniqueSCEVs.InsertNode(S, IP);
1920 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001921}
1922
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001923const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1924 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001925 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001926 Ops.push_back(LHS);
1927 Ops.push_back(RHS);
1928 return getUMaxExpr(Ops);
1929}
1930
Dan Gohman161ea032009-07-07 17:06:11 +00001931const SCEV *
1932ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001933 assert(!Ops.empty() && "Cannot get empty umax!");
1934 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001935#ifndef NDEBUG
1936 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1937 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1938 getEffectiveSCEVType(Ops[0]->getType()) &&
1939 "SCEVUMaxExpr operand types don't match!");
1940#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001941
1942 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001943 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001944
1945 // If there are any constants, fold them together.
1946 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001947 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001948 ++Idx;
1949 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001950 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001951 // We found two constants, fold them together!
1952 ConstantInt *Fold = ConstantInt::get(
1953 APIntOps::umax(LHSC->getValue()->getValue(),
1954 RHSC->getValue()->getValue()));
1955 Ops[0] = getConstant(Fold);
1956 Ops.erase(Ops.begin()+1); // Erase the folded element
1957 if (Ops.size() == 1) return Ops[0];
1958 LHSC = cast<SCEVConstant>(Ops[0]);
1959 }
1960
Dan Gohmand156c092009-06-24 14:46:22 +00001961 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001962 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1963 Ops.erase(Ops.begin());
1964 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001965 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1966 // If we have an umax with a constant maximum-int, it will always be
1967 // maximum-int.
1968 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001969 }
1970 }
1971
1972 if (Ops.size() == 1) return Ops[0];
1973
1974 // Find the first UMax
1975 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1976 ++Idx;
1977
1978 // Check to see if one of the operands is a UMax. If so, expand its operands
1979 // onto our operand list, and recurse to simplify.
1980 if (Idx < Ops.size()) {
1981 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001982 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001983 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1984 Ops.erase(Ops.begin()+Idx);
1985 DeletedUMax = true;
1986 }
1987
1988 if (DeletedUMax)
1989 return getUMaxExpr(Ops);
1990 }
1991
1992 // Okay, check to see if the same value occurs in the operand list twice. If
1993 // so, delete one. Since we sorted the list, these values are required to
1994 // be adjacent.
1995 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1996 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1997 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1998 --i; --e;
1999 }
2000
2001 if (Ops.size() == 1) return Ops[0];
2002
2003 assert(!Ops.empty() && "Reduced umax down to nothing!");
2004
2005 // Okay, it looks like we really DO need a umax expr. Check to see if we
2006 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002007 FoldingSetNodeID ID;
2008 ID.AddInteger(scUMaxExpr);
2009 ID.AddInteger(Ops.size());
2010 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2011 ID.AddPointer(Ops[i]);
2012 void *IP = 0;
2013 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2014 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00002015 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002016 UniqueSCEVs.InsertNode(S, IP);
2017 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002018}
2019
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002020const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2021 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00002022 // ~smax(~x, ~y) == smin(x, y).
2023 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2024}
2025
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002026const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2027 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00002028 // ~umax(~x, ~y) == umin(x, y)
2029 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2030}
2031
Dan Gohman161ea032009-07-07 17:06:11 +00002032const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002033 // Don't attempt to do anything other than create a SCEVUnknown object
2034 // here. createSCEV only calls getUnknown after checking for all other
2035 // interesting possibilities, and any other code that calls getUnknown
2036 // is doing so in order to hide a value from SCEV canonicalization.
2037
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002038 FoldingSetNodeID ID;
2039 ID.AddInteger(scUnknown);
2040 ID.AddPointer(V);
2041 void *IP = 0;
2042 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2043 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmand43a8282009-07-13 20:50:19 +00002044 new (S) SCEVUnknown(ID, V);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002045 UniqueSCEVs.InsertNode(S, IP);
2046 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047}
2048
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002049//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050// Basic SCEV Analysis and PHI Idiom Recognition Code
2051//
2052
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002053/// isSCEVable - Test if values of the given type are analyzable within
2054/// the SCEV framework. This primarily includes integer types, and it
2055/// can optionally include pointer types if the ScalarEvolution class
2056/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002057bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002058 // Integers are always SCEVable.
2059 if (Ty->isInteger())
2060 return true;
2061
2062 // Pointers are SCEVable if TargetData information is available
2063 // to provide pointer size information.
2064 if (isa<PointerType>(Ty))
2065 return TD != NULL;
2066
2067 // Otherwise it's not SCEVable.
2068 return false;
2069}
2070
2071/// getTypeSizeInBits - Return the size in bits of the specified type,
2072/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002073uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002074 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2075
2076 // If we have a TargetData, use it!
2077 if (TD)
2078 return TD->getTypeSizeInBits(Ty);
2079
2080 // Otherwise, we support only integer types.
2081 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2082 return Ty->getPrimitiveSizeInBits();
2083}
2084
2085/// getEffectiveSCEVType - Return a type with the same bitwidth as
2086/// the given type and which represents how SCEV will treat the given
2087/// type, for which isSCEVable must return true. For pointer types,
2088/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002089const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002090 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2091
2092 if (Ty->isInteger())
2093 return Ty;
2094
2095 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2096 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002097}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098
Dan Gohman161ea032009-07-07 17:06:11 +00002099const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002100 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002101}
2102
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2104/// expression and create a new one.
Dan Gohman161ea032009-07-07 17:06:11 +00002105const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002106 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107
Dan Gohman161ea032009-07-07 17:06:11 +00002108 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109 if (I != Scalars.end()) return I->second;
Dan Gohman161ea032009-07-07 17:06:11 +00002110 const SCEV *S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002111 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112 return S;
2113}
2114
Dan Gohman984c78a2009-06-24 00:54:57 +00002115/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002116/// specified signed integer value and return a SCEV for the constant.
Dan Gohman161ea032009-07-07 17:06:11 +00002117const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002118 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00002119 return getConstant(Context->getConstantInt(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002120}
2121
2122/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2123///
Dan Gohman161ea032009-07-07 17:06:11 +00002124const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002125 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson15b39322009-07-13 04:09:18 +00002126 return getConstant(
2127 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002128
2129 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002130 Ty = getEffectiveSCEVType(Ty);
Owen Anderson035d41d2009-07-13 20:58:05 +00002131 return getMulExpr(V,
2132 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty))));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002133}
2134
2135/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman161ea032009-07-07 17:06:11 +00002136const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002137 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson035d41d2009-07-13 20:58:05 +00002138 return getConstant(
2139 cast<ConstantInt>(Context->getConstantExprNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002140
2141 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002142 Ty = getEffectiveSCEVType(Ty);
Owen Anderson035d41d2009-07-13 20:58:05 +00002143 const SCEV *AllOnes =
2144 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002145 return getMinusSCEV(AllOnes, V);
2146}
2147
2148/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2149///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002150const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2151 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002152 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002153 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002154}
2155
2156/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2157/// input value to the specified type. If the type must be extended, it is zero
2158/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002159const SCEV *
2160ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002161 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002162 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002163 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2164 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002165 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002166 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002167 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002168 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002169 return getTruncateExpr(V, Ty);
2170 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002171}
2172
2173/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2174/// input value to the specified type. If the type must be extended, it is sign
2175/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002176const SCEV *
2177ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002178 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002179 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002180 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2181 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002182 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002183 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002184 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002185 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002186 return getTruncateExpr(V, Ty);
2187 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002188}
2189
Dan Gohmanac959332009-05-13 03:46:30 +00002190/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2191/// input value to the specified type. If the type must be extended, it is zero
2192/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002193const SCEV *
2194ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002195 const Type *SrcTy = V->getType();
2196 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2197 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2198 "Cannot noop or zero extend with non-integer arguments!");
2199 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2200 "getNoopOrZeroExtend cannot truncate!");
2201 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2202 return V; // No conversion
2203 return getZeroExtendExpr(V, Ty);
2204}
2205
2206/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2207/// input value to the specified type. If the type must be extended, it is sign
2208/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002209const SCEV *
2210ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002211 const Type *SrcTy = V->getType();
2212 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2213 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2214 "Cannot noop or sign extend with non-integer arguments!");
2215 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2216 "getNoopOrSignExtend cannot truncate!");
2217 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2218 return V; // No conversion
2219 return getSignExtendExpr(V, Ty);
2220}
2221
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002222/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2223/// the input value to the specified type. If the type must be extended,
2224/// it is extended with unspecified bits. The conversion must not be
2225/// narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002226const SCEV *
2227ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002228 const Type *SrcTy = V->getType();
2229 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2230 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2231 "Cannot noop or any extend with non-integer arguments!");
2232 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2233 "getNoopOrAnyExtend cannot truncate!");
2234 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2235 return V; // No conversion
2236 return getAnyExtendExpr(V, Ty);
2237}
2238
Dan Gohmanac959332009-05-13 03:46:30 +00002239/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2240/// input value to the specified type. The conversion must not be widening.
Dan Gohman161ea032009-07-07 17:06:11 +00002241const SCEV *
2242ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002243 const Type *SrcTy = V->getType();
2244 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2245 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2246 "Cannot truncate or noop with non-integer arguments!");
2247 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2248 "getTruncateOrNoop cannot extend!");
2249 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2250 return V; // No conversion
2251 return getTruncateExpr(V, Ty);
2252}
2253
Dan Gohman8e8b5232009-06-22 00:31:57 +00002254/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2255/// the types using zero-extension, and then perform a umax operation
2256/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002257const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2258 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002259 const SCEV *PromotedLHS = LHS;
2260 const SCEV *PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002261
2262 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2263 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2264 else
2265 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2266
2267 return getUMaxExpr(PromotedLHS, PromotedRHS);
2268}
2269
Dan Gohman9e62bb02009-06-22 15:03:27 +00002270/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2271/// the types using zero-extension, and then perform a umin operation
2272/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002273const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2274 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002275 const SCEV *PromotedLHS = LHS;
2276 const SCEV *PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002277
2278 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2279 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2280 else
2281 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2282
2283 return getUMinExpr(PromotedLHS, PromotedRHS);
2284}
2285
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2287/// the specified instruction and replaces any references to the symbolic value
2288/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002289void
2290ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2291 const SCEV *SymName,
2292 const SCEV *NewVal) {
Dan Gohman161ea032009-07-07 17:06:11 +00002293 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002294 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 if (SI == Scalars.end()) return;
2296
Dan Gohman161ea032009-07-07 17:06:11 +00002297 const SCEV *NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002298 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 if (NV == SI->second) return; // No change.
2300
2301 SI->second = NV; // Update the scalars map!
2302
2303 // Any instruction values that use this instruction might also need to be
2304 // updated!
2305 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2306 UI != E; ++UI)
2307 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2308}
2309
2310/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2311/// a loop header, making it a potential recurrence, or it doesn't.
2312///
Dan Gohman161ea032009-07-07 17:06:11 +00002313const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002315 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 if (L->getHeader() == PN->getParent()) {
2317 // If it lives in the loop header, it has two incoming values, one
2318 // from outside the loop, and one from inside.
2319 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2320 unsigned BackEdge = IncomingEdge^1;
2321
2322 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman161ea032009-07-07 17:06:11 +00002323 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 assert(Scalars.find(PN) == Scalars.end() &&
2325 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002326 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002327
2328 // Using this symbolic name for the PHI, analyze the value coming around
2329 // the back-edge.
Dan Gohman161ea032009-07-07 17:06:11 +00002330 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002331
2332 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2333 // has a special value for the first iteration of the loop.
2334
2335 // If the value coming around the backedge is an add with the symbolic
2336 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002337 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 // If there is a single occurrence of the symbolic value, replace it
2339 // with a recurrence.
2340 unsigned FoundIndex = Add->getNumOperands();
2341 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2342 if (Add->getOperand(i) == SymbolicName)
2343 if (FoundIndex == e) {
2344 FoundIndex = i;
2345 break;
2346 }
2347
2348 if (FoundIndex != Add->getNumOperands()) {
2349 // Create an add with everything but the specified operand.
Dan Gohman161ea032009-07-07 17:06:11 +00002350 SmallVector<const SCEV *, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002351 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2352 if (i != FoundIndex)
2353 Ops.push_back(Add->getOperand(i));
Dan Gohman161ea032009-07-07 17:06:11 +00002354 const SCEV *Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355
2356 // This is not a valid addrec if the step amount is varying each
2357 // loop iteration, but is not itself an addrec in this loop.
2358 if (Accum->isLoopInvariant(L) ||
2359 (isa<SCEVAddRecExpr>(Accum) &&
2360 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002361 const SCEV *StartVal =
2362 getSCEV(PN->getIncomingValue(IncomingEdge));
2363 const SCEV *PHISCEV =
2364 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002365
2366 // Okay, for the entire analysis of this edge we assumed the PHI
2367 // to be symbolic. We now need to go back and update all of the
2368 // entries for the scalars that use the PHI (except for the PHI
2369 // itself) to use the new analyzed value instead of the "symbolic"
2370 // value.
2371 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2372 return PHISCEV;
2373 }
2374 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002375 } else if (const SCEVAddRecExpr *AddRec =
2376 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002377 // Otherwise, this could be a loop like this:
2378 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2379 // In this case, j = {1,+,1} and BEValue is j.
2380 // Because the other in-value of i (0) fits the evolution of BEValue
2381 // i really is an addrec evolution.
2382 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman161ea032009-07-07 17:06:11 +00002383 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002384
2385 // If StartVal = j.start - j.stride, we can use StartVal as the
2386 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002387 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002388 AddRec->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002389 const SCEV *PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002390 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391
2392 // Okay, for the entire analysis of this edge we assumed the PHI
2393 // to be symbolic. We now need to go back and update all of the
2394 // entries for the scalars that use the PHI (except for the PHI
2395 // itself) to use the new analyzed value instead of the "symbolic"
2396 // value.
2397 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2398 return PHISCEV;
2399 }
2400 }
2401 }
2402
2403 return SymbolicName;
2404 }
2405
Dan Gohman32f35cc2009-07-14 14:06:25 +00002406 // It's tempting to recognize PHIs with a unique incoming value, however
2407 // this leads passes like indvars to break LCSSA form. Fortunately, such
2408 // PHIs are rare, as instcombine zaps them.
2409
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002411 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002412}
2413
Dan Gohman509cf4d2009-05-08 20:26:55 +00002414/// createNodeForGEP - Expand GEP instructions into add and multiply
2415/// operations. This allows them to be analyzed by regular SCEV code.
2416///
Dan Gohman161ea032009-07-07 17:06:11 +00002417const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002418
2419 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002420 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002421 // Don't attempt to analyze GEPs over unsized objects.
2422 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2423 return getUnknown(GEP);
Dan Gohman161ea032009-07-07 17:06:11 +00002424 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002425 gep_type_iterator GTI = gep_type_begin(GEP);
2426 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2427 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002428 I != E; ++I) {
2429 Value *Index = *I;
2430 // Compute the (potentially symbolic) offset in bytes for this index.
2431 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2432 // For a struct, add the member offset.
2433 const StructLayout &SL = *TD->getStructLayout(STy);
2434 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2435 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002436 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002437 } else {
2438 // For an array, add the element offset, explicitly scaled.
Dan Gohman161ea032009-07-07 17:06:11 +00002439 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002440 if (!isa<PointerType>(LocalOffset->getType()))
2441 // Getelementptr indicies are signed.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002442 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002443 LocalOffset =
2444 getMulExpr(LocalOffset,
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002445 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002446 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2447 }
2448 }
2449 return getAddExpr(getSCEV(Base), TotalOffset);
2450}
2451
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002452/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2453/// guaranteed to end in (at every loop iteration). It is, at the same time,
2454/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2455/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002456uint32_t
Dan Gohman161ea032009-07-07 17:06:11 +00002457ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002458 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002459 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460
Dan Gohmanc76b5452009-05-04 22:02:23 +00002461 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002462 return std::min(GetMinTrailingZeros(T->getOperand()),
2463 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002464
Dan Gohmanc76b5452009-05-04 22:02:23 +00002465 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002466 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2467 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2468 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002469 }
2470
Dan Gohmanc76b5452009-05-04 22:02:23 +00002471 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002472 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2473 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2474 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002475 }
2476
Dan Gohmanc76b5452009-05-04 22:02:23 +00002477 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002478 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002479 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002480 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002481 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002482 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 }
2484
Dan Gohmanc76b5452009-05-04 22:02:23 +00002485 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002486 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002487 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2488 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002489 for (unsigned i = 1, e = M->getNumOperands();
2490 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002491 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002492 BitWidth);
2493 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002494 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002495
Dan Gohmanc76b5452009-05-04 22:02:23 +00002496 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002497 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002498 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002499 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002500 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002501 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002502 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002503
Dan Gohmanc76b5452009-05-04 22:02:23 +00002504 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002505 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002506 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002507 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002508 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002509 return MinOpRes;
2510 }
2511
Dan Gohmanc76b5452009-05-04 22:02:23 +00002512 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002513 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002514 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002515 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002516 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002517 return MinOpRes;
2518 }
2519
Dan Gohman6e923a72009-06-19 23:29:04 +00002520 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2521 // For a SCEVUnknown, ask ValueTracking.
2522 unsigned BitWidth = getTypeSizeInBits(U->getType());
2523 APInt Mask = APInt::getAllOnesValue(BitWidth);
2524 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2525 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2526 return Zeros.countTrailingOnes();
2527 }
2528
2529 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002530 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531}
2532
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002533/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2534///
2535ConstantRange
2536ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002537
2538 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002539 return ConstantRange(C->getValue()->getValue());
Dan Gohman6e923a72009-06-19 23:29:04 +00002540
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002541 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2542 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2543 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2544 X = X.add(getUnsignedRange(Add->getOperand(i)));
2545 return X;
2546 }
2547
2548 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2549 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2550 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2551 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2552 return X;
2553 }
2554
2555 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2556 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2557 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2558 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2559 return X;
2560 }
2561
2562 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2563 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2564 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2565 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2566 return X;
2567 }
2568
2569 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2570 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2571 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2572 return X.udiv(Y);
2573 }
2574
2575 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2576 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2577 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2578 }
2579
2580 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2581 ConstantRange X = getUnsignedRange(SExt->getOperand());
2582 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2583 }
2584
2585 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2586 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2587 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2588 }
2589
2590 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2591
2592 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2593 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2594 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2595 if (!Trip) return FullSet;
2596
2597 // TODO: non-affine addrec
2598 if (AddRec->isAffine()) {
2599 const Type *Ty = AddRec->getType();
2600 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2601 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2602 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2603
2604 const SCEV *Start = AddRec->getStart();
2605 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2606
2607 // Check for overflow.
2608 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2609 return FullSet;
2610
2611 ConstantRange StartRange = getUnsignedRange(Start);
2612 ConstantRange EndRange = getUnsignedRange(End);
2613 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2614 EndRange.getUnsignedMin());
2615 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2616 EndRange.getUnsignedMax());
2617 if (Min.isMinValue() && Max.isMaxValue())
2618 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2619 return ConstantRange(Min, Max+1);
2620 }
2621 }
Dan Gohman6e923a72009-06-19 23:29:04 +00002622 }
2623
2624 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2625 // For a SCEVUnknown, ask ValueTracking.
2626 unsigned BitWidth = getTypeSizeInBits(U->getType());
2627 APInt Mask = APInt::getAllOnesValue(BitWidth);
2628 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2629 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002630 return ConstantRange(Ones, ~Zeros);
Dan Gohman6e923a72009-06-19 23:29:04 +00002631 }
2632
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002633 return FullSet;
Dan Gohman6e923a72009-06-19 23:29:04 +00002634}
2635
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002636/// getSignedRange - Determine the signed range for a particular SCEV.
2637///
2638ConstantRange
2639ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002640
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002641 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2642 return ConstantRange(C->getValue()->getValue());
2643
2644 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2645 ConstantRange X = getSignedRange(Add->getOperand(0));
2646 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2647 X = X.add(getSignedRange(Add->getOperand(i)));
2648 return X;
Dan Gohman6e923a72009-06-19 23:29:04 +00002649 }
2650
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002651 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2652 ConstantRange X = getSignedRange(Mul->getOperand(0));
2653 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2654 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2655 return X;
Dan Gohman6e923a72009-06-19 23:29:04 +00002656 }
2657
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002658 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2659 ConstantRange X = getSignedRange(SMax->getOperand(0));
2660 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2661 X = X.smax(getSignedRange(SMax->getOperand(i)));
2662 return X;
2663 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002664
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002665 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2666 ConstantRange X = getSignedRange(UMax->getOperand(0));
2667 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2668 X = X.umax(getSignedRange(UMax->getOperand(i)));
2669 return X;
2670 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002671
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002672 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2673 ConstantRange X = getSignedRange(UDiv->getLHS());
2674 ConstantRange Y = getSignedRange(UDiv->getRHS());
2675 return X.udiv(Y);
2676 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002677
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002678 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2679 ConstantRange X = getSignedRange(ZExt->getOperand());
2680 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2681 }
2682
2683 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2684 ConstantRange X = getSignedRange(SExt->getOperand());
2685 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2686 }
2687
2688 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2689 ConstantRange X = getSignedRange(Trunc->getOperand());
2690 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2691 }
2692
2693 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2694
2695 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2696 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2697 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2698 if (!Trip) return FullSet;
2699
2700 // TODO: non-affine addrec
2701 if (AddRec->isAffine()) {
2702 const Type *Ty = AddRec->getType();
2703 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2704 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2705 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2706
2707 const SCEV *Start = AddRec->getStart();
2708 const SCEV *Step = AddRec->getStepRecurrence(*this);
2709 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2710
2711 // Check for overflow.
2712 if (!(isKnownPositive(Step) &&
2713 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2714 !(isKnownNegative(Step) &&
2715 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2716 return FullSet;
2717
2718 ConstantRange StartRange = getSignedRange(Start);
2719 ConstantRange EndRange = getSignedRange(End);
2720 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2721 EndRange.getSignedMin());
2722 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2723 EndRange.getSignedMax());
2724 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2725 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2726 return ConstantRange(Min, Max+1);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002727 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002728 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002729 }
2730
Dan Gohman6e923a72009-06-19 23:29:04 +00002731 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2732 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002733 unsigned BitWidth = getTypeSizeInBits(U->getType());
2734 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2735 if (NS == 1)
2736 return FullSet;
2737 return
2738 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2739 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman6e923a72009-06-19 23:29:04 +00002740 }
2741
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002742 return FullSet;
Dan Gohman6e923a72009-06-19 23:29:04 +00002743}
2744
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745/// createSCEV - We know that there is no SCEV for the specified value.
2746/// Analyze the expression.
2747///
Dan Gohman161ea032009-07-07 17:06:11 +00002748const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002749 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002750 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002751
Dan Gohman3996f472008-06-22 19:56:46 +00002752 unsigned Opcode = Instruction::UserOp1;
2753 if (Instruction *I = dyn_cast<Instruction>(V))
2754 Opcode = I->getOpcode();
2755 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2756 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002757 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2758 return getConstant(CI);
2759 else if (isa<ConstantPointerNull>(V))
2760 return getIntegerSCEV(0, V->getType());
2761 else if (isa<UndefValue>(V))
2762 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002763 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002764 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765
Dan Gohman3996f472008-06-22 19:56:46 +00002766 User *U = cast<User>(V);
2767 switch (Opcode) {
2768 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002769 return getAddExpr(getSCEV(U->getOperand(0)),
2770 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002771 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002772 return getMulExpr(getSCEV(U->getOperand(0)),
2773 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002774 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002775 return getUDivExpr(getSCEV(U->getOperand(0)),
2776 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002777 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002778 return getMinusSCEV(getSCEV(U->getOperand(0)),
2779 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002780 case Instruction::And:
2781 // For an expression like x&255 that merely masks off the high bits,
2782 // use zext(trunc(x)) as the SCEV expression.
2783 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002784 if (CI->isNullValue())
2785 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002786 if (CI->isAllOnesValue())
2787 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002788 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002789
2790 // Instcombine's ShrinkDemandedConstant may strip bits out of
2791 // constants, obscuring what would otherwise be a low-bits mask.
2792 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2793 // knew about to reconstruct a low-bits mask value.
2794 unsigned LZ = A.countLeadingZeros();
2795 unsigned BitWidth = A.getBitWidth();
2796 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2797 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2798 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2799
2800 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2801
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002802 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002803 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002804 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002805 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002806 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002807 }
2808 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002809
Dan Gohman3996f472008-06-22 19:56:46 +00002810 case Instruction::Or:
2811 // If the RHS of the Or is a constant, we may have something like:
2812 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2813 // optimizations will transparently handle this case.
2814 //
2815 // In order for this transformation to be safe, the LHS must be of the
2816 // form X*(2^n) and the Or constant must be less than 2^n.
2817 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002818 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002819 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002820 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002821 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002822 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002823 }
Dan Gohman3996f472008-06-22 19:56:46 +00002824 break;
2825 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002826 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002827 // If the RHS of the xor is a signbit, then this is just an add.
2828 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002829 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002830 return getAddExpr(getSCEV(U->getOperand(0)),
2831 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002832
2833 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002834 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002835 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002836
2837 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2838 // This is a variant of the check for xor with -1, and it handles
2839 // the case where instcombine has trimmed non-demanded bits out
2840 // of an xor with -1.
2841 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2842 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2843 if (BO->getOpcode() == Instruction::And &&
2844 LCI->getValue() == CI->getValue())
2845 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002846 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002847 const Type *UTy = U->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00002848 const SCEV *Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002849 const Type *Z0Ty = Z0->getType();
2850 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2851
2852 // If C is a low-bits mask, the zero extend is zerving to
2853 // mask off the high bits. Complement the operand and
2854 // re-apply the zext.
2855 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2856 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2857
2858 // If C is a single bit, it may be in the sign-bit position
2859 // before the zero-extend. In this case, represent the xor
2860 // using an add, which is equivalent, and re-apply the zext.
2861 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2862 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2863 Trunc.isSignBit())
2864 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2865 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002866 }
Dan Gohman3996f472008-06-22 19:56:46 +00002867 }
2868 break;
2869
2870 case Instruction::Shl:
2871 // Turn shift left of a constant amount into a multiply.
2872 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2873 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2874 Constant *X = ConstantInt::get(
2875 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002876 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002877 }
2878 break;
2879
Nick Lewycky7fd27892008-07-07 06:15:49 +00002880 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002881 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002882 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2883 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2884 Constant *X = ConstantInt::get(
2885 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002886 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002887 }
2888 break;
2889
Dan Gohman53bf64a2009-04-21 02:26:00 +00002890 case Instruction::AShr:
2891 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2892 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2893 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2894 if (L->getOpcode() == Instruction::Shl &&
2895 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002896 unsigned BitWidth = getTypeSizeInBits(U->getType());
2897 uint64_t Amt = BitWidth - CI->getZExtValue();
2898 if (Amt == BitWidth)
2899 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2900 if (Amt > BitWidth)
2901 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002902 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002903 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002904 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002905 U->getType());
2906 }
2907 break;
2908
Dan Gohman3996f472008-06-22 19:56:46 +00002909 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002910 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002911
2912 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002913 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002914
2915 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002916 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002917
2918 case Instruction::BitCast:
2919 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002920 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002921 return getSCEV(U->getOperand(0));
2922 break;
2923
Dan Gohman01c2ee72009-04-16 03:18:22 +00002924 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002925 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002926 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002927 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002928
2929 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002930 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002931 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2932 U->getType());
2933
Dan Gohman509cf4d2009-05-08 20:26:55 +00002934 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002935 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002936 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002937
Dan Gohman3996f472008-06-22 19:56:46 +00002938 case Instruction::PHI:
2939 return createNodeForPHI(cast<PHINode>(U));
2940
2941 case Instruction::Select:
2942 // This could be a smax or umax that was lowered earlier.
2943 // Try to recover it.
2944 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2945 Value *LHS = ICI->getOperand(0);
2946 Value *RHS = ICI->getOperand(1);
2947 switch (ICI->getPredicate()) {
2948 case ICmpInst::ICMP_SLT:
2949 case ICmpInst::ICMP_SLE:
2950 std::swap(LHS, RHS);
2951 // fall through
2952 case ICmpInst::ICMP_SGT:
2953 case ICmpInst::ICMP_SGE:
2954 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002955 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002956 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002957 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002958 break;
2959 case ICmpInst::ICMP_ULT:
2960 case ICmpInst::ICMP_ULE:
2961 std::swap(LHS, RHS);
2962 // fall through
2963 case ICmpInst::ICMP_UGT:
2964 case ICmpInst::ICMP_UGE:
2965 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002966 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002967 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002968 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002969 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002970 case ICmpInst::ICMP_NE:
2971 // n != 0 ? n : 1 -> umax(n, 1)
2972 if (LHS == U->getOperand(1) &&
2973 isa<ConstantInt>(U->getOperand(2)) &&
2974 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2975 isa<ConstantInt>(RHS) &&
2976 cast<ConstantInt>(RHS)->isZero())
2977 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2978 break;
2979 case ICmpInst::ICMP_EQ:
2980 // n == 0 ? 1 : n -> umax(n, 1)
2981 if (LHS == U->getOperand(2) &&
2982 isa<ConstantInt>(U->getOperand(1)) &&
2983 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2984 isa<ConstantInt>(RHS) &&
2985 cast<ConstantInt>(RHS)->isZero())
2986 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2987 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002988 default:
2989 break;
2990 }
2991 }
2992
2993 default: // We cannot analyze this expression.
2994 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 }
2996
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002997 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998}
2999
3000
3001
3002//===----------------------------------------------------------------------===//
3003// Iteration Count Computation Code
3004//
3005
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003006/// getBackedgeTakenCount - If the specified loop has a predictable
3007/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3008/// object. The backedge-taken count is the number of times the loop header
3009/// will be branched to from within the loop. This is one less than the
3010/// trip count of the loop, since it doesn't count the first iteration,
3011/// when the header is branched to from outside the loop.
3012///
3013/// Note that it is not valid to call this method on a loop without a
3014/// loop-invariant backedge-taken count (see
3015/// hasLoopInvariantBackedgeTakenCount).
3016///
Dan Gohman161ea032009-07-07 17:06:11 +00003017const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003018 return getBackedgeTakenInfo(L).Exact;
3019}
3020
3021/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3022/// return the least SCEV value that is known never to be less than the
3023/// actual backedge taken count.
Dan Gohman161ea032009-07-07 17:06:11 +00003024const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003025 return getBackedgeTakenInfo(L).Max;
3026}
3027
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003028/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3029/// onto the given Worklist.
3030static void
3031PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3032 BasicBlock *Header = L->getHeader();
3033
3034 // Push all Loop-header PHIs onto the Worklist stack.
3035 for (BasicBlock::iterator I = Header->begin();
3036 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3037 Worklist.push_back(PN);
3038}
3039
3040/// PushDefUseChildren - Push users of the given Instruction
3041/// onto the given Worklist.
3042static void
3043PushDefUseChildren(Instruction *I,
3044 SmallVectorImpl<Instruction *> &Worklist) {
3045 // Push the def-use children onto the Worklist stack.
3046 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3047 UI != UE; ++UI)
3048 Worklist.push_back(cast<Instruction>(UI));
3049}
3050
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003051const ScalarEvolution::BackedgeTakenInfo &
3052ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00003053 // Initially insert a CouldNotCompute for this loop. If the insertion
3054 // succeeds, procede to actually compute a backedge-taken count and
3055 // update the value. The temporary CouldNotCompute value tells SCEV
3056 // code elsewhere that it shouldn't attempt to request a new
3057 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003058 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00003059 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3060 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003061 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003062 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003063 assert(ItCount.Exact->isLoopInvariant(L) &&
3064 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003065 "Computed trip count isn't loop invariant for loop!");
3066 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00003067
Dan Gohmana9dba962009-04-27 20:16:15 +00003068 // Update the value in the map.
3069 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003070 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003071 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003072 // Update the value in the map.
3073 Pair.first->second = ItCount;
3074 if (isa<PHINode>(L->getHeader()->begin()))
3075 // Only count loops that have phi nodes as not being computable.
3076 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003077 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003078
3079 // Now that we know more about the trip count for this loop, forget any
3080 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003081 // conservative estimates made without the benefit of trip count
3082 // information. This is similar to the code in
3083 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3084 // nodes specially.
3085 if (ItCount.hasAnyInfo()) {
3086 SmallVector<Instruction *, 16> Worklist;
3087 PushLoopPHIs(L, Worklist);
3088
3089 SmallPtrSet<Instruction *, 8> Visited;
3090 while (!Worklist.empty()) {
3091 Instruction *I = Worklist.pop_back_val();
3092 if (!Visited.insert(I)) continue;
3093
3094 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3095 Scalars.find(static_cast<Value *>(I));
3096 if (It != Scalars.end()) {
3097 // SCEVUnknown for a PHI either means that it has an unrecognized
3098 // structure, or it's a PHI that's in the progress of being computed
Dan Gohman0fa91f32009-07-13 22:04:06 +00003099 // by createNodeForPHI. In the former case, additional loop trip
3100 // count information isn't going to change anything. In the later
3101 // case, createNodeForPHI will perform the necessary updates on its
3102 // own when it gets to that point.
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003103 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3104 Scalars.erase(It);
3105 ValuesAtScopes.erase(I);
3106 if (PHINode *PN = dyn_cast<PHINode>(I))
3107 ConstantEvolutionLoopExitValue.erase(PN);
3108 }
3109
3110 PushDefUseChildren(I, Worklist);
3111 }
3112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003113 }
Dan Gohmana9dba962009-04-27 20:16:15 +00003114 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115}
3116
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003117/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003118/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003119/// ScalarEvolution's ability to compute a trip count, or if the loop
3120/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003121void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003122 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00003123
Dan Gohmanbff6b582009-05-04 22:30:44 +00003124 SmallVector<Instruction *, 16> Worklist;
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003125 PushLoopPHIs(L, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003126
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003127 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00003128 while (!Worklist.empty()) {
3129 Instruction *I = Worklist.pop_back_val();
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003130 if (!Visited.insert(I)) continue;
3131
3132 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3133 Scalars.find(static_cast<Value *>(I));
3134 if (It != Scalars.end()) {
3135 Scalars.erase(It);
3136 ValuesAtScopes.erase(I);
3137 if (PHINode *PN = dyn_cast<PHINode>(I))
3138 ConstantEvolutionLoopExitValue.erase(PN);
3139 }
3140
3141 PushDefUseChildren(I, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003142 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003143}
3144
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003145/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3146/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003147ScalarEvolution::BackedgeTakenInfo
3148ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00003149 SmallVector<BasicBlock*, 8> ExitingBlocks;
3150 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151
Dan Gohman8e8b5232009-06-22 00:31:57 +00003152 // Examine all exits and pick the most conservative values.
Dan Gohman161ea032009-07-07 17:06:11 +00003153 const SCEV *BECount = getCouldNotCompute();
3154 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003155 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003156 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3157 BackedgeTakenInfo NewBTI =
3158 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003160 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00003161 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00003162 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003163 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003164 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003165 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003166 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003167 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003168 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00003169 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003170 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003171 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003172 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003173 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003174 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003175 }
3176
3177 return BackedgeTakenInfo(BECount, MaxBECount);
3178}
3179
3180/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3181/// of the specified loop will execute if it exits via the specified block.
3182ScalarEvolution::BackedgeTakenInfo
3183ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3184 BasicBlock *ExitingBlock) {
3185
3186 // Okay, we've chosen an exiting block. See what condition causes us to
3187 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 //
3189 // FIXME: we should be able to handle switch instructions (with a single exit)
3190 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003191 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00003193
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194 // At this point, we know we have a conditional branch that determines whether
3195 // the loop is exited. However, we don't know if the branch is executed each
3196 // time through the loop. If not, then the execution count of the branch will
3197 // not be equal to the trip count of the loop.
3198 //
3199 // Currently we check for this by checking to see if the Exit branch goes to
3200 // the loop header. If so, we know it will always execute the same number of
3201 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00003202 // loop header. This is common for un-rotated loops.
3203 //
3204 // If both of those tests fail, walk up the unique predecessor chain to the
3205 // header, stopping if there is an edge that doesn't exit the loop. If the
3206 // header is reached, the execution count of the branch will be equal to the
3207 // trip count of the loop.
3208 //
3209 // More extensive analysis could be done to handle more cases here.
3210 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3212 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003213 ExitBr->getParent() != L->getHeader()) {
3214 // The simple checks failed, try climbing the unique predecessor chain
3215 // up to the header.
3216 bool Ok = false;
3217 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3218 BasicBlock *Pred = BB->getUniquePredecessor();
3219 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003220 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003221 TerminatorInst *PredTerm = Pred->getTerminator();
3222 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3223 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3224 if (PredSucc == BB)
3225 continue;
3226 // If the predecessor has a successor that isn't BB and isn't
3227 // outside the loop, assume the worst.
3228 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003229 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003230 }
3231 if (Pred == L->getHeader()) {
3232 Ok = true;
3233 break;
3234 }
3235 BB = Pred;
3236 }
3237 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003238 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003239 }
3240
3241 // Procede to the next level to examine the exit condition expression.
3242 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3243 ExitBr->getSuccessor(0),
3244 ExitBr->getSuccessor(1));
3245}
3246
3247/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3248/// backedge of the specified loop will execute if its exit condition
3249/// were a conditional branch of ExitCond, TBB, and FBB.
3250ScalarEvolution::BackedgeTakenInfo
3251ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3252 Value *ExitCond,
3253 BasicBlock *TBB,
3254 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003255 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3257 if (BO->getOpcode() == Instruction::And) {
3258 // Recurse on the operands of the and.
3259 BackedgeTakenInfo BTI0 =
3260 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3261 BackedgeTakenInfo BTI1 =
3262 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003263 const SCEV *BECount = getCouldNotCompute();
3264 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003265 if (L->contains(TBB)) {
3266 // Both conditions must be true for the loop to continue executing.
3267 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003268 if (BTI0.Exact == getCouldNotCompute() ||
3269 BTI1.Exact == getCouldNotCompute())
3270 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003271 else
3272 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003273 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003274 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003275 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003276 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003277 else
3278 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003279 } else {
3280 // Both conditions must be true for the loop to exit.
3281 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003282 if (BTI0.Exact != getCouldNotCompute() &&
3283 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003284 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003285 if (BTI0.Max != getCouldNotCompute() &&
3286 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003287 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3288 }
3289
3290 return BackedgeTakenInfo(BECount, MaxBECount);
3291 }
3292 if (BO->getOpcode() == Instruction::Or) {
3293 // Recurse on the operands of the or.
3294 BackedgeTakenInfo BTI0 =
3295 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3296 BackedgeTakenInfo BTI1 =
3297 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003298 const SCEV *BECount = getCouldNotCompute();
3299 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003300 if (L->contains(FBB)) {
3301 // Both conditions must be false for the loop to continue executing.
3302 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003303 if (BTI0.Exact == getCouldNotCompute() ||
3304 BTI1.Exact == getCouldNotCompute())
3305 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003306 else
3307 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003308 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003309 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003310 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003311 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003312 else
3313 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003314 } else {
3315 // Both conditions must be false for the loop to exit.
3316 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003317 if (BTI0.Exact != getCouldNotCompute() &&
3318 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003319 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003320 if (BTI0.Max != getCouldNotCompute() &&
3321 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003322 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3323 }
3324
3325 return BackedgeTakenInfo(BECount, MaxBECount);
3326 }
3327 }
3328
3329 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3330 // Procede to the next level to examine the icmp.
3331 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3332 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003333
Eli Friedman459d7292009-05-09 12:32:42 +00003334 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003335 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3336}
3337
3338/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3339/// backedge of the specified loop will execute if its exit condition
3340/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3341ScalarEvolution::BackedgeTakenInfo
3342ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3343 ICmpInst *ExitCond,
3344 BasicBlock *TBB,
3345 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346
3347 // If the condition was exit on true, convert the condition to exit on false
3348 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003349 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350 Cond = ExitCond->getPredicate();
3351 else
3352 Cond = ExitCond->getInversePredicate();
3353
3354 // Handle common loops like: for (X = "string"; *X; ++X)
3355 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3356 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00003357 const SCEV *ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003358 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003359 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3360 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3361 return BackedgeTakenInfo(ItCnt,
3362 isa<SCEVConstant>(ItCnt) ? ItCnt :
3363 getConstant(APInt::getMaxValue(BitWidth)-1));
3364 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 }
3366
Dan Gohman161ea032009-07-07 17:06:11 +00003367 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3368 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369
3370 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003371 LHS = getSCEVAtScope(LHS, L);
3372 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003373
Dan Gohman9bc642f2009-06-24 04:48:43 +00003374 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003376 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3377 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 std::swap(LHS, RHS);
3379 Cond = ICmpInst::getSwappedPredicate(Cond);
3380 }
3381
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382 // If we have a comparison of a chrec against a constant, try to use value
3383 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003384 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3385 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003386 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003387 // Form the constant range.
3388 ConstantRange CompRange(
3389 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003390
Dan Gohman161ea032009-07-07 17:06:11 +00003391 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003392 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393 }
3394
3395 switch (Cond) {
3396 case ICmpInst::ICMP_NE: { // while (X != Y)
3397 // Convert to: while (X-Y != 0)
Dan Gohman161ea032009-07-07 17:06:11 +00003398 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3400 break;
3401 }
3402 case ICmpInst::ICMP_EQ: {
3403 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman161ea032009-07-07 17:06:11 +00003404 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3406 break;
3407 }
3408 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003409 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3410 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 break;
3412 }
3413 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003414 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3415 getNotSCEV(RHS), L, true);
3416 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003417 break;
3418 }
3419 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003420 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3421 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003422 break;
3423 }
3424 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003425 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3426 getNotSCEV(RHS), L, false);
3427 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003428 break;
3429 }
3430 default:
3431#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003432 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003433 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003434 errs() << "[unsigned] ";
3435 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003436 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003437 << " " << *RHS << "\n";
3438#endif
3439 break;
3440 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003441 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003442 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003443}
3444
3445static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003446EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3447 ScalarEvolution &SE) {
Dan Gohman161ea032009-07-07 17:06:11 +00003448 const SCEV *InVal = SE.getConstant(C);
3449 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003450 assert(isa<SCEVConstant>(Val) &&
3451 "Evaluation of SCEV at constant didn't fold correctly?");
3452 return cast<SCEVConstant>(Val)->getValue();
3453}
3454
3455/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3456/// and a GEP expression (missing the pointer index) indexing into it, return
3457/// the addressed element of the initializer or null if the index expression is
3458/// invalid.
3459static Constant *
Owen Anderson15b39322009-07-13 04:09:18 +00003460GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461 const std::vector<ConstantInt*> &Indices) {
3462 Constant *Init = GV->getInitializer();
3463 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3464 uint64_t Idx = Indices[i]->getZExtValue();
3465 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3466 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3467 Init = cast<Constant>(CS->getOperand(Idx));
3468 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3469 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3470 Init = cast<Constant>(CA->getOperand(Idx));
3471 } else if (isa<ConstantAggregateZero>(Init)) {
3472 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3473 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Anderson15b39322009-07-13 04:09:18 +00003474 Init = Context->getNullValue(STy->getElementType(Idx));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003475 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3476 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Anderson15b39322009-07-13 04:09:18 +00003477 Init = Context->getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00003479 llvm_unreachable("Unknown constant aggregate type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003480 }
3481 return 0;
3482 } else {
3483 return 0; // Unknown initializer type
3484 }
3485 }
3486 return Init;
3487}
3488
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003489/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3490/// 'icmp op load X, cst', try to see if we can compute the backedge
3491/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003492const SCEV *
3493ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3494 LoadInst *LI,
3495 Constant *RHS,
3496 const Loop *L,
3497 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003498 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499
3500 // Check to see if the loaded pointer is a getelementptr of a global.
3501 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003502 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003503
3504 // Make sure that it is really a constant global we are gepping, with an
3505 // initializer, and make sure the first IDX is really 0.
3506 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3507 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3508 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3509 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003510 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511
3512 // Okay, we allow one non-constant index into the GEP instruction.
3513 Value *VarIdx = 0;
3514 std::vector<ConstantInt*> Indexes;
3515 unsigned VarIdxNum = 0;
3516 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3517 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3518 Indexes.push_back(CI);
3519 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003520 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521 VarIdx = GEP->getOperand(i);
3522 VarIdxNum = i-2;
3523 Indexes.push_back(0);
3524 }
3525
3526 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3527 // Check to see if X is a loop variant variable value now.
Dan Gohman161ea032009-07-07 17:06:11 +00003528 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003529 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530
3531 // We can only recognize very limited forms of loop index expressions, in
3532 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003533 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3535 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3536 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003537 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003538
3539 unsigned MaxSteps = MaxBruteForceIterations;
3540 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00003541 ConstantInt *ItCst = Context->getConstantInt(
3542 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003543 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003544
3545 // Form the GEP offset.
3546 Indexes[VarIdxNum] = Val;
3547
Owen Anderson15b39322009-07-13 04:09:18 +00003548 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 if (Result == 0) break; // Cannot compute!
3550
3551 // Evaluate the condition for this iteration.
3552 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3553 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3554 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3555#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003556 errs() << "\n***\n*** Computed loop count " << *ItCst
3557 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3558 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559#endif
3560 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003561 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562 }
3563 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003564 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565}
3566
3567
3568/// CanConstantFold - Return true if we can constant fold an instruction of the
3569/// specified type, assuming that all operands were constants.
3570static bool CanConstantFold(const Instruction *I) {
3571 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3572 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3573 return true;
3574
3575 if (const CallInst *CI = dyn_cast<CallInst>(I))
3576 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003577 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 return false;
3579}
3580
3581/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3582/// in the loop that V is derived from. We allow arbitrary operations along the
3583/// way, but the operands of an operation must either be constants or a value
3584/// derived from a constant PHI. If this expression does not fit with these
3585/// constraints, return null.
3586static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3587 // If this is not an instruction, or if this is an instruction outside of the
3588 // loop, it can't be derived from a loop PHI.
3589 Instruction *I = dyn_cast<Instruction>(V);
3590 if (I == 0 || !L->contains(I->getParent())) return 0;
3591
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003592 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003593 if (L->getHeader() == I->getParent())
3594 return PN;
3595 else
3596 // We don't currently keep track of the control flow needed to evaluate
3597 // PHIs, so we cannot handle PHIs inside of loops.
3598 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003599 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003600
3601 // If we won't be able to constant fold this expression even if the operands
3602 // are constants, return early.
3603 if (!CanConstantFold(I)) return 0;
3604
3605 // Otherwise, we can evaluate this instruction if all of its operands are
3606 // constant or derived from a PHI node themselves.
3607 PHINode *PHI = 0;
3608 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3609 if (!(isa<Constant>(I->getOperand(Op)) ||
3610 isa<GlobalValue>(I->getOperand(Op)))) {
3611 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3612 if (P == 0) return 0; // Not evolving from PHI
3613 if (PHI == 0)
3614 PHI = P;
3615 else if (PHI != P)
3616 return 0; // Evolving from multiple different PHIs.
3617 }
3618
3619 // This is a expression evolving from a constant PHI!
3620 return PHI;
3621}
3622
3623/// EvaluateExpression - Given an expression that passes the
3624/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3625/// in the loop has the value PHIVal. If we can't fold this expression for some
3626/// reason, return null.
3627static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3628 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003629 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003630 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003631 Instruction *I = cast<Instruction>(V);
Owen Anderson5349f052009-07-06 23:00:19 +00003632 LLVMContext *Context = I->getParent()->getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633
3634 std::vector<Constant*> Operands;
3635 Operands.resize(I->getNumOperands());
3636
3637 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3638 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3639 if (Operands[i] == 0) return 0;
3640 }
3641
Chris Lattnerd6e56912007-12-10 22:53:04 +00003642 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3643 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003644 &Operands[0], Operands.size(),
3645 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003646 else
3647 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003648 &Operands[0], Operands.size(),
3649 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650}
3651
3652/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3653/// in the header of its containing loop, we know the loop executes a
3654/// constant number of times, and the PHI node is just a recurrence
3655/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003656Constant *
3657ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3658 const APInt& BEs,
3659 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003660 std::map<PHINode*, Constant*>::iterator I =
3661 ConstantEvolutionLoopExitValue.find(PN);
3662 if (I != ConstantEvolutionLoopExitValue.end())
3663 return I->second;
3664
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003665 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003666 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3667
3668 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3669
3670 // Since the loop is canonicalized, the PHI node must have two entries. One
3671 // entry must be a constant (coming in from outside of the loop), and the
3672 // second must be derived from the same PHI.
3673 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3674 Constant *StartCST =
3675 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3676 if (StartCST == 0)
3677 return RetVal = 0; // Must be a constant.
3678
3679 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3680 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3681 if (PN2 != PN)
3682 return RetVal = 0; // Not derived from same PHI.
3683
3684 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003685 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3687
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003688 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003689 unsigned IterationNum = 0;
3690 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3691 if (IterationNum == NumIterations)
3692 return RetVal = PHIVal; // Got exit value!
3693
3694 // Compute the value of the PHI node for the next iteration.
3695 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3696 if (NextPHI == PHIVal)
3697 return RetVal = NextPHI; // Stopped evolving!
3698 if (NextPHI == 0)
3699 return 0; // Couldn't evaluate!
3700 PHIVal = NextPHI;
3701 }
3702}
3703
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003704/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003705/// constant number of times (the condition evolves only from constants),
3706/// try to evaluate a few iterations of the loop until we get the exit
3707/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003708/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003709const SCEV *
3710ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3711 Value *Cond,
3712 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003714 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003715
3716 // Since the loop is canonicalized, the PHI node must have two entries. One
3717 // entry must be a constant (coming in from outside of the loop), and the
3718 // second must be derived from the same PHI.
3719 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3720 Constant *StartCST =
3721 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003722 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003723
3724 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3725 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003726 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003727
3728 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3729 // the loop symbolically to determine when the condition gets a value of
3730 // "ExitWhen".
3731 unsigned IterationNum = 0;
3732 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3733 for (Constant *PHIVal = StartCST;
3734 IterationNum != MaxIterations; ++IterationNum) {
3735 ConstantInt *CondVal =
3736 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3737
3738 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003739 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003740
3741 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003743 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003744 }
3745
3746 // Compute the value of the PHI node for the next iteration.
3747 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3748 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003749 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003750 PHIVal = NextPHI;
3751 }
3752
3753 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003754 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755}
3756
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003757/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3758/// at the specified scope in the program. The L value specifies a loop
3759/// nest to evaluate the expression at, where null is the top-level or a
3760/// specified loop is immediately inside of the loop.
3761///
3762/// This method can be used to compute the exit value for a variable defined
3763/// in a loop by querying what the value will hold in the parent loop.
3764///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003765/// In the case that a relevant loop exit value cannot be computed, the
3766/// original value V is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003767const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003768 // FIXME: this should be turned into a virtual method on SCEV!
3769
3770 if (isa<SCEVConstant>(V)) return V;
3771
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003772 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003773 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003774 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003776 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003777 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3778 if (PHINode *PN = dyn_cast<PHINode>(I))
3779 if (PN->getParent() == LI->getHeader()) {
3780 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003781 // to see if the loop that contains it has a known backedge-taken
3782 // count. If so, we may be able to force computation of the exit
3783 // value.
Dan Gohman161ea032009-07-07 17:06:11 +00003784 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003785 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003786 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003787 // Okay, we know how many times the containing loop executes. If
3788 // this is a constant evolving PHI node, get the final value at
3789 // the specified iteration number.
3790 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003791 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003792 LI);
Dan Gohman652caf12009-06-29 21:31:18 +00003793 if (RV) return getSCEV(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003794 }
3795 }
3796
3797 // Okay, this is an expression that we cannot symbolically evaluate
3798 // into a SCEV. Check to see if it's possible to symbolically evaluate
3799 // the arguments into constants, and if so, try to constant propagate the
3800 // result. This is particularly useful for computing loop exit values.
3801 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003802 // Check to see if we've folded this instruction at this loop before.
3803 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3804 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3805 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3806 if (!Pair.second)
Dan Gohman652caf12009-06-29 21:31:18 +00003807 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohmanda0071e2009-05-08 20:47:27 +00003808
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003809 std::vector<Constant*> Operands;
3810 Operands.reserve(I->getNumOperands());
3811 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3812 Value *Op = I->getOperand(i);
3813 if (Constant *C = dyn_cast<Constant>(Op)) {
3814 Operands.push_back(C);
3815 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003816 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003817 // non-integer and non-pointer, don't even try to analyze them
3818 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003819 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003820 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003821
Dan Gohman55e2d7e2009-07-13 21:35:55 +00003822 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003823 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003824 Constant *C = SC->getValue();
3825 if (C->getType() != Op->getType())
3826 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3827 Op->getType(),
3828 false),
3829 C, Op->getType());
3830 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003831 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003832 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3833 if (C->getType() != Op->getType())
3834 C =
3835 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3836 Op->getType(),
3837 false),
3838 C, Op->getType());
3839 Operands.push_back(C);
3840 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003841 return V;
3842 } else {
3843 return V;
3844 }
3845 }
3846 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003847
Chris Lattnerd6e56912007-12-10 22:53:04 +00003848 Constant *C;
3849 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3850 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003851 &Operands[0], Operands.size(),
3852 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003853 else
3854 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003855 &Operands[0], Operands.size(), Context);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003856 Pair.first->second = C;
Dan Gohman652caf12009-06-29 21:31:18 +00003857 return getSCEV(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858 }
3859 }
3860
3861 // This is some other type of SCEVUnknown, just return it.
3862 return V;
3863 }
3864
Dan Gohmanc76b5452009-05-04 22:02:23 +00003865 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 // Avoid performing the look-up in the common case where the specified
3867 // expression has no loop-variant portions.
3868 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00003869 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003870 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003871 // Okay, at least one of these operands is loop variant but might be
3872 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003873 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3874 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003875 NewOps.push_back(OpAtScope);
3876
3877 for (++i; i != e; ++i) {
3878 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003879 NewOps.push_back(OpAtScope);
3880 }
3881 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003882 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003883 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003884 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003885 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003886 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003887 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003888 return getUMaxExpr(NewOps);
Edwin Törökbd448e32009-07-14 16:55:14 +00003889 llvm_unreachable("Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003890 }
3891 }
3892 // If we got here, all operands are loop invariant.
3893 return Comm;
3894 }
3895
Dan Gohmanc76b5452009-05-04 22:02:23 +00003896 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003897 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3898 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003899 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3900 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003901 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 }
3903
3904 // If this is a loop recurrence for a loop that does not contain L, then we
3905 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003906 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003907 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3908 // To evaluate this recurrence, we need to know how many times the AddRec
3909 // loop iterates. Compute this now.
Dan Gohman161ea032009-07-07 17:06:11 +00003910 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003911 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003912
Eli Friedman7489ec92008-08-04 23:49:06 +00003913 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003914 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003915 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003916 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003917 }
3918
Dan Gohmanc76b5452009-05-04 22:02:23 +00003919 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003920 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003921 if (Op == Cast->getOperand())
3922 return Cast; // must be loop invariant
3923 return getZeroExtendExpr(Op, Cast->getType());
3924 }
3925
Dan Gohmanc76b5452009-05-04 22:02:23 +00003926 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003927 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003928 if (Op == Cast->getOperand())
3929 return Cast; // must be loop invariant
3930 return getSignExtendExpr(Op, Cast->getType());
3931 }
3932
Dan Gohmanc76b5452009-05-04 22:02:23 +00003933 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003934 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003935 if (Op == Cast->getOperand())
3936 return Cast; // must be loop invariant
3937 return getTruncateExpr(Op, Cast->getType());
3938 }
3939
Edwin Törökbd448e32009-07-14 16:55:14 +00003940 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003941 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003942}
3943
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003944/// getSCEVAtScope - This is a convenience function which does
3945/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman161ea032009-07-07 17:06:11 +00003946const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003947 return getSCEVAtScope(getSCEV(V), L);
3948}
3949
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003950/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3951/// following equation:
3952///
3953/// A * X = B (mod N)
3954///
3955/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3956/// A and B isn't important.
3957///
3958/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003959static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003960 ScalarEvolution &SE) {
3961 uint32_t BW = A.getBitWidth();
3962 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3963 assert(A != 0 && "A must be non-zero.");
3964
3965 // 1. D = gcd(A, N)
3966 //
3967 // The gcd of A and N may have only one prime factor: 2. The number of
3968 // trailing zeros in A is its multiplicity
3969 uint32_t Mult2 = A.countTrailingZeros();
3970 // D = 2^Mult2
3971
3972 // 2. Check if B is divisible by D.
3973 //
3974 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3975 // is not less than multiplicity of this prime factor for D.
3976 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003977 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003978
3979 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3980 // modulo (N / D).
3981 //
3982 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3983 // bit width during computations.
3984 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3985 APInt Mod(BW + 1, 0);
3986 Mod.set(BW - Mult2); // Mod = N / D
3987 APInt I = AD.multiplicativeInverse(Mod);
3988
3989 // 4. Compute the minimum unsigned root of the equation:
3990 // I * (B / D) mod (N / D)
3991 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3992
3993 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3994 // bits.
3995 return SE.getConstant(Result.trunc(BW));
3996}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997
3998/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3999/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4000/// might be the same) or two SCEVCouldNotCompute objects.
4001///
Dan Gohman161ea032009-07-07 17:06:11 +00004002static std::pair<const SCEV *,const SCEV *>
Dan Gohman89f85052007-10-22 18:31:58 +00004003SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004004 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004005 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4006 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4007 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004008
4009 // We currently can only solve this if the coefficients are constants.
4010 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004011 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004012 return std::make_pair(CNC, CNC);
4013 }
4014
4015 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4016 const APInt &L = LC->getValue()->getValue();
4017 const APInt &M = MC->getValue()->getValue();
4018 const APInt &N = NC->getValue()->getValue();
4019 APInt Two(BitWidth, 2);
4020 APInt Four(BitWidth, 4);
4021
Dan Gohman9bc642f2009-06-24 04:48:43 +00004022 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004023 using namespace APIntOps;
4024 const APInt& C = L;
4025 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4026 // The B coefficient is M-N/2
4027 APInt B(M);
4028 B -= sdiv(N,Two);
4029
4030 // The A coefficient is N/2
4031 APInt A(N.sdiv(Two));
4032
4033 // Compute the B^2-4ac term.
4034 APInt SqrtTerm(B);
4035 SqrtTerm *= B;
4036 SqrtTerm -= Four * (A * C);
4037
4038 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4039 // integer value or else APInt::sqrt() will assert.
4040 APInt SqrtVal(SqrtTerm.sqrt());
4041
Dan Gohman9bc642f2009-06-24 04:48:43 +00004042 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004043 // The divisions must be performed as signed divisions.
4044 APInt NegB(-B);
4045 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00004046 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004047 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00004048 return std::make_pair(CNC, CNC);
4049 }
4050
Owen Andersone755b092009-07-06 22:37:39 +00004051 LLVMContext *Context = SE.getContext();
4052
4053 ConstantInt *Solution1 =
4054 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4055 ConstantInt *Solution2 =
4056 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004057
Dan Gohman9bc642f2009-06-24 04:48:43 +00004058 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00004059 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004060 } // end APIntOps namespace
4061}
4062
4063/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00004064/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman161ea032009-07-07 17:06:11 +00004065const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004066 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00004067 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004068 // If the value is already zero, the branch will execute zero times.
4069 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004070 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004071 }
4072
Dan Gohmanbff6b582009-05-04 22:30:44 +00004073 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004074 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004075 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076
4077 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004078 // If this is an affine expression, the execution count of this branch is
4079 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004080 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004081 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004082 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004083 // equivalent to:
4084 //
4085 // Step*N = -Start (mod 2^BW)
4086 //
4087 // where BW is the common bit width of Start and Step.
4088
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004090 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4091 L->getParentLoop());
4092 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4093 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004094
Dan Gohmanc76b5452009-05-04 22:02:23 +00004095 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004096 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004097
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004098 // First, handle unitary steps.
4099 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004100 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004101 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4102 return Start; // N = Start (as unsigned)
4103
4104 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004105 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004106 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004107 -StartC->getValue()->getValue(),
4108 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004109 }
4110 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4111 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4112 // the quadratic equation to solve it.
Dan Gohman161ea032009-07-07 17:06:11 +00004113 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004114 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004115 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4116 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004117 if (R1) {
4118#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00004119 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4120 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004121#endif
4122 // Pick the smallest positive root value.
4123 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004124 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004125 R1->getValue(), R2->getValue()))) {
4126 if (CB->getZExtValue() == false)
4127 std::swap(R1, R2); // R1 is the minimum root now.
4128
4129 // We can only use this value if the chrec ends up with an exact zero
4130 // value at this index. When solving for "X*X != 5", for example, we
4131 // should not accept a root of 2.
Dan Gohman161ea032009-07-07 17:06:11 +00004132 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00004133 if (Val->isZero())
4134 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135 }
4136 }
4137 }
4138
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004139 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004140}
4141
4142/// HowFarToNonZero - Return the number of times a backedge checking the
4143/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004144/// CouldNotCompute
Dan Gohman161ea032009-07-07 17:06:11 +00004145const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 // Loops that look like: while (X == 0) are very strange indeed. We don't
4147 // handle them yet except for the trivial case. This could be expanded in the
4148 // future as needed.
4149
4150 // If the value is a constant, check to see if it is known to be non-zero
4151 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004152 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00004153 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004154 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004155 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004156 }
4157
4158 // We could implement others, but I really doubt anyone writes loops like
4159 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004160 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004161}
4162
Dan Gohmanab157b22009-05-18 15:36:09 +00004163/// getLoopPredecessor - If the given loop's header has exactly one unique
4164/// predecessor outside the loop, return it. Otherwise return null.
4165///
4166BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4167 BasicBlock *Header = L->getHeader();
4168 BasicBlock *Pred = 0;
4169 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4170 PI != E; ++PI)
4171 if (!L->contains(*PI)) {
4172 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4173 Pred = *PI;
4174 }
4175 return Pred;
4176}
4177
Dan Gohman1cddf972008-09-15 22:18:04 +00004178/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4179/// (which may not be an immediate predecessor) which has exactly one
4180/// successor from which BB is reachable, or null if no such block is
4181/// found.
4182///
4183BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004184ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00004185 // If the block has a unique predecessor, then there is no path from the
4186 // predecessor to the block that does not go through the direct edge
4187 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00004188 if (BasicBlock *Pred = BB->getSinglePredecessor())
4189 return Pred;
4190
4191 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00004192 // If the header has a unique predecessor outside the loop, it must be
4193 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004194 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00004195 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00004196
4197 return 0;
4198}
4199
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004200/// HasSameValue - SCEV structural equivalence is usually sufficient for
4201/// testing whether two expressions are equal, however for the purposes of
4202/// looking for a condition guarding a loop, it can be useful to be a little
4203/// more general, since a front-end may have replicated the controlling
4204/// expression.
4205///
Dan Gohman161ea032009-07-07 17:06:11 +00004206static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004207 // Quick check to see if they are the same SCEV.
4208 if (A == B) return true;
4209
4210 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4211 // two different instructions with the same value. Check for this case.
4212 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4213 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4214 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4215 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4216 if (AI->isIdenticalTo(BI))
4217 return true;
4218
4219 // Otherwise assume they may have a different value.
4220 return false;
4221}
4222
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004223bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4224 return getSignedRange(S).getSignedMax().isNegative();
4225}
4226
4227bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4228 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4229}
4230
4231bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4232 return !getSignedRange(S).getSignedMin().isNegative();
4233}
4234
4235bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4236 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4237}
4238
4239bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4240 return isKnownNegative(S) || isKnownPositive(S);
4241}
4242
4243bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4244 const SCEV *LHS, const SCEV *RHS) {
4245
4246 if (HasSameValue(LHS, RHS))
4247 return ICmpInst::isTrueWhenEqual(Pred);
4248
4249 switch (Pred) {
4250 default:
4251 assert(0 && "Unexpected ICmpInst::Predicate value!");
4252 break;
4253 case ICmpInst::ICMP_SGT:
4254 Pred = ICmpInst::ICMP_SLT;
4255 std::swap(LHS, RHS);
4256 case ICmpInst::ICMP_SLT: {
4257 ConstantRange LHSRange = getSignedRange(LHS);
4258 ConstantRange RHSRange = getSignedRange(RHS);
4259 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4260 return true;
4261 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4262 return false;
4263
4264 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4265 ConstantRange DiffRange = getUnsignedRange(Diff);
4266 if (isKnownNegative(Diff)) {
4267 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4268 return true;
4269 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4270 return false;
4271 } else if (isKnownPositive(Diff)) {
4272 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4273 return true;
4274 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4275 return false;
4276 }
4277 break;
4278 }
4279 case ICmpInst::ICMP_SGE:
4280 Pred = ICmpInst::ICMP_SLE;
4281 std::swap(LHS, RHS);
4282 case ICmpInst::ICMP_SLE: {
4283 ConstantRange LHSRange = getSignedRange(LHS);
4284 ConstantRange RHSRange = getSignedRange(RHS);
4285 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4286 return true;
4287 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4288 return false;
4289
4290 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4291 ConstantRange DiffRange = getUnsignedRange(Diff);
4292 if (isKnownNonPositive(Diff)) {
4293 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4294 return true;
4295 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4296 return false;
4297 } else if (isKnownNonNegative(Diff)) {
4298 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4299 return true;
4300 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4301 return false;
4302 }
4303 break;
4304 }
4305 case ICmpInst::ICMP_UGT:
4306 Pred = ICmpInst::ICMP_ULT;
4307 std::swap(LHS, RHS);
4308 case ICmpInst::ICMP_ULT: {
4309 ConstantRange LHSRange = getUnsignedRange(LHS);
4310 ConstantRange RHSRange = getUnsignedRange(RHS);
4311 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4312 return true;
4313 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4314 return false;
4315
4316 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4317 ConstantRange DiffRange = getUnsignedRange(Diff);
4318 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4319 return true;
4320 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4321 return false;
4322 break;
4323 }
4324 case ICmpInst::ICMP_UGE:
4325 Pred = ICmpInst::ICMP_ULE;
4326 std::swap(LHS, RHS);
4327 case ICmpInst::ICMP_ULE: {
4328 ConstantRange LHSRange = getUnsignedRange(LHS);
4329 ConstantRange RHSRange = getUnsignedRange(RHS);
4330 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4331 return true;
4332 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4333 return false;
4334
4335 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4336 ConstantRange DiffRange = getUnsignedRange(Diff);
4337 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4338 return true;
4339 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4340 return false;
4341 break;
4342 }
4343 case ICmpInst::ICMP_NE: {
4344 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4345 return true;
4346 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4347 return true;
4348
4349 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4350 if (isKnownNonZero(Diff))
4351 return true;
4352 break;
4353 }
4354 case ICmpInst::ICMP_EQ:
4355 break;
4356 }
4357 return false;
4358}
4359
4360/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4361/// protected by a conditional between LHS and RHS. This is used to
4362/// to eliminate casts.
4363bool
4364ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4365 ICmpInst::Predicate Pred,
4366 const SCEV *LHS, const SCEV *RHS) {
4367 // Interpret a null as meaning no loop, where there is obviously no guard
4368 // (interprocedural conditions notwithstanding).
4369 if (!L) return true;
4370
4371 BasicBlock *Latch = L->getLoopLatch();
4372 if (!Latch)
4373 return false;
4374
4375 BranchInst *LoopContinuePredicate =
4376 dyn_cast<BranchInst>(Latch->getTerminator());
4377 if (!LoopContinuePredicate ||
4378 LoopContinuePredicate->isUnconditional())
4379 return false;
4380
4381 return
4382 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4383 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4384}
4385
4386/// isLoopGuardedByCond - Test whether entry to the loop is protected
4387/// by a conditional between LHS and RHS. This is used to help avoid max
4388/// expressions in loop trip counts, and to eliminate casts.
4389bool
4390ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4391 ICmpInst::Predicate Pred,
4392 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004393 // Interpret a null as meaning no loop, where there is obviously no guard
4394 // (interprocedural conditions notwithstanding).
4395 if (!L) return false;
4396
Dan Gohmanab157b22009-05-18 15:36:09 +00004397 BasicBlock *Predecessor = getLoopPredecessor(L);
4398 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004399
Dan Gohmanab157b22009-05-18 15:36:09 +00004400 // Starting at the loop predecessor, climb up the predecessor chain, as long
4401 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004402 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004403 for (; Predecessor;
4404 PredecessorDest = Predecessor,
4405 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004406
4407 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004408 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004409 if (!LoopEntryPredicate ||
4410 LoopEntryPredicate->isUnconditional())
4411 continue;
4412
Dan Gohman423ed6c2009-06-24 01:18:18 +00004413 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4414 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004415 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004416 }
4417
Dan Gohmanab678fb2008-08-12 20:17:31 +00004418 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004419}
4420
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004421/// isNecessaryCond - Test whether the condition described by Pred, LHS,
4422/// and RHS is a necessary condition for the given Cond value to evaluate
4423/// to true.
Dan Gohman423ed6c2009-06-24 01:18:18 +00004424bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4425 ICmpInst::Predicate Pred,
4426 const SCEV *LHS, const SCEV *RHS,
4427 bool Inverse) {
4428 // Recursivly handle And and Or conditions.
4429 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4430 if (BO->getOpcode() == Instruction::And) {
4431 if (!Inverse)
4432 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4433 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4434 } else if (BO->getOpcode() == Instruction::Or) {
4435 if (Inverse)
4436 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4437 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4438 }
4439 }
4440
4441 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4442 if (!ICI) return false;
4443
4444 // Now that we found a conditional branch that dominates the loop, check to
4445 // see if it is the comparison we are looking for.
4446 Value *PreCondLHS = ICI->getOperand(0);
4447 Value *PreCondRHS = ICI->getOperand(1);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004448 ICmpInst::Predicate FoundPred;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004449 if (Inverse)
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004450 FoundPred = ICI->getInversePredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004451 else
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004452 FoundPred = ICI->getPredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004453
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004454 if (FoundPred == Pred)
Dan Gohman423ed6c2009-06-24 01:18:18 +00004455 ; // An exact match.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004456 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4457 // The actual condition is beyond sufficient.
4458 FoundPred = ICmpInst::ICMP_NE;
4459 // NE is symmetric but the original comparison may not be. Swap
4460 // the operands if necessary so that they match below.
4461 if (isa<SCEVConstant>(LHS))
4462 std::swap(PreCondLHS, PreCondRHS);
4463 } else
Dan Gohman423ed6c2009-06-24 01:18:18 +00004464 // Check a few special cases.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004465 switch (FoundPred) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00004466 case ICmpInst::ICMP_UGT:
4467 if (Pred == ICmpInst::ICMP_ULT) {
4468 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004469 FoundPred = ICmpInst::ICMP_ULT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004470 break;
4471 }
4472 return false;
4473 case ICmpInst::ICMP_SGT:
4474 if (Pred == ICmpInst::ICMP_SLT) {
4475 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004476 FoundPred = ICmpInst::ICMP_SLT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004477 break;
4478 }
4479 return false;
4480 case ICmpInst::ICMP_NE:
4481 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4482 // so check for this case by checking if the NE is comparing against
4483 // a minimum or maximum constant.
4484 if (!ICmpInst::isTrueWhenEqual(Pred))
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004485 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4486 const APInt &A = C->getValue()->getValue();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004487 switch (Pred) {
4488 case ICmpInst::ICMP_SLT:
4489 if (A.isMaxSignedValue()) break;
4490 return false;
4491 case ICmpInst::ICMP_SGT:
4492 if (A.isMinSignedValue()) break;
4493 return false;
4494 case ICmpInst::ICMP_ULT:
4495 if (A.isMaxValue()) break;
4496 return false;
4497 case ICmpInst::ICMP_UGT:
4498 if (A.isMinValue()) break;
4499 return false;
4500 default:
4501 return false;
4502 }
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004503 FoundPred = Pred;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004504 // NE is symmetric but the original comparison may not be. Swap
4505 // the operands if necessary so that they match below.
4506 if (isa<SCEVConstant>(LHS))
4507 std::swap(PreCondLHS, PreCondRHS);
4508 break;
4509 }
4510 return false;
4511 default:
4512 // We weren't able to reconcile the condition.
4513 return false;
4514 }
4515
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004516 assert(Pred == FoundPred && "Conditions were not reconciled!");
Dan Gohman423ed6c2009-06-24 01:18:18 +00004517
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004518 // Bail if the ICmp's operands' types are wider than the needed type
4519 // before attempting to call getSCEV on them. This avoids infinite
4520 // recursion, since the analysis of widening casts can require loop
4521 // exit condition information for overflow checking, which would
4522 // lead back here.
4523 if (getTypeSizeInBits(LHS->getType()) <
4524 getTypeSizeInBits(PreCondLHS->getType()))
4525 return false;
4526
4527 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4528 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4529
4530 // Balance the types. The case where FoundLHS' type is wider than
4531 // LHS' type is checked for above.
4532 if (getTypeSizeInBits(LHS->getType()) >
4533 getTypeSizeInBits(FoundLHS->getType())) {
4534 if (CmpInst::isSigned(Pred)) {
4535 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4536 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4537 } else {
4538 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4539 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4540 }
4541 }
4542
4543 return isNecessaryCondOperands(Pred, LHS, RHS,
4544 FoundLHS, FoundRHS) ||
4545 // ~x < ~y --> x > y
4546 isNecessaryCondOperands(Pred, LHS, RHS,
4547 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4548}
4549
4550/// isNecessaryCondOperands - Test whether the condition described by Pred,
4551/// LHS, and RHS is a necessary condition for the condition described by
4552/// Pred, FoundLHS, and FoundRHS to evaluate to true.
4553bool
4554ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4555 const SCEV *LHS, const SCEV *RHS,
4556 const SCEV *FoundLHS,
4557 const SCEV *FoundRHS) {
4558 switch (Pred) {
4559 default: break;
4560 case ICmpInst::ICMP_SLT:
4561 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4562 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4563 return true;
4564 break;
4565 case ICmpInst::ICMP_SGT:
4566 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4567 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4568 return true;
4569 break;
4570 case ICmpInst::ICMP_ULT:
4571 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4572 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4573 return true;
4574 break;
4575 case ICmpInst::ICMP_UGT:
4576 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4577 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4578 return true;
4579 break;
4580 }
4581
4582 return false;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004583}
4584
Dan Gohmand2b62c42009-06-21 23:46:38 +00004585/// getBECount - Subtract the end and start values and divide by the step,
4586/// rounding up, to get the number of times the backedge is executed. Return
4587/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman161ea032009-07-07 17:06:11 +00004588const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohman69eacc72009-07-13 22:05:32 +00004589 const SCEV *End,
4590 const SCEV *Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004591 const Type *Ty = Start->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00004592 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4593 const SCEV *Diff = getMinusSCEV(End, Start);
4594 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004595
4596 // Add an adjustment to the difference between End and Start so that
4597 // the division will effectively round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004598 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004599
4600 // Check Add for unsigned overflow.
4601 // TODO: More sophisticated things could be done here.
Owen Andersone755b092009-07-06 22:37:39 +00004602 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004603 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4604 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4605 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004606 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004607 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004608
4609 return getUDivExpr(Add, Step);
4610}
4611
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004612/// HowManyLessThans - Return the number of times a backedge containing the
4613/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004614/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004615ScalarEvolution::BackedgeTakenInfo
4616ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4617 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004618 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004619 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004620
Dan Gohmanbff6b582009-05-04 22:30:44 +00004621 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004622 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004623 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004624
4625 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004626 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004627 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004628 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004629
4630 // TODO: handle non-constant strides.
4631 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4632 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004633 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004634 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004635 // With unit stride, the iteration never steps past the limit value.
4636 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4637 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4638 // Test whether a positive iteration iteration can step past the limit
4639 // value and past the maximum value for its type in a single step.
4640 if (isSigned) {
4641 APInt Max = APInt::getSignedMaxValue(BitWidth);
4642 if ((Max - CStep->getValue()->getValue())
4643 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004644 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004645 } else {
4646 APInt Max = APInt::getMaxValue(BitWidth);
4647 if ((Max - CStep->getValue()->getValue())
4648 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004649 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004650 }
4651 } else
4652 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004653 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004654 } else
4655 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004656 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004657
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004658 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4659 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4660 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004661 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004663 // First, we get the value of the LHS in the first iteration: n
Dan Gohman161ea032009-07-07 17:06:11 +00004664 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004665
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004666 // Determine the minimum constant start value.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004667 const SCEV *MinStart = getConstant(isSigned ?
4668 getSignedRange(Start).getSignedMin() :
4669 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004670
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004671 // If we know that the condition is true in order to enter the loop,
4672 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004673 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4674 // the division must round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004675 const SCEV *End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004676 if (!isLoopGuardedByCond(L,
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004677 isSigned ? ICmpInst::ICMP_SLT :
4678 ICmpInst::ICMP_ULT,
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004679 getMinusSCEV(Start, Step), RHS))
4680 End = isSigned ? getSMaxExpr(RHS, Start)
4681 : getUMaxExpr(RHS, Start);
4682
4683 // Determine the maximum constant end value.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004684 const SCEV *MaxEnd = getConstant(isSigned ?
4685 getSignedRange(End).getSignedMax() :
4686 getUnsignedRange(End).getUnsignedMax());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004687
4688 // Finally, we subtract these two values and divide, rounding up, to get
4689 // the number of times the backedge is executed.
Dan Gohman161ea032009-07-07 17:06:11 +00004690 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004691
4692 // The maximum backedge count is similar, except using the minimum start
4693 // value and the maximum end value.
Dan Gohman161ea032009-07-07 17:06:11 +00004694 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004695
4696 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004697 }
4698
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004699 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004700}
4701
4702/// getNumIterationsInRange - Return the number of iterations of this loop that
4703/// produce values in the specified constant range. Another way of looking at
4704/// this is that it returns the first iteration number where the value is not in
4705/// the condition, thus computing the exit count. If the iteration count can't
4706/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00004707const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004708 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004709 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004710 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004711
4712 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004713 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004714 if (!SC->getValue()->isZero()) {
Dan Gohman161ea032009-07-07 17:06:11 +00004715 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004716 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004717 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004718 if (const SCEVAddRecExpr *ShiftedAddRec =
4719 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004720 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004721 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004722 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004723 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004724 }
4725
4726 // The only time we can solve this is when we have all constant indices.
4727 // Otherwise, we cannot determine the overflow conditions.
4728 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4729 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004730 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004731
4732
4733 // Okay at this point we know that all elements of the chrec are constants and
4734 // that the start element is zero.
4735
4736 // First check to see if the range contains zero. If not, the first
4737 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004738 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004739 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004740 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004741
4742 if (isAffine()) {
4743 // If this is an affine expression then we have this situation:
4744 // Solve {0,+,A} in Range === Ax in Range
4745
4746 // We know that zero is in the range. If A is positive then we know that
4747 // the upper value of the range must be the first possible exit value.
4748 // If A is negative then the lower of the range is the last possible loop
4749 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004750 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4752 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4753
4754 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004755 APInt ExitVal = (End + A).udiv(A);
Owen Andersone755b092009-07-06 22:37:39 +00004756 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004757
4758 // Evaluate at the exit value. If we really did fall out of the valid
4759 // range, then we computed our trip count, otherwise wrap around or other
4760 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004761 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004762 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004763 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004764
4765 // Ensure that the previous value is in the range. This is a sanity check.
4766 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004767 EvaluateConstantChrecAtConstant(this,
Owen Andersone755b092009-07-06 22:37:39 +00004768 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004769 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004770 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004771 } else if (isQuadratic()) {
4772 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4773 // quadratic equation to solve it. To do this, we must frame our problem in
4774 // terms of figuring out when zero is crossed, instead of when
4775 // Range.getUpper() is crossed.
Dan Gohman161ea032009-07-07 17:06:11 +00004776 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004777 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman161ea032009-07-07 17:06:11 +00004778 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004779
4780 // Next, solve the constructed addrec
Dan Gohman161ea032009-07-07 17:06:11 +00004781 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004782 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004783 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4784 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004785 if (R1) {
4786 // Pick the smallest positive root value.
4787 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004788 dyn_cast<ConstantInt>(
4789 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4790 R1->getValue(), R2->getValue()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791 if (CB->getZExtValue() == false)
4792 std::swap(R1, R2); // R1 is the minimum root now.
4793
4794 // Make sure the root is not off by one. The returned iteration should
4795 // not be in the range, but the previous one should be. When solving
4796 // for "X*X < 5", for example, we should not return a root of 2.
4797 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004798 R1->getValue(),
4799 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004800 if (Range.contains(R1Val->getValue())) {
4801 // The next iteration must be out of the range...
Owen Andersone755b092009-07-06 22:37:39 +00004802 ConstantInt *NextVal =
4803 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004804
Dan Gohman89f85052007-10-22 18:31:58 +00004805 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004806 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004807 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004808 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004809 }
4810
4811 // If R1 was not in the range, then it is a good return value. Make
4812 // sure that R1-1 WAS in the range though, just in case.
Owen Andersone755b092009-07-06 22:37:39 +00004813 ConstantInt *NextVal =
4814 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004815 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004816 if (Range.contains(R1Val->getValue()))
4817 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004818 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004819 }
4820 }
4821 }
4822
Dan Gohman0ad08b02009-04-18 17:58:19 +00004823 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004824}
4825
4826
4827
4828//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004829// SCEVCallbackVH Class Implementation
4830//===----------------------------------------------------------------------===//
4831
Dan Gohman999d14e2009-05-19 19:22:47 +00004832void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman31b69c12009-07-13 22:20:53 +00004833 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004834 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4835 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004836 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4837 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004838 SE->Scalars.erase(getValPtr());
4839 // this now dangles!
4840}
4841
Dan Gohman999d14e2009-05-19 19:22:47 +00004842void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman31b69c12009-07-13 22:20:53 +00004843 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004844
4845 // Forget all the expressions associated with users of the old value,
4846 // so that future queries will recompute the expressions using the new
4847 // value.
4848 SmallVector<User *, 16> Worklist;
Dan Gohman6b9da312009-07-14 14:34:04 +00004849 SmallPtrSet<User *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00004850 Value *Old = getValPtr();
4851 bool DeleteOld = false;
4852 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4853 UI != UE; ++UI)
4854 Worklist.push_back(*UI);
4855 while (!Worklist.empty()) {
4856 User *U = Worklist.pop_back_val();
4857 // Deleting the Old value will cause this to dangle. Postpone
4858 // that until everything else is done.
4859 if (U == Old) {
4860 DeleteOld = true;
4861 continue;
4862 }
Dan Gohman6b9da312009-07-14 14:34:04 +00004863 if (!Visited.insert(U))
4864 continue;
Dan Gohmanbff6b582009-05-04 22:30:44 +00004865 if (PHINode *PN = dyn_cast<PHINode>(U))
4866 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004867 if (Instruction *I = dyn_cast<Instruction>(U))
4868 SE->ValuesAtScopes.erase(I);
Dan Gohman6b9da312009-07-14 14:34:04 +00004869 SE->Scalars.erase(U);
4870 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4871 UI != UE; ++UI)
4872 Worklist.push_back(*UI);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004873 }
Dan Gohman6b9da312009-07-14 14:34:04 +00004874 // Delete the Old value if it (indirectly) references itself.
Dan Gohmanbff6b582009-05-04 22:30:44 +00004875 if (DeleteOld) {
4876 if (PHINode *PN = dyn_cast<PHINode>(Old))
4877 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004878 if (Instruction *I = dyn_cast<Instruction>(Old))
4879 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004880 SE->Scalars.erase(Old);
4881 // this now dangles!
4882 }
4883 // this may dangle!
4884}
4885
Dan Gohman999d14e2009-05-19 19:22:47 +00004886ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004887 : CallbackVH(V), SE(se) {}
4888
4889//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004890// ScalarEvolution Class Implementation
4891//===----------------------------------------------------------------------===//
4892
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004893ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004894 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004895}
4896
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004897bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004898 this->F = &F;
4899 LI = &getAnalysis<LoopInfo>();
4900 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004901 return false;
4902}
4903
4904void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004905 Scalars.clear();
4906 BackedgeTakenCounts.clear();
4907 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004908 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004909 UniqueSCEVs.clear();
4910 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004911}
4912
4913void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4914 AU.setPreservesAll();
4915 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004916}
4917
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004918bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004919 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004920}
4921
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004922static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004923 const Loop *L) {
4924 // Print all inner loops first
4925 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4926 PrintLoopInfo(OS, SE, *I);
4927
Nick Lewyckye5da1912008-01-02 02:49:20 +00004928 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004929
Devang Patel02451fa2007-08-21 00:31:24 +00004930 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004931 L->getExitBlocks(ExitBlocks);
4932 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004933 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004934
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004935 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4936 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004937 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004938 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004939 }
4940
Nick Lewyckye5da1912008-01-02 02:49:20 +00004941 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004942 OS << "Loop " << L->getHeader()->getName() << ": ";
4943
4944 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4945 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4946 } else {
4947 OS << "Unpredictable max backedge-taken count. ";
4948 }
4949
4950 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004951}
4952
Dan Gohman13058cc2009-04-21 00:47:46 +00004953void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004954 // ScalarEvolution's implementaiton of the print method is to print
4955 // out SCEV values of all instructions that are interesting. Doing
4956 // this potentially causes it to create new SCEV objects though,
4957 // which technically conflicts with the const qualifier. This isn't
Dan Gohmanac2a9d62009-07-10 20:25:29 +00004958 // observable from outside the class though, so casting away the
4959 // const isn't dangerous.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004960 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004961
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004962 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004963 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004964 if (isSCEVable(I->getType())) {
Dan Gohman12668ad2009-07-13 23:03:05 +00004965 OS << *I << '\n';
Dan Gohmanabe991f2008-09-14 17:21:12 +00004966 OS << " --> ";
Dan Gohman161ea032009-07-07 17:06:11 +00004967 const SCEV *SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004968 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004969
Dan Gohman8db598a2009-06-19 17:49:54 +00004970 const Loop *L = LI->getLoopFor((*I).getParent());
4971
Dan Gohman161ea032009-07-07 17:06:11 +00004972 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004973 if (AtUse != SV) {
4974 OS << " --> ";
4975 AtUse->print(OS);
4976 }
4977
4978 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004979 OS << "\t\t" "Exits: ";
Dan Gohman161ea032009-07-07 17:06:11 +00004980 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004981 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004982 OS << "<<Unknown>>";
4983 } else {
4984 OS << *ExitValue;
4985 }
4986 }
4987
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004988 OS << "\n";
4989 }
4990
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004991 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4992 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4993 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004994}
Dan Gohman13058cc2009-04-21 00:47:46 +00004995
4996void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4997 raw_os_ostream OS(o);
4998 print(OS, M);
4999}