blob: 86a7613175885f3e6267ce133348b114319d138f [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() :
148 SCEV(scCouldNotCompute) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000150void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
Edwin Török675d5622009-07-11 20:10:48 +0000151 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000152}
153
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Edwin Török675d5622009-07-11 20:10:48 +0000155 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 return false;
157}
158
159const Type *SCEVCouldNotCompute::getType() const {
Edwin Török675d5622009-07-11 20:10:48 +0000160 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 return 0;
162}
163
164bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Edwin Török675d5622009-07-11 20:10:48 +0000165 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 return false;
167}
168
Dan Gohman9bc642f2009-06-24 04:48:43 +0000169const SCEV *
170SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
171 const SCEV *Sym,
172 const SCEV *Conc,
173 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 return this;
175}
176
Dan Gohman13058cc2009-04-21 00:47:46 +0000177void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 OS << "***COULDNOTCOMPUTE***";
179}
180
181bool SCEVCouldNotCompute::classof(const SCEV *S) {
182 return S->getSCEVType() == scCouldNotCompute;
183}
184
Dan Gohman161ea032009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000186 FoldingSetNodeID ID;
187 ID.AddInteger(scConstant);
188 ID.AddPointer(V);
189 void *IP = 0;
190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
191 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
192 new (S) SCEVConstant(V);
193 UniqueSCEVs.InsertNode(S, IP);
194 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195}
196
Dan Gohman161ea032009-07-07 17:06:11 +0000197const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000198 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199}
200
Dan Gohman161ea032009-07-07 17:06:11 +0000201const SCEV *
Dan Gohman8fd520a2009-06-15 22:12:54 +0000202ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
203 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
204}
205
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000206void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
207 ID.AddInteger(scConstant);
208 ID.AddPointer(V);
209}
210
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211const Type *SCEVConstant::getType() const { return V->getType(); }
212
Dan Gohman13058cc2009-04-21 00:47:46 +0000213void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 WriteAsOperand(OS, V, false);
215}
216
Dan Gohman2a381532009-04-21 01:25:57 +0000217SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Dan Gohman161ea032009-07-07 17:06:11 +0000218 const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000219 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman2a381532009-04-21 01:25:57 +0000220
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000221void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
222 ID.AddInteger(getSCEVType());
223 ID.AddPointer(Op);
224 ID.AddPointer(Ty);
225}
226
Dan Gohman2a381532009-04-21 01:25:57 +0000227bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
228 return Op->dominates(BB, DT);
229}
230
Dan Gohman161ea032009-07-07 17:06:11 +0000231SCEVTruncateExpr::SCEVTruncateExpr(const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000232 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
Dan Gohman13058cc2009-04-21 00:47:46 +0000238void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000239 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240}
241
Dan Gohman161ea032009-07-07 17:06:11 +0000242SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000243 : SCEVCastExpr(scZeroExtend, 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 zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247}
248
Dan Gohman13058cc2009-04-21 00:47:46 +0000249void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000250 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251}
252
Dan Gohman161ea032009-07-07 17:06:11 +0000253SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000254 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000255 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
256 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258}
259
Dan Gohman13058cc2009-04-21 00:47:46 +0000260void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262}
263
Dan Gohman13058cc2009-04-21 00:47:46 +0000264void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
266 const char *OpStr = getOperationStr();
267 OS << "(" << *Operands[0];
268 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
269 OS << OpStr << *Operands[i];
270 OS << ")";
271}
272
Dan Gohman9bc642f2009-06-24 04:48:43 +0000273const SCEV *
274SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
275 const SCEV *Sym,
276 const SCEV *Conc,
277 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000279 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000280 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000282 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 NewOps.reserve(getNumOperands());
284 for (unsigned j = 0; j != i; ++j)
285 NewOps.push_back(getOperand(j));
286 NewOps.push_back(H);
287 for (++i; i != e; ++i)
288 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000289 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290
291 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000292 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000294 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000295 else if (isa<SCEVSMaxExpr>(this))
296 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000297 else if (isa<SCEVUMaxExpr>(this))
298 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 else
Edwin Török675d5622009-07-11 20:10:48 +0000300 LLVM_UNREACHABLE("Unknown commutative expr!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 }
302 }
303 return this;
304}
305
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000306void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
307 ID.AddInteger(getSCEVType());
308 ID.AddInteger(Operands.size());
309 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
310 ID.AddPointer(Operands[i]);
311}
312
Dan Gohman72a8a022009-05-07 14:00:19 +0000313bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000314 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
315 if (!getOperand(i)->dominates(BB, DT))
316 return false;
317 }
318 return true;
319}
320
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000321void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
322 ID.AddInteger(scUDivExpr);
323 ID.AddPointer(LHS);
324 ID.AddPointer(RHS);
325}
326
Evan Cheng98c073b2009-02-17 00:13:06 +0000327bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
328 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
329}
330
Dan Gohman13058cc2009-04-21 00:47:46 +0000331void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000332 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333}
334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000336 // In most cases the types of LHS and RHS will be the same, but in some
337 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
338 // depend on the type for correctness, but handling types carefully can
339 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
340 // a pointer type than the RHS, so use the RHS' type here.
341 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342}
343
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000344void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
345 ID.AddInteger(scAddRecExpr);
346 ID.AddInteger(Operands.size());
347 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
348 ID.AddPointer(Operands[i]);
349 ID.AddPointer(L);
350}
351
Dan Gohman9bc642f2009-06-24 04:48:43 +0000352const SCEV *
353SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
354 const SCEV *Conc,
355 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000357 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000358 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000360 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 NewOps.reserve(getNumOperands());
362 for (unsigned j = 0; j != i; ++j)
363 NewOps.push_back(getOperand(j));
364 NewOps.push_back(H);
365 for (++i; i != e; ++i)
366 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000367 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368
Dan Gohman89f85052007-10-22 18:31:58 +0000369 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 }
371 }
372 return this;
373}
374
375
376bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000377 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000378 if (!QueryLoop)
379 return false;
380
381 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
382 if (QueryLoop->contains(L->getHeader()))
383 return false;
384
385 // This recurrence is variant w.r.t. QueryLoop if any of its operands
386 // are variant.
387 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
388 if (!getOperand(i)->isLoopInvariant(QueryLoop))
389 return false;
390
391 // Otherwise it's loop-invariant.
392 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393}
394
Dan Gohman13058cc2009-04-21 00:47:46 +0000395void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 OS << "{" << *Operands[0];
397 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
398 OS << ",+," << *Operands[i];
399 OS << "}<" << L->getHeader()->getName() + ">";
400}
401
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000402void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
403 ID.AddInteger(scUnknown);
404 ID.AddPointer(V);
405}
406
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000410 // Instructions are never considered invariant in the function body
411 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000413 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return true;
415}
416
Evan Cheng98c073b2009-02-17 00:13:06 +0000417bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
418 if (Instruction *I = dyn_cast<Instruction>(getValue()))
419 return DT->dominates(I->getParent(), BB);
420 return true;
421}
422
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423const Type *SCEVUnknown::getType() const {
424 return V->getType();
425}
426
Dan Gohman13058cc2009-04-21 00:47:46 +0000427void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 WriteAsOperand(OS, V, false);
429}
430
431//===----------------------------------------------------------------------===//
432// SCEV Utilities
433//===----------------------------------------------------------------------===//
434
435namespace {
436 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
437 /// than the complexity of the RHS. This comparator is used to canonicalize
438 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000439 class VISIBILITY_HIDDEN SCEVComplexityCompare {
440 LoopInfo *LI;
441 public:
442 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
443
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000444 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000445 // Primarily, sort the SCEVs by their getSCEVType().
446 if (LHS->getSCEVType() != RHS->getSCEVType())
447 return LHS->getSCEVType() < RHS->getSCEVType();
448
449 // Aside from the getSCEVType() ordering, the particular ordering
450 // isn't very important except that it's beneficial to be consistent,
451 // so that (a + b) and (b + a) don't end up as different expressions.
452
453 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
454 // not as complete as it could be.
455 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
456 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
457
Dan Gohmand0c01232009-05-19 02:15:55 +0000458 // Order pointer values after integer values. This helps SCEVExpander
459 // form GEPs.
460 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
461 return false;
462 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
463 return true;
464
Dan Gohman5d486452009-05-07 14:39:04 +0000465 // Compare getValueID values.
466 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
467 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
468
469 // Sort arguments by their position.
470 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
471 const Argument *RA = cast<Argument>(RU->getValue());
472 return LA->getArgNo() < RA->getArgNo();
473 }
474
475 // For instructions, compare their loop depth, and their opcode.
476 // This is pretty loose.
477 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
478 Instruction *RV = cast<Instruction>(RU->getValue());
479
480 // Compare loop depths.
481 if (LI->getLoopDepth(LV->getParent()) !=
482 LI->getLoopDepth(RV->getParent()))
483 return LI->getLoopDepth(LV->getParent()) <
484 LI->getLoopDepth(RV->getParent());
485
486 // Compare opcodes.
487 if (LV->getOpcode() != RV->getOpcode())
488 return LV->getOpcode() < RV->getOpcode();
489
490 // Compare the number of operands.
491 if (LV->getNumOperands() != RV->getNumOperands())
492 return LV->getNumOperands() < RV->getNumOperands();
493 }
494
495 return false;
496 }
497
Dan Gohman56fc8f12009-06-14 22:51:25 +0000498 // Compare constant values.
499 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
500 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewycky9bb14052009-07-04 17:24:52 +0000501 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
502 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman56fc8f12009-06-14 22:51:25 +0000503 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
504 }
505
506 // Compare addrec loop depths.
507 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
508 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
509 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
510 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
511 }
Dan Gohman5d486452009-05-07 14:39:04 +0000512
513 // Lexicographically compare n-ary expressions.
514 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
515 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
516 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
517 if (i >= RC->getNumOperands())
518 return false;
519 if (operator()(LC->getOperand(i), RC->getOperand(i)))
520 return true;
521 if (operator()(RC->getOperand(i), LC->getOperand(i)))
522 return false;
523 }
524 return LC->getNumOperands() < RC->getNumOperands();
525 }
526
Dan Gohman6e10db12009-05-07 19:23:21 +0000527 // Lexicographically compare udiv expressions.
528 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
529 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
530 if (operator()(LC->getLHS(), RC->getLHS()))
531 return true;
532 if (operator()(RC->getLHS(), LC->getLHS()))
533 return false;
534 if (operator()(LC->getRHS(), RC->getRHS()))
535 return true;
536 if (operator()(RC->getRHS(), LC->getRHS()))
537 return false;
538 return false;
539 }
540
Dan Gohman5d486452009-05-07 14:39:04 +0000541 // Compare cast expressions by operand.
542 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
543 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
544 return operator()(LC->getOperand(), RC->getOperand());
545 }
546
Edwin Török675d5622009-07-11 20:10:48 +0000547 LLVM_UNREACHABLE("Unknown SCEV kind!");
Dan Gohman5d486452009-05-07 14:39:04 +0000548 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 }
550 };
551}
552
553/// GroupByComplexity - Given a list of SCEV objects, order them by their
554/// complexity, and group objects of the same complexity together by value.
555/// When this routine is finished, we know that any duplicates in the vector are
556/// consecutive and that complexity is monotonically increasing.
557///
558/// Note that we go take special precautions to ensure that we get determinstic
559/// results from this routine. In other words, we don't want the results of
560/// this to depend on where the addresses of various SCEV objects happened to
561/// land in memory.
562///
Dan Gohman161ea032009-07-07 17:06:11 +0000563static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000564 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 if (Ops.size() < 2) return; // Noop
566 if (Ops.size() == 2) {
567 // This is the common case, which also happens to be trivially simple.
568 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000569 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 std::swap(Ops[0], Ops[1]);
571 return;
572 }
573
574 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000575 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576
577 // Now that we are sorted by complexity, group elements of the same
578 // complexity. Note that this is, at worst, N^2, but the vector is likely to
579 // be extremely short in practice. Note that we take this approach because we
580 // do not want to depend on the addresses of the objects we are grouping.
581 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000582 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 unsigned Complexity = S->getSCEVType();
584
585 // If there are any objects of the same complexity and same value as this
586 // one, group them.
587 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
588 if (Ops[j] == S) { // Found a duplicate.
589 // Move it to immediately after i'th element.
590 std::swap(Ops[i+1], Ops[j]);
591 ++i; // no need to rescan it.
592 if (i == e-2) return; // Done!
593 }
594 }
595 }
596}
597
598
599
600//===----------------------------------------------------------------------===//
601// Simple SCEV method implementations
602//===----------------------------------------------------------------------===//
603
Eli Friedman7489ec92008-08-04 23:49:06 +0000604/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000605/// Assume, K > 0.
Dan Gohman161ea032009-07-07 17:06:11 +0000606static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000607 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000608 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000609 // Handle the simplest case efficiently.
610 if (K == 1)
611 return SE.getTruncateOrZeroExtend(It, ResultTy);
612
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000613 // We are using the following formula for BC(It, K):
614 //
615 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
616 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000617 // Suppose, W is the bitwidth of the return value. We must be prepared for
618 // overflow. Hence, we must assure that the result of our computation is
619 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
620 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000621 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000622 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000623 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000624 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
625 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000627 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000628 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000629 // This formula is trivially equivalent to the previous formula. However,
630 // this formula can be implemented much more efficiently. The trick is that
631 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
632 // arithmetic. To do exact division in modular arithmetic, all we have
633 // to do is multiply by the inverse. Therefore, this step can be done at
634 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000635 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000636 // The next issue is how to safely do the division by 2^T. The way this
637 // is done is by doing the multiplication step at a width of at least W + T
638 // bits. This way, the bottom W+T bits of the product are accurate. Then,
639 // when we perform the division by 2^T (which is equivalent to a right shift
640 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
641 // truncated out after the division by 2^T.
642 //
643 // In comparison to just directly using the first formula, this technique
644 // is much more efficient; using the first formula requires W * K bits,
645 // but this formula less than W + K bits. Also, the first formula requires
646 // a division step, whereas this formula only requires multiplies and shifts.
647 //
648 // It doesn't matter whether the subtraction step is done in the calculation
649 // width or the input iteration count's width; if the subtraction overflows,
650 // the result must be zero anyway. We prefer here to do it in the width of
651 // the induction variable because it helps a lot for certain cases; CodeGen
652 // isn't smart enough to ignore the overflow, which leads to much less
653 // efficient code if the width of the subtraction is wider than the native
654 // register width.
655 //
656 // (It's possible to not widen at all by pulling out factors of 2 before
657 // the multiplication; for example, K=2 can be calculated as
658 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
659 // extra arithmetic, so it's not an obvious win, and it gets
660 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000661
Eli Friedman7489ec92008-08-04 23:49:06 +0000662 // Protection from insane SCEVs; this bound is conservative,
663 // but it probably doesn't matter.
664 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000665 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000666
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000667 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000668
Eli Friedman7489ec92008-08-04 23:49:06 +0000669 // Calculate K! / 2^T and T; we divide out the factors of two before
670 // multiplying for calculating K! / 2^T to avoid overflow.
671 // Other overflow doesn't matter because we only care about the bottom
672 // W bits of the result.
673 APInt OddFactorial(W, 1);
674 unsigned T = 1;
675 for (unsigned i = 3; i <= K; ++i) {
676 APInt Mult(W, i);
677 unsigned TwoFactors = Mult.countTrailingZeros();
678 T += TwoFactors;
679 Mult = Mult.lshr(TwoFactors);
680 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000682
Eli Friedman7489ec92008-08-04 23:49:06 +0000683 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000684 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000685
686 // Calcuate 2^T, at width T+W.
687 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
688
689 // Calculate the multiplicative inverse of K! / 2^T;
690 // this multiplication factor will perform the exact division by
691 // K! / 2^T.
692 APInt Mod = APInt::getSignedMinValue(W+1);
693 APInt MultiplyFactor = OddFactorial.zext(W+1);
694 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
695 MultiplyFactor = MultiplyFactor.trunc(W);
696
697 // Calculate the product, at width T+W
698 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman161ea032009-07-07 17:06:11 +0000699 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000700 for (unsigned i = 1; i != K; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000701 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000702 Dividend = SE.getMulExpr(Dividend,
703 SE.getTruncateOrZeroExtend(S, CalculationTy));
704 }
705
706 // Divide by 2^T
Dan Gohman161ea032009-07-07 17:06:11 +0000707 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000708
709 // Truncate the result, and divide by K! / 2^T.
710
711 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
712 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713}
714
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715/// evaluateAtIteration - Return the value of this chain of recurrences at
716/// the specified iteration number. We can evaluate this recurrence by
717/// multiplying each element in the chain by the binomial coefficient
718/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
719///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000720/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000722/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723///
Dan Gohman161ea032009-07-07 17:06:11 +0000724const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman89f85052007-10-22 18:31:58 +0000725 ScalarEvolution &SE) const {
Dan Gohman161ea032009-07-07 17:06:11 +0000726 const SCEV *Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000728 // The computation is correct in the face of overflow provided that the
729 // multiplication is performed _after_ the evaluation of the binomial
730 // coefficient.
Dan Gohman161ea032009-07-07 17:06:11 +0000731 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000732 if (isa<SCEVCouldNotCompute>(Coeff))
733 return Coeff;
734
735 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 }
737 return Result;
738}
739
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740//===----------------------------------------------------------------------===//
741// SCEV Expression folder implementations
742//===----------------------------------------------------------------------===//
743
Dan Gohman161ea032009-07-07 17:06:11 +0000744const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000745 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000746 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000747 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000748 assert(isSCEVable(Ty) &&
749 "This is not a conversion to a SCEVable type!");
750 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000751
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000752 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000753 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000754 return getConstant(
755 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756
Dan Gohman1a5c4992009-04-22 16:20:48 +0000757 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000758 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000759 return getTruncateExpr(ST->getOperand(), Ty);
760
Nick Lewycky37d04642009-04-23 05:15:08 +0000761 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000762 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000763 return getTruncateOrSignExtend(SS->getOperand(), Ty);
764
765 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000766 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000767 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
768
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000769 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000770 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000771 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000773 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
774 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 }
776
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000777 FoldingSetNodeID ID;
778 ID.AddInteger(scTruncate);
779 ID.AddPointer(Op);
780 ID.AddPointer(Ty);
781 void *IP = 0;
782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
783 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
784 new (S) SCEVTruncateExpr(Op, Ty);
785 UniqueSCEVs.InsertNode(S, IP);
786 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787}
788
Dan Gohman161ea032009-07-07 17:06:11 +0000789const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000790 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000791 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000792 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000793 assert(isSCEVable(Ty) &&
794 "This is not a conversion to a SCEVable type!");
795 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000796
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000797 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000798 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000799 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000800 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
801 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000802 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000803 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804
Dan Gohman1a5c4992009-04-22 16:20:48 +0000805 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000806 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000807 return getZeroExtendExpr(SZ->getOperand(), Ty);
808
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000813 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000814 if (AR->isAffine()) {
Dan Gohman232756f2009-07-10 16:42:52 +0000815 const SCEV *Start = AR->getStart();
816 const SCEV *Step = AR->getStepRecurrence(*this);
817 unsigned BitWidth = getTypeSizeInBits(AR->getType());
818 const Loop *L = AR->getLoop();
819
Dan Gohmana9dba962009-04-27 20:16:15 +0000820 // Check whether the backedge-taken count is SCEVCouldNotCompute.
821 // Note that this serves two purposes: It filters out loops that are
822 // simply not analyzable, and it covers the case where this code is
823 // being called from within backedge-taken count analysis, such that
824 // attempting to ask for the backedge-taken count would likely result
825 // in infinite recursion. In the later case, the analysis code will
826 // cope with a conservative value, and it will take care to purge
827 // that value once it has finished.
Dan Gohman232756f2009-07-10 16:42:52 +0000828 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000829 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000830 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000831 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000832
833 // Check whether the backedge-taken count can be losslessly casted to
834 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000835 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000836 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000837 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000838 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
839 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman232756f2009-07-10 16:42:52 +0000840 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000841 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000842 const SCEV *ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000843 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000844 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000845 const SCEV *Add = getAddExpr(Start, ZMul);
846 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000847 getAddExpr(getZeroExtendExpr(Start, WideTy),
848 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
849 getZeroExtendExpr(Step, WideTy)));
850 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000851 // Return the expression with the addrec on the outside.
852 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
853 getZeroExtendExpr(Step, Ty),
Dan Gohman232756f2009-07-10 16:42:52 +0000854 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000855
856 // Similar to above, only this time treat the step value as signed.
857 // This covers loops that count down.
Dan Gohman161ea032009-07-07 17:06:11 +0000858 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000859 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000860 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000861 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000862 OperandExtendedAdd =
863 getAddExpr(getZeroExtendExpr(Start, WideTy),
864 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
865 getSignExtendExpr(Step, WideTy)));
866 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000867 // Return the expression with the addrec on the outside.
868 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
869 getSignExtendExpr(Step, Ty),
Dan Gohman232756f2009-07-10 16:42:52 +0000870 L);
871 }
872
873 // If the backedge is guarded by a comparison with the pre-inc value
874 // the addrec is safe. Also, if the entry is guarded by a comparison
875 // with the start value and the backedge is guarded by a comparison
876 // with the post-inc value, the addrec is safe.
877 if (isKnownPositive(Step)) {
878 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
879 getUnsignedRange(Step).getUnsignedMax());
880 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
881 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
882 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
883 AR->getPostIncExpr(*this), N)))
884 // Return the expression with the addrec on the outside.
885 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
886 getZeroExtendExpr(Step, Ty),
887 L);
888 } else if (isKnownNegative(Step)) {
889 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
890 getSignedRange(Step).getSignedMin());
891 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
892 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
893 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
894 AR->getPostIncExpr(*this), N)))
895 // Return the expression with the addrec on the outside.
896 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
897 getSignExtendExpr(Step, Ty),
898 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000899 }
900 }
901 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000903 FoldingSetNodeID ID;
904 ID.AddInteger(scZeroExtend);
905 ID.AddPointer(Op);
906 ID.AddPointer(Ty);
907 void *IP = 0;
908 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
909 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
910 new (S) SCEVZeroExtendExpr(Op, Ty);
911 UniqueSCEVs.InsertNode(S, IP);
912 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913}
914
Dan Gohman161ea032009-07-07 17:06:11 +0000915const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000916 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000917 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000918 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000919 assert(isSCEVable(Ty) &&
920 "This is not a conversion to a SCEVable type!");
921 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000922
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000923 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000924 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000925 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000926 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
927 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000928 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000929 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930
Dan Gohman1a5c4992009-04-22 16:20:48 +0000931 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000932 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000933 return getSignExtendExpr(SS->getOperand(), Ty);
934
Dan Gohmana9dba962009-04-27 20:16:15 +0000935 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000937 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000939 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000940 if (AR->isAffine()) {
Dan Gohman232756f2009-07-10 16:42:52 +0000941 const SCEV *Start = AR->getStart();
942 const SCEV *Step = AR->getStepRecurrence(*this);
943 unsigned BitWidth = getTypeSizeInBits(AR->getType());
944 const Loop *L = AR->getLoop();
945
Dan Gohmana9dba962009-04-27 20:16:15 +0000946 // Check whether the backedge-taken count is SCEVCouldNotCompute.
947 // Note that this serves two purposes: It filters out loops that are
948 // simply not analyzable, and it covers the case where this code is
949 // being called from within backedge-taken count analysis, such that
950 // attempting to ask for the backedge-taken count would likely result
951 // in infinite recursion. In the later case, the analysis code will
952 // cope with a conservative value, and it will take care to purge
953 // that value once it has finished.
Dan Gohman232756f2009-07-10 16:42:52 +0000954 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000955 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000956 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000957 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000958
959 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000960 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000961 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000962 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000963 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000964 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
965 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman232756f2009-07-10 16:42:52 +0000966 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000967 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000968 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000969 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000970 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000971 const SCEV *Add = getAddExpr(Start, SMul);
972 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000973 getAddExpr(getSignExtendExpr(Start, WideTy),
974 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
975 getSignExtendExpr(Step, WideTy)));
976 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000977 // Return the expression with the addrec on the outside.
978 return getAddRecExpr(getSignExtendExpr(Start, Ty),
979 getSignExtendExpr(Step, Ty),
Dan Gohman232756f2009-07-10 16:42:52 +0000980 L);
981 }
982
983 // If the backedge is guarded by a comparison with the pre-inc value
984 // the addrec is safe. Also, if the entry is guarded by a comparison
985 // with the start value and the backedge is guarded by a comparison
986 // with the post-inc value, the addrec is safe.
987 if (isKnownPositive(Step)) {
988 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
989 getSignedRange(Step).getSignedMax());
990 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
991 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
992 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
993 AR->getPostIncExpr(*this), N)))
994 // Return the expression with the addrec on the outside.
995 return getAddRecExpr(getSignExtendExpr(Start, Ty),
996 getSignExtendExpr(Step, Ty),
997 L);
998 } else if (isKnownNegative(Step)) {
999 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1000 getSignedRange(Step).getSignedMin());
1001 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1002 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1003 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1004 AR->getPostIncExpr(*this), N)))
1005 // Return the expression with the addrec on the outside.
1006 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1007 getSignExtendExpr(Step, Ty),
1008 L);
Dan Gohmana9dba962009-04-27 20:16:15 +00001009 }
1010 }
1011 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001013 FoldingSetNodeID ID;
1014 ID.AddInteger(scSignExtend);
1015 ID.AddPointer(Op);
1016 ID.AddPointer(Ty);
1017 void *IP = 0;
1018 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1019 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1020 new (S) SCEVSignExtendExpr(Op, Ty);
1021 UniqueSCEVs.InsertNode(S, IP);
1022 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023}
1024
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001025/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1026/// unspecified bits out to the given type.
1027///
Dan Gohman161ea032009-07-07 17:06:11 +00001028const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001029 const Type *Ty) {
1030 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1031 "This is not an extending conversion!");
1032 assert(isSCEVable(Ty) &&
1033 "This is not a conversion to a SCEVable type!");
1034 Ty = getEffectiveSCEVType(Ty);
1035
1036 // Sign-extend negative constants.
1037 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1038 if (SC->getValue()->getValue().isNegative())
1039 return getSignExtendExpr(Op, Ty);
1040
1041 // Peel off a truncate cast.
1042 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001043 const SCEV *NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001044 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1045 return getAnyExtendExpr(NewOp, Ty);
1046 return getTruncateOrNoop(NewOp, Ty);
1047 }
1048
1049 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +00001050 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001051 if (!isa<SCEVZeroExtendExpr>(ZExt))
1052 return ZExt;
1053
1054 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +00001055 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001056 if (!isa<SCEVSignExtendExpr>(SExt))
1057 return SExt;
1058
1059 // If the expression is obviously signed, use the sext cast value.
1060 if (isa<SCEVSMaxExpr>(Op))
1061 return SExt;
1062
1063 // Absent any other information, use the zext cast value.
1064 return ZExt;
1065}
1066
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001067/// CollectAddOperandsWithScales - Process the given Ops list, which is
1068/// a list of operands to be added under the given scale, update the given
1069/// map. This is a helper function for getAddRecExpr. As an example of
1070/// what it does, given a sequence of operands that would form an add
1071/// expression like this:
1072///
1073/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1074///
1075/// where A and B are constants, update the map with these values:
1076///
1077/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1078///
1079/// and add 13 + A*B*29 to AccumulatedConstant.
1080/// This will allow getAddRecExpr to produce this:
1081///
1082/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1083///
1084/// This form often exposes folding opportunities that are hidden in
1085/// the original operand list.
1086///
1087/// Return true iff it appears that any interesting folding opportunities
1088/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1089/// the common case where no interesting opportunities are present, and
1090/// is also used as a check to avoid infinite recursion.
1091///
1092static bool
Dan Gohman161ea032009-07-07 17:06:11 +00001093CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1094 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001095 APInt &AccumulatedConstant,
Dan Gohman161ea032009-07-07 17:06:11 +00001096 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001097 const APInt &Scale,
1098 ScalarEvolution &SE) {
1099 bool Interesting = false;
1100
1101 // Iterate over the add operands.
1102 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1103 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1104 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1105 APInt NewScale =
1106 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1107 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1108 // A multiplication of a constant with another add; recurse.
1109 Interesting |=
1110 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1111 cast<SCEVAddExpr>(Mul->getOperand(1))
1112 ->getOperands(),
1113 NewScale, SE);
1114 } else {
1115 // A multiplication of a constant with some other value. Update
1116 // the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001117 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1118 const SCEV *Key = SE.getMulExpr(MulOps);
1119 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001120 M.insert(std::make_pair(Key, NewScale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001121 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001122 NewOps.push_back(Pair.first->first);
1123 } else {
1124 Pair.first->second += NewScale;
1125 // The map already had an entry for this value, which may indicate
1126 // a folding opportunity.
1127 Interesting = true;
1128 }
1129 }
1130 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1131 // Pull a buried constant out to the outside.
1132 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1133 Interesting = true;
1134 AccumulatedConstant += Scale * C->getValue()->getValue();
1135 } else {
1136 // An ordinary operand. Update the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001137 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001138 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001139 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001140 NewOps.push_back(Pair.first->first);
1141 } else {
1142 Pair.first->second += Scale;
1143 // The map already had an entry for this value, which may indicate
1144 // a folding opportunity.
1145 Interesting = true;
1146 }
1147 }
1148 }
1149
1150 return Interesting;
1151}
1152
1153namespace {
1154 struct APIntCompare {
1155 bool operator()(const APInt &LHS, const APInt &RHS) const {
1156 return LHS.ult(RHS);
1157 }
1158 };
1159}
1160
Dan Gohmanc8a29272009-05-24 23:45:28 +00001161/// getAddExpr - Get a canonical add expression, or something simpler if
1162/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001163const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 assert(!Ops.empty() && "Cannot get empty add!");
1165 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001166#ifndef NDEBUG
1167 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1168 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1169 getEffectiveSCEVType(Ops[0]->getType()) &&
1170 "SCEVAddExpr operand types don't match!");
1171#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172
1173 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001174 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175
1176 // If there are any constants, fold them together.
1177 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001178 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 ++Idx;
1180 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001181 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001183 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1184 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001185 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001186 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001187 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 }
1189
1190 // If we are left with a constant zero being added, strip it off.
1191 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1192 Ops.erase(Ops.begin());
1193 --Idx;
1194 }
1195 }
1196
1197 if (Ops.size() == 1) return Ops[0];
1198
1199 // Okay, check to see if the same value occurs in the operand list twice. If
1200 // so, merge them together into an multiply expression. Since we sorted the
1201 // list, these values are required to be adjacent.
1202 const Type *Ty = Ops[0]->getType();
1203 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1204 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1205 // Found a match, merge the two values into a multiply, and add any
1206 // remaining values to the result.
Dan Gohman161ea032009-07-07 17:06:11 +00001207 const SCEV *Two = getIntegerSCEV(2, Ty);
1208 const SCEV *Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 if (Ops.size() == 2)
1210 return Mul;
1211 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1212 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001213 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 }
1215
Dan Gohman45b3b542009-05-08 21:03:19 +00001216 // Check for truncates. If all the operands are truncated from the same
1217 // type, see if factoring out the truncate would permit the result to be
1218 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1219 // if the contents of the resulting outer trunc fold to something simple.
1220 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1221 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1222 const Type *DstType = Trunc->getType();
1223 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00001224 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001225 bool Ok = true;
1226 // Check all the operands to see if they can be represented in the
1227 // source type of the truncate.
1228 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1229 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1230 if (T->getOperand()->getType() != SrcType) {
1231 Ok = false;
1232 break;
1233 }
1234 LargeOps.push_back(T->getOperand());
1235 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1236 // This could be either sign or zero extension, but sign extension
1237 // is much more likely to be foldable here.
1238 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1239 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman161ea032009-07-07 17:06:11 +00001240 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001241 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1242 if (const SCEVTruncateExpr *T =
1243 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1244 if (T->getOperand()->getType() != SrcType) {
1245 Ok = false;
1246 break;
1247 }
1248 LargeMulOps.push_back(T->getOperand());
1249 } else if (const SCEVConstant *C =
1250 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1251 // This could be either sign or zero extension, but sign extension
1252 // is much more likely to be foldable here.
1253 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1254 } else {
1255 Ok = false;
1256 break;
1257 }
1258 }
1259 if (Ok)
1260 LargeOps.push_back(getMulExpr(LargeMulOps));
1261 } else {
1262 Ok = false;
1263 break;
1264 }
1265 }
1266 if (Ok) {
1267 // Evaluate the expression in the larger type.
Dan Gohman161ea032009-07-07 17:06:11 +00001268 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001269 // If it folds to something simple, use it. Otherwise, don't.
1270 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1271 return getTruncateExpr(Fold, DstType);
1272 }
1273 }
1274
1275 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1277 ++Idx;
1278
1279 // If there are add operands they would be next.
1280 if (Idx < Ops.size()) {
1281 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001282 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 // If we have an add, expand the add operands onto the end of the operands
1284 // list.
1285 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1286 Ops.erase(Ops.begin()+Idx);
1287 DeletedAdd = true;
1288 }
1289
1290 // If we deleted at least one add, we added operands to the end of the list,
1291 // and they are not necessarily sorted. Recurse to resort and resimplify
1292 // any operands we just aquired.
1293 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001294 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 }
1296
1297 // Skip over the add expression until we get to a multiply.
1298 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1299 ++Idx;
1300
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001301 // Check to see if there are any folding opportunities present with
1302 // operands multiplied by constant values.
1303 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1304 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00001305 DenseMap<const SCEV *, APInt> M;
1306 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001307 APInt AccumulatedConstant(BitWidth, 0);
1308 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1309 Ops, APInt(BitWidth, 1), *this)) {
1310 // Some interesting folding opportunity is present, so its worthwhile to
1311 // re-generate the operands list. Group the operands by constant scale,
1312 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman161ea032009-07-07 17:06:11 +00001313 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1314 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001315 E = NewOps.end(); I != E; ++I)
1316 MulOpLists[M.find(*I)->second].push_back(*I);
1317 // Re-generate the operands list.
1318 Ops.clear();
1319 if (AccumulatedConstant != 0)
1320 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001321 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1322 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001323 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001324 Ops.push_back(getMulExpr(getConstant(I->first),
1325 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001326 if (Ops.empty())
1327 return getIntegerSCEV(0, Ty);
1328 if (Ops.size() == 1)
1329 return Ops[0];
1330 return getAddExpr(Ops);
1331 }
1332 }
1333
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 // If we are adding something to a multiply expression, make sure the
1335 // something is not already an operand of the multiply. If so, merge it into
1336 // the multiply.
1337 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001338 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001340 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001342 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman161ea032009-07-07 17:06:11 +00001344 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 if (Mul->getNumOperands() != 2) {
1346 // If the multiply has more than two operands, we must get the
1347 // Y*Z term.
Dan Gohman161ea032009-07-07 17:06:11 +00001348 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001350 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 }
Dan Gohman161ea032009-07-07 17:06:11 +00001352 const SCEV *One = getIntegerSCEV(1, Ty);
1353 const SCEV *AddOne = getAddExpr(InnerMul, One);
1354 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 if (Ops.size() == 2) return OuterMul;
1356 if (AddOp < Idx) {
1357 Ops.erase(Ops.begin()+AddOp);
1358 Ops.erase(Ops.begin()+Idx-1);
1359 } else {
1360 Ops.erase(Ops.begin()+Idx);
1361 Ops.erase(Ops.begin()+AddOp-1);
1362 }
1363 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001364 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 }
1366
1367 // Check this multiply against other multiplies being added together.
1368 for (unsigned OtherMulIdx = Idx+1;
1369 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1370 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001371 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 // If MulOp occurs in OtherMul, we can fold the two multiplies
1373 // together.
1374 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1375 OMulOp != e; ++OMulOp)
1376 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1377 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman161ea032009-07-07 17:06:11 +00001378 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001380 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1381 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001383 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 }
Dan Gohman161ea032009-07-07 17:06:11 +00001385 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001387 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1388 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001390 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 }
Dan Gohman161ea032009-07-07 17:06:11 +00001392 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1393 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 if (Ops.size() == 2) return OuterMul;
1395 Ops.erase(Ops.begin()+Idx);
1396 Ops.erase(Ops.begin()+OtherMulIdx-1);
1397 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001398 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001399 }
1400 }
1401 }
1402 }
1403
1404 // If there are any add recurrences in the operands list, see if any other
1405 // added values are loop invariant. If so, we can fold them into the
1406 // recurrence.
1407 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1408 ++Idx;
1409
1410 // Scan over all recurrences, trying to fold loop invariants into them.
1411 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1412 // Scan all of the other operands to this add and add them to the vector if
1413 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001414 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001415 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1417 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1418 LIOps.push_back(Ops[i]);
1419 Ops.erase(Ops.begin()+i);
1420 --i; --e;
1421 }
1422
1423 // If we found some loop invariants, fold them into the recurrence.
1424 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001425 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 LIOps.push_back(AddRec->getStart());
1427
Dan Gohman161ea032009-07-07 17:06:11 +00001428 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001429 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001430 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431
Dan Gohman161ea032009-07-07 17:06:11 +00001432 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 // If all of the other operands were loop invariant, we are done.
1434 if (Ops.size() == 1) return NewRec;
1435
1436 // Otherwise, add the folded AddRec by the non-liv parts.
1437 for (unsigned i = 0;; ++i)
1438 if (Ops[i] == AddRec) {
1439 Ops[i] = NewRec;
1440 break;
1441 }
Dan Gohman89f85052007-10-22 18:31:58 +00001442 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 }
1444
1445 // Okay, if there weren't any loop invariants to be folded, check to see if
1446 // there are multiple AddRec's with the same loop induction variable being
1447 // added together. If so, we can fold them.
1448 for (unsigned OtherIdx = Idx+1;
1449 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1450 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001451 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1453 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001454 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1455 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1457 if (i >= NewOps.size()) {
1458 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1459 OtherAddRec->op_end());
1460 break;
1461 }
Dan Gohman89f85052007-10-22 18:31:58 +00001462 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 }
Dan Gohman161ea032009-07-07 17:06:11 +00001464 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465
1466 if (Ops.size() == 2) return NewAddRec;
1467
1468 Ops.erase(Ops.begin()+Idx);
1469 Ops.erase(Ops.begin()+OtherIdx-1);
1470 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001471 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 }
1473 }
1474
1475 // Otherwise couldn't fold anything into this recurrence. Move onto the
1476 // next one.
1477 }
1478
1479 // Okay, it looks like we really DO need an add expr. Check to see if we
1480 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001481 FoldingSetNodeID ID;
1482 ID.AddInteger(scAddExpr);
1483 ID.AddInteger(Ops.size());
1484 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1485 ID.AddPointer(Ops[i]);
1486 void *IP = 0;
1487 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1488 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1489 new (S) SCEVAddExpr(Ops);
1490 UniqueSCEVs.InsertNode(S, IP);
1491 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492}
1493
1494
Dan Gohmanc8a29272009-05-24 23:45:28 +00001495/// getMulExpr - Get a canonical multiply expression, or something simpler if
1496/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001497const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001498 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001499#ifndef NDEBUG
1500 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1501 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1502 getEffectiveSCEVType(Ops[0]->getType()) &&
1503 "SCEVMulExpr operand types don't match!");
1504#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505
1506 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001507 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508
1509 // If there are any constants, fold them together.
1510 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001511 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
1513 // C1*(C2+V) -> C1*C2 + C1*V
1514 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001515 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 if (Add->getNumOperands() == 2 &&
1517 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001518 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1519 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520
1521
1522 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001523 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001525 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001526 RHSC->getValue()->getValue());
1527 Ops[0] = getConstant(Fold);
1528 Ops.erase(Ops.begin()+1); // Erase the folded element
1529 if (Ops.size() == 1) return Ops[0];
1530 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 }
1532
1533 // If we are left with a constant one being multiplied, strip it off.
1534 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1535 Ops.erase(Ops.begin());
1536 --Idx;
1537 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1538 // If we have a multiply of zero, it will always be zero.
1539 return Ops[0];
1540 }
1541 }
1542
1543 // Skip over the add expression until we get to a multiply.
1544 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1545 ++Idx;
1546
1547 if (Ops.size() == 1)
1548 return Ops[0];
1549
1550 // If there are mul operands inline them all into this expression.
1551 if (Idx < Ops.size()) {
1552 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001553 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 // If we have an mul, expand the mul operands onto the end of the operands
1555 // list.
1556 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1557 Ops.erase(Ops.begin()+Idx);
1558 DeletedMul = true;
1559 }
1560
1561 // If we deleted at least one mul, we added operands to the end of the list,
1562 // and they are not necessarily sorted. Recurse to resort and resimplify
1563 // any operands we just aquired.
1564 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001565 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566 }
1567
1568 // If there are any add recurrences in the operands list, see if any other
1569 // added values are loop invariant. If so, we can fold them into the
1570 // recurrence.
1571 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1572 ++Idx;
1573
1574 // Scan over all recurrences, trying to fold loop invariants into them.
1575 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1576 // Scan all of the other operands to this mul and add them to the vector if
1577 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001578 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001579 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1581 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1582 LIOps.push_back(Ops[i]);
1583 Ops.erase(Ops.begin()+i);
1584 --i; --e;
1585 }
1586
1587 // If we found some loop invariants, fold them into the recurrence.
1588 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001589 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman161ea032009-07-07 17:06:11 +00001590 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 NewOps.reserve(AddRec->getNumOperands());
1592 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001593 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001595 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 } else {
1597 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001598 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001600 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601 }
1602 }
1603
Dan Gohman161ea032009-07-07 17:06:11 +00001604 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605
1606 // If all of the other operands were loop invariant, we are done.
1607 if (Ops.size() == 1) return NewRec;
1608
1609 // Otherwise, multiply the folded AddRec by the non-liv parts.
1610 for (unsigned i = 0;; ++i)
1611 if (Ops[i] == AddRec) {
1612 Ops[i] = NewRec;
1613 break;
1614 }
Dan Gohman89f85052007-10-22 18:31:58 +00001615 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616 }
1617
1618 // Okay, if there weren't any loop invariants to be folded, check to see if
1619 // there are multiple AddRec's with the same loop induction variable being
1620 // multiplied together. If so, we can fold them.
1621 for (unsigned OtherIdx = Idx+1;
1622 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1623 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001624 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1626 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001627 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman161ea032009-07-07 17:06:11 +00001628 const SCEV *NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 G->getStart());
Dan Gohman161ea032009-07-07 17:06:11 +00001630 const SCEV *B = F->getStepRecurrence(*this);
1631 const SCEV *D = G->getStepRecurrence(*this);
1632 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001633 getMulExpr(G, B),
1634 getMulExpr(B, D));
Dan Gohman161ea032009-07-07 17:06:11 +00001635 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001636 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637 if (Ops.size() == 2) return NewAddRec;
1638
1639 Ops.erase(Ops.begin()+Idx);
1640 Ops.erase(Ops.begin()+OtherIdx-1);
1641 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001642 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643 }
1644 }
1645
1646 // Otherwise couldn't fold anything into this recurrence. Move onto the
1647 // next one.
1648 }
1649
1650 // Okay, it looks like we really DO need an mul expr. Check to see if we
1651 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001652 FoldingSetNodeID ID;
1653 ID.AddInteger(scMulExpr);
1654 ID.AddInteger(Ops.size());
1655 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1656 ID.AddPointer(Ops[i]);
1657 void *IP = 0;
1658 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1659 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1660 new (S) SCEVMulExpr(Ops);
1661 UniqueSCEVs.InsertNode(S, IP);
1662 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663}
1664
Dan Gohmanc8a29272009-05-24 23:45:28 +00001665/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1666/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001667const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1668 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001669 assert(getEffectiveSCEVType(LHS->getType()) ==
1670 getEffectiveSCEVType(RHS->getType()) &&
1671 "SCEVUDivExpr operand types don't match!");
1672
Dan Gohmanc76b5452009-05-04 22:02:23 +00001673 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001675 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001676 if (RHSC->isZero())
1677 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001679 // Determine if the division can be folded into the operands of
1680 // its operands.
1681 // TODO: Generalize this to non-constants by using known-bits information.
1682 const Type *Ty = LHS->getType();
1683 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1684 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1685 // For non-power-of-two values, effectively round the value up to the
1686 // nearest power of two.
1687 if (!RHSC->getValue()->getValue().isPowerOf2())
1688 ++MaxShiftAmt;
1689 const IntegerType *ExtTy =
1690 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1691 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1692 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1693 if (const SCEVConstant *Step =
1694 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1695 if (!Step->getValue()->getValue()
1696 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001697 getZeroExtendExpr(AR, ExtTy) ==
1698 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1699 getZeroExtendExpr(Step, ExtTy),
1700 AR->getLoop())) {
Dan Gohman161ea032009-07-07 17:06:11 +00001701 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001702 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1703 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1704 return getAddRecExpr(Operands, AR->getLoop());
1705 }
1706 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001707 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001708 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001709 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1710 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1711 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001712 // Find an operand that's safely divisible.
1713 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001714 const SCEV *Op = M->getOperand(i);
1715 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001716 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman161ea032009-07-07 17:06:11 +00001717 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1718 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001719 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001720 Operands[i] = Div;
1721 return getMulExpr(Operands);
1722 }
1723 }
Dan Gohman14374d32009-05-08 23:11:16 +00001724 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001725 // (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 +00001726 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001727 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001728 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1729 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1730 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1731 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001732 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001733 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001734 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1735 break;
1736 Operands.push_back(Op);
1737 }
1738 if (Operands.size() == A->getNumOperands())
1739 return getAddExpr(Operands);
1740 }
Dan Gohman14374d32009-05-08 23:11:16 +00001741 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001742
1743 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001744 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745 Constant *LHSCV = LHSC->getValue();
1746 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001747 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1748 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749 }
1750 }
1751
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001752 FoldingSetNodeID ID;
1753 ID.AddInteger(scUDivExpr);
1754 ID.AddPointer(LHS);
1755 ID.AddPointer(RHS);
1756 void *IP = 0;
1757 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1758 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1759 new (S) SCEVUDivExpr(LHS, RHS);
1760 UniqueSCEVs.InsertNode(S, IP);
1761 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762}
1763
1764
Dan Gohmanc8a29272009-05-24 23:45:28 +00001765/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1766/// Simplify the expression as much as possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001767const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1768 const SCEV *Step, const Loop *L) {
1769 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001771 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 if (StepChrec->getLoop() == L) {
1773 Operands.insert(Operands.end(), StepChrec->op_begin(),
1774 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001775 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776 }
1777
1778 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001779 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001780}
1781
Dan Gohmanc8a29272009-05-24 23:45:28 +00001782/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1783/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001784const SCEV *
Dan Gohman161ea032009-07-07 17:06:11 +00001785ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman9bc642f2009-06-24 04:48:43 +00001786 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001787 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001788#ifndef NDEBUG
1789 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1790 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1791 getEffectiveSCEVType(Operands[0]->getType()) &&
1792 "SCEVAddRecExpr operand types don't match!");
1793#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794
Dan Gohman7b560c42008-06-18 16:23:07 +00001795 if (Operands.back()->isZero()) {
1796 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001797 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001798 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799
Dan Gohman42936882008-08-08 18:33:12 +00001800 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001801 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001802 const Loop* NestedLoop = NestedAR->getLoop();
1803 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman161ea032009-07-07 17:06:11 +00001804 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001805 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001806 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001807 // AddRecs require their operands be loop-invariant with respect to their
1808 // loops. Don't perform this transformation if it would break this
1809 // requirement.
1810 bool AllInvariant = true;
1811 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1812 if (!Operands[i]->isLoopInvariant(L)) {
1813 AllInvariant = false;
1814 break;
1815 }
1816 if (AllInvariant) {
1817 NestedOperands[0] = getAddRecExpr(Operands, L);
1818 AllInvariant = true;
1819 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1820 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1821 AllInvariant = false;
1822 break;
1823 }
1824 if (AllInvariant)
1825 // Ok, both add recurrences are valid after the transformation.
1826 return getAddRecExpr(NestedOperands, NestedLoop);
1827 }
1828 // Reset Operands to its original state.
1829 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001830 }
1831 }
1832
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001833 FoldingSetNodeID ID;
1834 ID.AddInteger(scAddRecExpr);
1835 ID.AddInteger(Operands.size());
1836 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1837 ID.AddPointer(Operands[i]);
1838 ID.AddPointer(L);
1839 void *IP = 0;
1840 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1841 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1842 new (S) SCEVAddRecExpr(Operands, L);
1843 UniqueSCEVs.InsertNode(S, IP);
1844 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001845}
1846
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001847const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1848 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001849 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001850 Ops.push_back(LHS);
1851 Ops.push_back(RHS);
1852 return getSMaxExpr(Ops);
1853}
1854
Dan Gohman161ea032009-07-07 17:06:11 +00001855const SCEV *
1856ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001857 assert(!Ops.empty() && "Cannot get empty smax!");
1858 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001859#ifndef NDEBUG
1860 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1861 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1862 getEffectiveSCEVType(Ops[0]->getType()) &&
1863 "SCEVSMaxExpr operand types don't match!");
1864#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001865
1866 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001867 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001868
1869 // If there are any constants, fold them together.
1870 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001871 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001872 ++Idx;
1873 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001874 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001875 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001876 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001877 APIntOps::smax(LHSC->getValue()->getValue(),
1878 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001879 Ops[0] = getConstant(Fold);
1880 Ops.erase(Ops.begin()+1); // Erase the folded element
1881 if (Ops.size() == 1) return Ops[0];
1882 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001883 }
1884
Dan Gohmand156c092009-06-24 14:46:22 +00001885 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001886 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1887 Ops.erase(Ops.begin());
1888 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001889 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1890 // If we have an smax with a constant maximum-int, it will always be
1891 // maximum-int.
1892 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001893 }
1894 }
1895
1896 if (Ops.size() == 1) return Ops[0];
1897
1898 // Find the first SMax
1899 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1900 ++Idx;
1901
1902 // Check to see if one of the operands is an SMax. If so, expand its operands
1903 // onto our operand list, and recurse to simplify.
1904 if (Idx < Ops.size()) {
1905 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001906 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001907 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1908 Ops.erase(Ops.begin()+Idx);
1909 DeletedSMax = true;
1910 }
1911
1912 if (DeletedSMax)
1913 return getSMaxExpr(Ops);
1914 }
1915
1916 // Okay, check to see if the same value occurs in the operand list twice. If
1917 // so, delete one. Since we sorted the list, these values are required to
1918 // be adjacent.
1919 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1920 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1921 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1922 --i; --e;
1923 }
1924
1925 if (Ops.size() == 1) return Ops[0];
1926
1927 assert(!Ops.empty() && "Reduced smax down to nothing!");
1928
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001929 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001930 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001931 FoldingSetNodeID ID;
1932 ID.AddInteger(scSMaxExpr);
1933 ID.AddInteger(Ops.size());
1934 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1935 ID.AddPointer(Ops[i]);
1936 void *IP = 0;
1937 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1938 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1939 new (S) SCEVSMaxExpr(Ops);
1940 UniqueSCEVs.InsertNode(S, IP);
1941 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001942}
1943
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001944const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1945 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001946 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001947 Ops.push_back(LHS);
1948 Ops.push_back(RHS);
1949 return getUMaxExpr(Ops);
1950}
1951
Dan Gohman161ea032009-07-07 17:06:11 +00001952const SCEV *
1953ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001954 assert(!Ops.empty() && "Cannot get empty umax!");
1955 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001956#ifndef NDEBUG
1957 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1958 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1959 getEffectiveSCEVType(Ops[0]->getType()) &&
1960 "SCEVUMaxExpr operand types don't match!");
1961#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001962
1963 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001964 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001965
1966 // If there are any constants, fold them together.
1967 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001968 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001969 ++Idx;
1970 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001971 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001972 // We found two constants, fold them together!
1973 ConstantInt *Fold = ConstantInt::get(
1974 APIntOps::umax(LHSC->getValue()->getValue(),
1975 RHSC->getValue()->getValue()));
1976 Ops[0] = getConstant(Fold);
1977 Ops.erase(Ops.begin()+1); // Erase the folded element
1978 if (Ops.size() == 1) return Ops[0];
1979 LHSC = cast<SCEVConstant>(Ops[0]);
1980 }
1981
Dan Gohmand156c092009-06-24 14:46:22 +00001982 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001983 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1984 Ops.erase(Ops.begin());
1985 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001986 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1987 // If we have an umax with a constant maximum-int, it will always be
1988 // maximum-int.
1989 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001990 }
1991 }
1992
1993 if (Ops.size() == 1) return Ops[0];
1994
1995 // Find the first UMax
1996 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1997 ++Idx;
1998
1999 // Check to see if one of the operands is a UMax. If so, expand its operands
2000 // onto our operand list, and recurse to simplify.
2001 if (Idx < Ops.size()) {
2002 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00002003 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002004 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2005 Ops.erase(Ops.begin()+Idx);
2006 DeletedUMax = true;
2007 }
2008
2009 if (DeletedUMax)
2010 return getUMaxExpr(Ops);
2011 }
2012
2013 // Okay, check to see if the same value occurs in the operand list twice. If
2014 // so, delete one. Since we sorted the list, these values are required to
2015 // be adjacent.
2016 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2017 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2018 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2019 --i; --e;
2020 }
2021
2022 if (Ops.size() == 1) return Ops[0];
2023
2024 assert(!Ops.empty() && "Reduced umax down to nothing!");
2025
2026 // Okay, it looks like we really DO need a umax expr. Check to see if we
2027 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002028 FoldingSetNodeID ID;
2029 ID.AddInteger(scUMaxExpr);
2030 ID.AddInteger(Ops.size());
2031 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2032 ID.AddPointer(Ops[i]);
2033 void *IP = 0;
2034 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2035 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2036 new (S) SCEVUMaxExpr(Ops);
2037 UniqueSCEVs.InsertNode(S, IP);
2038 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002039}
2040
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002041const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2042 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00002043 // ~smax(~x, ~y) == smin(x, y).
2044 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2045}
2046
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002047const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2048 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00002049 // ~umax(~x, ~y) == umin(x, y)
2050 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2051}
2052
Dan Gohman161ea032009-07-07 17:06:11 +00002053const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002054 // Don't attempt to do anything other than create a SCEVUnknown object
2055 // here. createSCEV only calls getUnknown after checking for all other
2056 // interesting possibilities, and any other code that calls getUnknown
2057 // is doing so in order to hide a value from SCEV canonicalization.
2058
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002059 FoldingSetNodeID ID;
2060 ID.AddInteger(scUnknown);
2061 ID.AddPointer(V);
2062 void *IP = 0;
2063 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2064 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2065 new (S) SCEVUnknown(V);
2066 UniqueSCEVs.InsertNode(S, IP);
2067 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068}
2069
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002071// Basic SCEV Analysis and PHI Idiom Recognition Code
2072//
2073
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002074/// isSCEVable - Test if values of the given type are analyzable within
2075/// the SCEV framework. This primarily includes integer types, and it
2076/// can optionally include pointer types if the ScalarEvolution class
2077/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002078bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002079 // Integers are always SCEVable.
2080 if (Ty->isInteger())
2081 return true;
2082
2083 // Pointers are SCEVable if TargetData information is available
2084 // to provide pointer size information.
2085 if (isa<PointerType>(Ty))
2086 return TD != NULL;
2087
2088 // Otherwise it's not SCEVable.
2089 return false;
2090}
2091
2092/// getTypeSizeInBits - Return the size in bits of the specified type,
2093/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002094uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002095 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2096
2097 // If we have a TargetData, use it!
2098 if (TD)
2099 return TD->getTypeSizeInBits(Ty);
2100
2101 // Otherwise, we support only integer types.
2102 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2103 return Ty->getPrimitiveSizeInBits();
2104}
2105
2106/// getEffectiveSCEVType - Return a type with the same bitwidth as
2107/// the given type and which represents how SCEV will treat the given
2108/// type, for which isSCEVable must return true. For pointer types,
2109/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002110const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002111 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2112
2113 if (Ty->isInteger())
2114 return Ty;
2115
2116 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2117 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002118}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119
Dan Gohman161ea032009-07-07 17:06:11 +00002120const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002121 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002122}
2123
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002124/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2125/// expression and create a new one.
Dan Gohman161ea032009-07-07 17:06:11 +00002126const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002127 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128
Dan Gohman161ea032009-07-07 17:06:11 +00002129 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 if (I != Scalars.end()) return I->second;
Dan Gohman161ea032009-07-07 17:06:11 +00002131 const SCEV *S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002132 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002133 return S;
2134}
2135
Dan Gohman984c78a2009-06-24 00:54:57 +00002136/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002137/// specified signed integer value and return a SCEV for the constant.
Dan Gohman161ea032009-07-07 17:06:11 +00002138const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002139 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2140 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002141}
2142
2143/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2144///
Dan Gohman161ea032009-07-07 17:06:11 +00002145const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002146 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002147 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002148
2149 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002150 Ty = getEffectiveSCEVType(Ty);
2151 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002152}
2153
2154/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman161ea032009-07-07 17:06:11 +00002155const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002156 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002157 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002158
2159 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002160 Ty = getEffectiveSCEVType(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00002161 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002162 return getMinusSCEV(AllOnes, V);
2163}
2164
2165/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2166///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002167const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2168 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002169 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002170 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002171}
2172
2173/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2174/// input value to the specified type. If the type must be extended, it is zero
2175/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002176const SCEV *
2177ScalarEvolution::getTruncateOrZeroExtend(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 getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002188}
2189
2190/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2191/// input value to the specified type. If the type must be extended, it is sign
2192/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002193const SCEV *
2194ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002195 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002196 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002197 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2198 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002199 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002200 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002201 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002202 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002203 return getTruncateExpr(V, Ty);
2204 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002205}
2206
Dan Gohmanac959332009-05-13 03:46:30 +00002207/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2208/// input value to the specified type. If the type must be extended, it is zero
2209/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002210const SCEV *
2211ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002212 const Type *SrcTy = V->getType();
2213 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2214 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2215 "Cannot noop or zero extend with non-integer arguments!");
2216 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2217 "getNoopOrZeroExtend cannot truncate!");
2218 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2219 return V; // No conversion
2220 return getZeroExtendExpr(V, Ty);
2221}
2222
2223/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2224/// input value to the specified type. If the type must be extended, it is sign
2225/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002226const SCEV *
2227ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +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 sign extend with non-integer arguments!");
2232 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2233 "getNoopOrSignExtend cannot truncate!");
2234 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2235 return V; // No conversion
2236 return getSignExtendExpr(V, Ty);
2237}
2238
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002239/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2240/// the input value to the specified type. If the type must be extended,
2241/// it is extended with unspecified bits. The conversion must not be
2242/// narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002243const SCEV *
2244ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002245 const Type *SrcTy = V->getType();
2246 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2247 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2248 "Cannot noop or any extend with non-integer arguments!");
2249 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2250 "getNoopOrAnyExtend cannot truncate!");
2251 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2252 return V; // No conversion
2253 return getAnyExtendExpr(V, Ty);
2254}
2255
Dan Gohmanac959332009-05-13 03:46:30 +00002256/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2257/// input value to the specified type. The conversion must not be widening.
Dan Gohman161ea032009-07-07 17:06:11 +00002258const SCEV *
2259ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002260 const Type *SrcTy = V->getType();
2261 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2262 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2263 "Cannot truncate or noop with non-integer arguments!");
2264 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2265 "getTruncateOrNoop cannot extend!");
2266 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2267 return V; // No conversion
2268 return getTruncateExpr(V, Ty);
2269}
2270
Dan Gohman8e8b5232009-06-22 00:31:57 +00002271/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2272/// the types using zero-extension, and then perform a umax operation
2273/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002274const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2275 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002276 const SCEV *PromotedLHS = LHS;
2277 const SCEV *PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002278
2279 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2280 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2281 else
2282 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2283
2284 return getUMaxExpr(PromotedLHS, PromotedRHS);
2285}
2286
Dan Gohman9e62bb02009-06-22 15:03:27 +00002287/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2288/// the types using zero-extension, and then perform a umin operation
2289/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002290const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2291 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002292 const SCEV *PromotedLHS = LHS;
2293 const SCEV *PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002294
2295 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2296 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2297 else
2298 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2299
2300 return getUMinExpr(PromotedLHS, PromotedRHS);
2301}
2302
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2304/// the specified instruction and replaces any references to the symbolic value
2305/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002306void
2307ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2308 const SCEV *SymName,
2309 const SCEV *NewVal) {
Dan Gohman161ea032009-07-07 17:06:11 +00002310 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002311 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312 if (SI == Scalars.end()) return;
2313
Dan Gohman161ea032009-07-07 17:06:11 +00002314 const SCEV *NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002315 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 if (NV == SI->second) return; // No change.
2317
2318 SI->second = NV; // Update the scalars map!
2319
2320 // Any instruction values that use this instruction might also need to be
2321 // updated!
2322 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2323 UI != E; ++UI)
2324 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2325}
2326
2327/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2328/// a loop header, making it a potential recurrence, or it doesn't.
2329///
Dan Gohman161ea032009-07-07 17:06:11 +00002330const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002331 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002332 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333 if (L->getHeader() == PN->getParent()) {
2334 // If it lives in the loop header, it has two incoming values, one
2335 // from outside the loop, and one from inside.
2336 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2337 unsigned BackEdge = IncomingEdge^1;
2338
2339 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman161ea032009-07-07 17:06:11 +00002340 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341 assert(Scalars.find(PN) == Scalars.end() &&
2342 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002343 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344
2345 // Using this symbolic name for the PHI, analyze the value coming around
2346 // the back-edge.
Dan Gohman161ea032009-07-07 17:06:11 +00002347 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002348
2349 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2350 // has a special value for the first iteration of the loop.
2351
2352 // If the value coming around the backedge is an add with the symbolic
2353 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002354 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355 // If there is a single occurrence of the symbolic value, replace it
2356 // with a recurrence.
2357 unsigned FoundIndex = Add->getNumOperands();
2358 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2359 if (Add->getOperand(i) == SymbolicName)
2360 if (FoundIndex == e) {
2361 FoundIndex = i;
2362 break;
2363 }
2364
2365 if (FoundIndex != Add->getNumOperands()) {
2366 // Create an add with everything but the specified operand.
Dan Gohman161ea032009-07-07 17:06:11 +00002367 SmallVector<const SCEV *, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2369 if (i != FoundIndex)
2370 Ops.push_back(Add->getOperand(i));
Dan Gohman161ea032009-07-07 17:06:11 +00002371 const SCEV *Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002372
2373 // This is not a valid addrec if the step amount is varying each
2374 // loop iteration, but is not itself an addrec in this loop.
2375 if (Accum->isLoopInvariant(L) ||
2376 (isa<SCEVAddRecExpr>(Accum) &&
2377 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002378 const SCEV *StartVal =
2379 getSCEV(PN->getIncomingValue(IncomingEdge));
2380 const SCEV *PHISCEV =
2381 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382
2383 // Okay, for the entire analysis of this edge we assumed the PHI
2384 // to be symbolic. We now need to go back and update all of the
2385 // entries for the scalars that use the PHI (except for the PHI
2386 // itself) to use the new analyzed value instead of the "symbolic"
2387 // value.
2388 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2389 return PHISCEV;
2390 }
2391 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002392 } else if (const SCEVAddRecExpr *AddRec =
2393 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002394 // Otherwise, this could be a loop like this:
2395 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2396 // In this case, j = {1,+,1} and BEValue is j.
2397 // Because the other in-value of i (0) fits the evolution of BEValue
2398 // i really is an addrec evolution.
2399 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman161ea032009-07-07 17:06:11 +00002400 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401
2402 // If StartVal = j.start - j.stride, we can use StartVal as the
2403 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002404 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002405 AddRec->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002406 const SCEV *PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002407 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408
2409 // Okay, for the entire analysis of this edge we assumed the PHI
2410 // to be symbolic. We now need to go back and update all of the
2411 // entries for the scalars that use the PHI (except for the PHI
2412 // itself) to use the new analyzed value instead of the "symbolic"
2413 // value.
2414 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2415 return PHISCEV;
2416 }
2417 }
2418 }
2419
2420 return SymbolicName;
2421 }
2422
2423 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002424 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002425}
2426
Dan Gohman509cf4d2009-05-08 20:26:55 +00002427/// createNodeForGEP - Expand GEP instructions into add and multiply
2428/// operations. This allows them to be analyzed by regular SCEV code.
2429///
Dan Gohman161ea032009-07-07 17:06:11 +00002430const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002431
2432 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002433 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002434 // Don't attempt to analyze GEPs over unsized objects.
2435 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2436 return getUnknown(GEP);
Dan Gohman161ea032009-07-07 17:06:11 +00002437 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002438 gep_type_iterator GTI = gep_type_begin(GEP);
2439 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2440 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002441 I != E; ++I) {
2442 Value *Index = *I;
2443 // Compute the (potentially symbolic) offset in bytes for this index.
2444 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2445 // For a struct, add the member offset.
2446 const StructLayout &SL = *TD->getStructLayout(STy);
2447 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2448 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman232756f2009-07-10 16:42:52 +00002449 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002450 } else {
2451 // For an array, add the element offset, explicitly scaled.
Dan Gohman161ea032009-07-07 17:06:11 +00002452 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002453 if (!isa<PointerType>(LocalOffset->getType()))
2454 // Getelementptr indicies are signed.
Dan Gohman232756f2009-07-10 16:42:52 +00002455 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002456 LocalOffset =
2457 getMulExpr(LocalOffset,
Dan Gohman232756f2009-07-10 16:42:52 +00002458 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002459 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2460 }
2461 }
2462 return getAddExpr(getSCEV(Base), TotalOffset);
2463}
2464
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002465/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2466/// guaranteed to end in (at every loop iteration). It is, at the same time,
2467/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2468/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002469uint32_t
Dan Gohman161ea032009-07-07 17:06:11 +00002470ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002471 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002472 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473
Dan Gohmanc76b5452009-05-04 22:02:23 +00002474 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002475 return std::min(GetMinTrailingZeros(T->getOperand()),
2476 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002477
Dan Gohmanc76b5452009-05-04 22:02:23 +00002478 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002479 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2480 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2481 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002482 }
2483
Dan Gohmanc76b5452009-05-04 22:02:23 +00002484 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002485 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2486 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2487 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002488 }
2489
Dan Gohmanc76b5452009-05-04 22:02:23 +00002490 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002491 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002492 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002493 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002494 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002495 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496 }
2497
Dan Gohmanc76b5452009-05-04 22:02:23 +00002498 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002499 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002500 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2501 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002502 for (unsigned i = 1, e = M->getNumOperands();
2503 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002504 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002505 BitWidth);
2506 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002507 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002508
Dan Gohmanc76b5452009-05-04 22:02:23 +00002509 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002510 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002511 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002512 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002513 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002514 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002516
Dan Gohmanc76b5452009-05-04 22:02:23 +00002517 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002518 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002519 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002520 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002521 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002522 return MinOpRes;
2523 }
2524
Dan Gohmanc76b5452009-05-04 22:02:23 +00002525 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002526 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002527 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002528 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002529 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002530 return MinOpRes;
2531 }
2532
Dan Gohman6e923a72009-06-19 23:29:04 +00002533 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2534 // For a SCEVUnknown, ask ValueTracking.
2535 unsigned BitWidth = getTypeSizeInBits(U->getType());
2536 APInt Mask = APInt::getAllOnesValue(BitWidth);
2537 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2538 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2539 return Zeros.countTrailingOnes();
2540 }
2541
2542 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002543 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544}
2545
Dan Gohman232756f2009-07-10 16:42:52 +00002546/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2547///
2548ConstantRange
2549ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002550
2551 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman232756f2009-07-10 16:42:52 +00002552 return ConstantRange(C->getValue()->getValue());
Dan Gohman6e923a72009-06-19 23:29:04 +00002553
Dan Gohman232756f2009-07-10 16:42:52 +00002554 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2555 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2556 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2557 X = X.add(getUnsignedRange(Add->getOperand(i)));
2558 return X;
2559 }
2560
2561 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2562 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2563 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2564 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2565 return X;
2566 }
2567
2568 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2569 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2570 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2571 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2572 return X;
2573 }
2574
2575 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2576 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2577 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2578 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2579 return X;
2580 }
2581
2582 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2583 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2584 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2585 return X.udiv(Y);
2586 }
2587
2588 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2589 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2590 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2591 }
2592
2593 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2594 ConstantRange X = getUnsignedRange(SExt->getOperand());
2595 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2596 }
2597
2598 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2599 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2600 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2601 }
2602
2603 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2604
2605 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2606 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2607 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2608 if (!Trip) return FullSet;
2609
2610 // TODO: non-affine addrec
2611 if (AddRec->isAffine()) {
2612 const Type *Ty = AddRec->getType();
2613 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2614 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2615 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2616
2617 const SCEV *Start = AddRec->getStart();
2618 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2619
2620 // Check for overflow.
2621 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2622 return FullSet;
2623
2624 ConstantRange StartRange = getUnsignedRange(Start);
2625 ConstantRange EndRange = getUnsignedRange(End);
2626 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2627 EndRange.getUnsignedMin());
2628 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2629 EndRange.getUnsignedMax());
2630 if (Min.isMinValue() && Max.isMaxValue())
2631 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2632 return ConstantRange(Min, Max+1);
2633 }
2634 }
Dan Gohman6e923a72009-06-19 23:29:04 +00002635 }
2636
2637 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2638 // For a SCEVUnknown, ask ValueTracking.
2639 unsigned BitWidth = getTypeSizeInBits(U->getType());
2640 APInt Mask = APInt::getAllOnesValue(BitWidth);
2641 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2642 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman232756f2009-07-10 16:42:52 +00002643 return ConstantRange(Ones, ~Zeros);
Dan Gohman6e923a72009-06-19 23:29:04 +00002644 }
2645
Dan Gohman232756f2009-07-10 16:42:52 +00002646 return FullSet;
Dan Gohman6e923a72009-06-19 23:29:04 +00002647}
2648
Dan Gohman232756f2009-07-10 16:42:52 +00002649/// getSignedRange - Determine the signed range for a particular SCEV.
2650///
2651ConstantRange
2652ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002653
Dan Gohman232756f2009-07-10 16:42:52 +00002654 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2655 return ConstantRange(C->getValue()->getValue());
2656
2657 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2658 ConstantRange X = getSignedRange(Add->getOperand(0));
2659 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2660 X = X.add(getSignedRange(Add->getOperand(i)));
2661 return X;
Dan Gohman6e923a72009-06-19 23:29:04 +00002662 }
2663
Dan Gohman232756f2009-07-10 16:42:52 +00002664 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2665 ConstantRange X = getSignedRange(Mul->getOperand(0));
2666 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2667 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2668 return X;
Dan Gohman6e923a72009-06-19 23:29:04 +00002669 }
2670
Dan Gohman232756f2009-07-10 16:42:52 +00002671 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2672 ConstantRange X = getSignedRange(SMax->getOperand(0));
2673 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2674 X = X.smax(getSignedRange(SMax->getOperand(i)));
2675 return X;
2676 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002677
Dan Gohman232756f2009-07-10 16:42:52 +00002678 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2679 ConstantRange X = getSignedRange(UMax->getOperand(0));
2680 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2681 X = X.umax(getSignedRange(UMax->getOperand(i)));
2682 return X;
2683 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002684
Dan Gohman232756f2009-07-10 16:42:52 +00002685 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2686 ConstantRange X = getSignedRange(UDiv->getLHS());
2687 ConstantRange Y = getSignedRange(UDiv->getRHS());
2688 return X.udiv(Y);
2689 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002690
Dan Gohman232756f2009-07-10 16:42:52 +00002691 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2692 ConstantRange X = getSignedRange(ZExt->getOperand());
2693 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2694 }
2695
2696 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2697 ConstantRange X = getSignedRange(SExt->getOperand());
2698 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2699 }
2700
2701 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2702 ConstantRange X = getSignedRange(Trunc->getOperand());
2703 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2704 }
2705
2706 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2707
2708 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2709 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2710 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2711 if (!Trip) return FullSet;
2712
2713 // TODO: non-affine addrec
2714 if (AddRec->isAffine()) {
2715 const Type *Ty = AddRec->getType();
2716 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2717 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2718 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2719
2720 const SCEV *Start = AddRec->getStart();
2721 const SCEV *Step = AddRec->getStepRecurrence(*this);
2722 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2723
2724 // Check for overflow.
2725 if (!(isKnownPositive(Step) &&
2726 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2727 !(isKnownNegative(Step) &&
2728 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2729 return FullSet;
2730
2731 ConstantRange StartRange = getSignedRange(Start);
2732 ConstantRange EndRange = getSignedRange(End);
2733 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2734 EndRange.getSignedMin());
2735 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2736 EndRange.getSignedMax());
2737 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2738 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2739 return ConstantRange(Min, Max+1);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002740 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002741 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002742 }
2743
Dan Gohman6e923a72009-06-19 23:29:04 +00002744 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2745 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman232756f2009-07-10 16:42:52 +00002746 unsigned BitWidth = getTypeSizeInBits(U->getType());
2747 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2748 if (NS == 1)
2749 return FullSet;
2750 return
2751 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2752 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman6e923a72009-06-19 23:29:04 +00002753 }
2754
Dan Gohman232756f2009-07-10 16:42:52 +00002755 return FullSet;
Dan Gohman6e923a72009-06-19 23:29:04 +00002756}
2757
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758/// createSCEV - We know that there is no SCEV for the specified value.
2759/// Analyze the expression.
2760///
Dan Gohman161ea032009-07-07 17:06:11 +00002761const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002762 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002763 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002764
Dan Gohman3996f472008-06-22 19:56:46 +00002765 unsigned Opcode = Instruction::UserOp1;
2766 if (Instruction *I = dyn_cast<Instruction>(V))
2767 Opcode = I->getOpcode();
2768 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2769 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002770 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2771 return getConstant(CI);
2772 else if (isa<ConstantPointerNull>(V))
2773 return getIntegerSCEV(0, V->getType());
2774 else if (isa<UndefValue>(V))
2775 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002776 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002777 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778
Dan Gohman3996f472008-06-22 19:56:46 +00002779 User *U = cast<User>(V);
2780 switch (Opcode) {
2781 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002782 return getAddExpr(getSCEV(U->getOperand(0)),
2783 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002784 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002785 return getMulExpr(getSCEV(U->getOperand(0)),
2786 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002787 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002788 return getUDivExpr(getSCEV(U->getOperand(0)),
2789 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002790 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002791 return getMinusSCEV(getSCEV(U->getOperand(0)),
2792 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002793 case Instruction::And:
2794 // For an expression like x&255 that merely masks off the high bits,
2795 // use zext(trunc(x)) as the SCEV expression.
2796 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002797 if (CI->isNullValue())
2798 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002799 if (CI->isAllOnesValue())
2800 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002801 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002802
2803 // Instcombine's ShrinkDemandedConstant may strip bits out of
2804 // constants, obscuring what would otherwise be a low-bits mask.
2805 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2806 // knew about to reconstruct a low-bits mask value.
2807 unsigned LZ = A.countLeadingZeros();
2808 unsigned BitWidth = A.getBitWidth();
2809 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2810 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2811 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2812
2813 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2814
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002815 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002816 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002817 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002818 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002819 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002820 }
2821 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002822
Dan Gohman3996f472008-06-22 19:56:46 +00002823 case Instruction::Or:
2824 // If the RHS of the Or is a constant, we may have something like:
2825 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2826 // optimizations will transparently handle this case.
2827 //
2828 // In order for this transformation to be safe, the LHS must be of the
2829 // form X*(2^n) and the Or constant must be less than 2^n.
2830 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002831 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002832 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002833 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002834 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002835 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002836 }
Dan Gohman3996f472008-06-22 19:56:46 +00002837 break;
2838 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002839 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002840 // If the RHS of the xor is a signbit, then this is just an add.
2841 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002842 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002843 return getAddExpr(getSCEV(U->getOperand(0)),
2844 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002845
2846 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002847 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002848 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002849
2850 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2851 // This is a variant of the check for xor with -1, and it handles
2852 // the case where instcombine has trimmed non-demanded bits out
2853 // of an xor with -1.
2854 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2855 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2856 if (BO->getOpcode() == Instruction::And &&
2857 LCI->getValue() == CI->getValue())
2858 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002859 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002860 const Type *UTy = U->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00002861 const SCEV *Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002862 const Type *Z0Ty = Z0->getType();
2863 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2864
2865 // If C is a low-bits mask, the zero extend is zerving to
2866 // mask off the high bits. Complement the operand and
2867 // re-apply the zext.
2868 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2869 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2870
2871 // If C is a single bit, it may be in the sign-bit position
2872 // before the zero-extend. In this case, represent the xor
2873 // using an add, which is equivalent, and re-apply the zext.
2874 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2875 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2876 Trunc.isSignBit())
2877 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2878 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002879 }
Dan Gohman3996f472008-06-22 19:56:46 +00002880 }
2881 break;
2882
2883 case Instruction::Shl:
2884 // Turn shift left of a constant amount into a multiply.
2885 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2886 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2887 Constant *X = ConstantInt::get(
2888 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002889 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002890 }
2891 break;
2892
Nick Lewycky7fd27892008-07-07 06:15:49 +00002893 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002894 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002895 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2896 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2897 Constant *X = ConstantInt::get(
2898 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002899 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002900 }
2901 break;
2902
Dan Gohman53bf64a2009-04-21 02:26:00 +00002903 case Instruction::AShr:
2904 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2905 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2906 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2907 if (L->getOpcode() == Instruction::Shl &&
2908 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002909 unsigned BitWidth = getTypeSizeInBits(U->getType());
2910 uint64_t Amt = BitWidth - CI->getZExtValue();
2911 if (Amt == BitWidth)
2912 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2913 if (Amt > BitWidth)
2914 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002915 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002916 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002917 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002918 U->getType());
2919 }
2920 break;
2921
Dan Gohman3996f472008-06-22 19:56:46 +00002922 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002923 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002924
2925 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002926 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002927
2928 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002929 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002930
2931 case Instruction::BitCast:
2932 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002933 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002934 return getSCEV(U->getOperand(0));
2935 break;
2936
Dan Gohman01c2ee72009-04-16 03:18:22 +00002937 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002938 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002939 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002940 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002941
2942 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002943 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002944 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2945 U->getType());
2946
Dan Gohman509cf4d2009-05-08 20:26:55 +00002947 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002948 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002949 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002950
Dan Gohman3996f472008-06-22 19:56:46 +00002951 case Instruction::PHI:
2952 return createNodeForPHI(cast<PHINode>(U));
2953
2954 case Instruction::Select:
2955 // This could be a smax or umax that was lowered earlier.
2956 // Try to recover it.
2957 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2958 Value *LHS = ICI->getOperand(0);
2959 Value *RHS = ICI->getOperand(1);
2960 switch (ICI->getPredicate()) {
2961 case ICmpInst::ICMP_SLT:
2962 case ICmpInst::ICMP_SLE:
2963 std::swap(LHS, RHS);
2964 // fall through
2965 case ICmpInst::ICMP_SGT:
2966 case ICmpInst::ICMP_SGE:
2967 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002968 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002969 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002970 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002971 break;
2972 case ICmpInst::ICMP_ULT:
2973 case ICmpInst::ICMP_ULE:
2974 std::swap(LHS, RHS);
2975 // fall through
2976 case ICmpInst::ICMP_UGT:
2977 case ICmpInst::ICMP_UGE:
2978 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002979 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002980 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002981 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002982 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002983 case ICmpInst::ICMP_NE:
2984 // n != 0 ? n : 1 -> umax(n, 1)
2985 if (LHS == U->getOperand(1) &&
2986 isa<ConstantInt>(U->getOperand(2)) &&
2987 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2988 isa<ConstantInt>(RHS) &&
2989 cast<ConstantInt>(RHS)->isZero())
2990 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2991 break;
2992 case ICmpInst::ICMP_EQ:
2993 // n == 0 ? 1 : n -> umax(n, 1)
2994 if (LHS == U->getOperand(2) &&
2995 isa<ConstantInt>(U->getOperand(1)) &&
2996 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2997 isa<ConstantInt>(RHS) &&
2998 cast<ConstantInt>(RHS)->isZero())
2999 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3000 break;
Dan Gohman3996f472008-06-22 19:56:46 +00003001 default:
3002 break;
3003 }
3004 }
3005
3006 default: // We cannot analyze this expression.
3007 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003008 }
3009
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003010 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011}
3012
3013
3014
3015//===----------------------------------------------------------------------===//
3016// Iteration Count Computation Code
3017//
3018
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003019/// getBackedgeTakenCount - If the specified loop has a predictable
3020/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3021/// object. The backedge-taken count is the number of times the loop header
3022/// will be branched to from within the loop. This is one less than the
3023/// trip count of the loop, since it doesn't count the first iteration,
3024/// when the header is branched to from outside the loop.
3025///
3026/// Note that it is not valid to call this method on a loop without a
3027/// loop-invariant backedge-taken count (see
3028/// hasLoopInvariantBackedgeTakenCount).
3029///
Dan Gohman161ea032009-07-07 17:06:11 +00003030const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003031 return getBackedgeTakenInfo(L).Exact;
3032}
3033
3034/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3035/// return the least SCEV value that is known never to be less than the
3036/// actual backedge taken count.
Dan Gohman161ea032009-07-07 17:06:11 +00003037const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003038 return getBackedgeTakenInfo(L).Max;
3039}
3040
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003041/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3042/// onto the given Worklist.
3043static void
3044PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3045 BasicBlock *Header = L->getHeader();
3046
3047 // Push all Loop-header PHIs onto the Worklist stack.
3048 for (BasicBlock::iterator I = Header->begin();
3049 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3050 Worklist.push_back(PN);
3051}
3052
3053/// PushDefUseChildren - Push users of the given Instruction
3054/// onto the given Worklist.
3055static void
3056PushDefUseChildren(Instruction *I,
3057 SmallVectorImpl<Instruction *> &Worklist) {
3058 // Push the def-use children onto the Worklist stack.
3059 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3060 UI != UE; ++UI)
3061 Worklist.push_back(cast<Instruction>(UI));
3062}
3063
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003064const ScalarEvolution::BackedgeTakenInfo &
3065ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00003066 // Initially insert a CouldNotCompute for this loop. If the insertion
3067 // succeeds, procede to actually compute a backedge-taken count and
3068 // update the value. The temporary CouldNotCompute value tells SCEV
3069 // code elsewhere that it shouldn't attempt to request a new
3070 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003071 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00003072 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3073 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003074 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003075 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003076 assert(ItCount.Exact->isLoopInvariant(L) &&
3077 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003078 "Computed trip count isn't loop invariant for loop!");
3079 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00003080
Dan Gohmana9dba962009-04-27 20:16:15 +00003081 // Update the value in the map.
3082 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003083 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003084 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003085 // Update the value in the map.
3086 Pair.first->second = ItCount;
3087 if (isa<PHINode>(L->getHeader()->begin()))
3088 // Only count loops that have phi nodes as not being computable.
3089 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003090 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003091
3092 // Now that we know more about the trip count for this loop, forget any
3093 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003094 // conservative estimates made without the benefit of trip count
3095 // information. This is similar to the code in
3096 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3097 // nodes specially.
3098 if (ItCount.hasAnyInfo()) {
3099 SmallVector<Instruction *, 16> Worklist;
3100 PushLoopPHIs(L, Worklist);
3101
3102 SmallPtrSet<Instruction *, 8> Visited;
3103 while (!Worklist.empty()) {
3104 Instruction *I = Worklist.pop_back_val();
3105 if (!Visited.insert(I)) continue;
3106
3107 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3108 Scalars.find(static_cast<Value *>(I));
3109 if (It != Scalars.end()) {
3110 // SCEVUnknown for a PHI either means that it has an unrecognized
3111 // structure, or it's a PHI that's in the progress of being computed
3112 // by createNodeForPHI. In the former case, additional loop trip count
3113 // information isn't going to change anything. In the later case,
3114 // createNodeForPHI will perform the necessary updates on its own when
3115 // it gets to that point.
3116 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3117 Scalars.erase(It);
3118 ValuesAtScopes.erase(I);
3119 if (PHINode *PN = dyn_cast<PHINode>(I))
3120 ConstantEvolutionLoopExitValue.erase(PN);
3121 }
3122
3123 PushDefUseChildren(I, Worklist);
3124 }
3125 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003126 }
Dan Gohmana9dba962009-04-27 20:16:15 +00003127 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128}
3129
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003130/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003131/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003132/// ScalarEvolution's ability to compute a trip count, or if the loop
3133/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003134void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003135 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00003136
Dan Gohmanbff6b582009-05-04 22:30:44 +00003137 SmallVector<Instruction *, 16> Worklist;
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003138 PushLoopPHIs(L, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003139
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003140 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00003141 while (!Worklist.empty()) {
3142 Instruction *I = Worklist.pop_back_val();
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003143 if (!Visited.insert(I)) continue;
3144
3145 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3146 Scalars.find(static_cast<Value *>(I));
3147 if (It != Scalars.end()) {
3148 Scalars.erase(It);
3149 ValuesAtScopes.erase(I);
3150 if (PHINode *PN = dyn_cast<PHINode>(I))
3151 ConstantEvolutionLoopExitValue.erase(PN);
3152 }
3153
3154 PushDefUseChildren(I, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003155 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003156}
3157
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003158/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3159/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003160ScalarEvolution::BackedgeTakenInfo
3161ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00003162 SmallVector<BasicBlock*, 8> ExitingBlocks;
3163 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003164
Dan Gohman8e8b5232009-06-22 00:31:57 +00003165 // Examine all exits and pick the most conservative values.
Dan Gohman161ea032009-07-07 17:06:11 +00003166 const SCEV *BECount = getCouldNotCompute();
3167 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003168 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003169 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3170 BackedgeTakenInfo NewBTI =
3171 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003173 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00003174 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00003175 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003176 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003177 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003178 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003179 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003180 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003181 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00003182 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003183 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003184 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003185 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003186 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003187 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003188 }
3189
3190 return BackedgeTakenInfo(BECount, MaxBECount);
3191}
3192
3193/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3194/// of the specified loop will execute if it exits via the specified block.
3195ScalarEvolution::BackedgeTakenInfo
3196ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3197 BasicBlock *ExitingBlock) {
3198
3199 // Okay, we've chosen an exiting block. See what condition causes us to
3200 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201 //
3202 // FIXME: we should be able to handle switch instructions (with a single exit)
3203 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003204 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00003206
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 // At this point, we know we have a conditional branch that determines whether
3208 // the loop is exited. However, we don't know if the branch is executed each
3209 // time through the loop. If not, then the execution count of the branch will
3210 // not be equal to the trip count of the loop.
3211 //
3212 // Currently we check for this by checking to see if the Exit branch goes to
3213 // the loop header. If so, we know it will always execute the same number of
3214 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00003215 // loop header. This is common for un-rotated loops.
3216 //
3217 // If both of those tests fail, walk up the unique predecessor chain to the
3218 // header, stopping if there is an edge that doesn't exit the loop. If the
3219 // header is reached, the execution count of the branch will be equal to the
3220 // trip count of the loop.
3221 //
3222 // More extensive analysis could be done to handle more cases here.
3223 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3225 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003226 ExitBr->getParent() != L->getHeader()) {
3227 // The simple checks failed, try climbing the unique predecessor chain
3228 // up to the header.
3229 bool Ok = false;
3230 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3231 BasicBlock *Pred = BB->getUniquePredecessor();
3232 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003233 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003234 TerminatorInst *PredTerm = Pred->getTerminator();
3235 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3236 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3237 if (PredSucc == BB)
3238 continue;
3239 // If the predecessor has a successor that isn't BB and isn't
3240 // outside the loop, assume the worst.
3241 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003242 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003243 }
3244 if (Pred == L->getHeader()) {
3245 Ok = true;
3246 break;
3247 }
3248 BB = Pred;
3249 }
3250 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003251 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003252 }
3253
3254 // Procede to the next level to examine the exit condition expression.
3255 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3256 ExitBr->getSuccessor(0),
3257 ExitBr->getSuccessor(1));
3258}
3259
3260/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3261/// backedge of the specified loop will execute if its exit condition
3262/// were a conditional branch of ExitCond, TBB, and FBB.
3263ScalarEvolution::BackedgeTakenInfo
3264ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3265 Value *ExitCond,
3266 BasicBlock *TBB,
3267 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003268 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003269 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3270 if (BO->getOpcode() == Instruction::And) {
3271 // Recurse on the operands of the and.
3272 BackedgeTakenInfo BTI0 =
3273 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3274 BackedgeTakenInfo BTI1 =
3275 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003276 const SCEV *BECount = getCouldNotCompute();
3277 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003278 if (L->contains(TBB)) {
3279 // Both conditions must be true for the loop to continue executing.
3280 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003281 if (BTI0.Exact == getCouldNotCompute() ||
3282 BTI1.Exact == getCouldNotCompute())
3283 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003284 else
3285 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003286 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003287 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003288 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003289 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003290 else
3291 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003292 } else {
3293 // Both conditions must be true for the loop to exit.
3294 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003295 if (BTI0.Exact != getCouldNotCompute() &&
3296 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003297 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003298 if (BTI0.Max != getCouldNotCompute() &&
3299 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003300 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3301 }
3302
3303 return BackedgeTakenInfo(BECount, MaxBECount);
3304 }
3305 if (BO->getOpcode() == Instruction::Or) {
3306 // Recurse on the operands of the or.
3307 BackedgeTakenInfo BTI0 =
3308 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3309 BackedgeTakenInfo BTI1 =
3310 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003311 const SCEV *BECount = getCouldNotCompute();
3312 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003313 if (L->contains(FBB)) {
3314 // Both conditions must be false for the loop to continue executing.
3315 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003316 if (BTI0.Exact == getCouldNotCompute() ||
3317 BTI1.Exact == getCouldNotCompute())
3318 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003319 else
3320 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003321 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003322 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003323 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003324 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003325 else
3326 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003327 } else {
3328 // Both conditions must be false for the loop to exit.
3329 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003330 if (BTI0.Exact != getCouldNotCompute() &&
3331 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003332 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003333 if (BTI0.Max != getCouldNotCompute() &&
3334 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003335 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3336 }
3337
3338 return BackedgeTakenInfo(BECount, MaxBECount);
3339 }
3340 }
3341
3342 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3343 // Procede to the next level to examine the icmp.
3344 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3345 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346
Eli Friedman459d7292009-05-09 12:32:42 +00003347 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003348 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3349}
3350
3351/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3352/// backedge of the specified loop will execute if its exit condition
3353/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3354ScalarEvolution::BackedgeTakenInfo
3355ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3356 ICmpInst *ExitCond,
3357 BasicBlock *TBB,
3358 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359
3360 // If the condition was exit on true, convert the condition to exit on false
3361 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003362 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363 Cond = ExitCond->getPredicate();
3364 else
3365 Cond = ExitCond->getInversePredicate();
3366
3367 // Handle common loops like: for (X = "string"; *X; ++X)
3368 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3369 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00003370 const SCEV *ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003371 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003372 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3373 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3374 return BackedgeTakenInfo(ItCnt,
3375 isa<SCEVConstant>(ItCnt) ? ItCnt :
3376 getConstant(APInt::getMaxValue(BitWidth)-1));
3377 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 }
3379
Dan Gohman161ea032009-07-07 17:06:11 +00003380 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3381 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382
3383 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003384 LHS = getSCEVAtScope(LHS, L);
3385 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003386
Dan Gohman9bc642f2009-06-24 04:48:43 +00003387 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003388 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003389 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3390 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391 std::swap(LHS, RHS);
3392 Cond = ICmpInst::getSwappedPredicate(Cond);
3393 }
3394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003395 // If we have a comparison of a chrec against a constant, try to use value
3396 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003397 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3398 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003400 // Form the constant range.
3401 ConstantRange CompRange(
3402 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403
Dan Gohman161ea032009-07-07 17:06:11 +00003404 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003405 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 }
3407
3408 switch (Cond) {
3409 case ICmpInst::ICMP_NE: { // while (X != Y)
3410 // Convert to: while (X-Y != 0)
Dan Gohman161ea032009-07-07 17:06:11 +00003411 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003412 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3413 break;
3414 }
3415 case ICmpInst::ICMP_EQ: {
3416 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman161ea032009-07-07 17:06:11 +00003417 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003418 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3419 break;
3420 }
3421 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003422 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3423 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003424 break;
3425 }
3426 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003427 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3428 getNotSCEV(RHS), L, true);
3429 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003430 break;
3431 }
3432 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003433 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3434 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003435 break;
3436 }
3437 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003438 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3439 getNotSCEV(RHS), L, false);
3440 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441 break;
3442 }
3443 default:
3444#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003445 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003446 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003447 errs() << "[unsigned] ";
3448 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003449 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003450 << " " << *RHS << "\n";
3451#endif
3452 break;
3453 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003454 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003455 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456}
3457
3458static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003459EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3460 ScalarEvolution &SE) {
Dan Gohman161ea032009-07-07 17:06:11 +00003461 const SCEV *InVal = SE.getConstant(C);
3462 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003463 assert(isa<SCEVConstant>(Val) &&
3464 "Evaluation of SCEV at constant didn't fold correctly?");
3465 return cast<SCEVConstant>(Val)->getValue();
3466}
3467
3468/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3469/// and a GEP expression (missing the pointer index) indexing into it, return
3470/// the addressed element of the initializer or null if the index expression is
3471/// invalid.
3472static Constant *
3473GetAddressedElementFromGlobal(GlobalVariable *GV,
3474 const std::vector<ConstantInt*> &Indices) {
3475 Constant *Init = GV->getInitializer();
3476 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3477 uint64_t Idx = Indices[i]->getZExtValue();
3478 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3479 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3480 Init = cast<Constant>(CS->getOperand(Idx));
3481 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3482 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3483 Init = cast<Constant>(CA->getOperand(Idx));
3484 } else if (isa<ConstantAggregateZero>(Init)) {
3485 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3486 assert(Idx < STy->getNumElements() && "Bad struct index!");
3487 Init = Constant::getNullValue(STy->getElementType(Idx));
3488 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3489 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3490 Init = Constant::getNullValue(ATy->getElementType());
3491 } else {
Edwin Török675d5622009-07-11 20:10:48 +00003492 LLVM_UNREACHABLE("Unknown constant aggregate type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003493 }
3494 return 0;
3495 } else {
3496 return 0; // Unknown initializer type
3497 }
3498 }
3499 return Init;
3500}
3501
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003502/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3503/// 'icmp op load X, cst', try to see if we can compute the backedge
3504/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003505const SCEV *
3506ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3507 LoadInst *LI,
3508 Constant *RHS,
3509 const Loop *L,
3510 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003511 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512
3513 // Check to see if the loaded pointer is a getelementptr of a global.
3514 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003515 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516
3517 // Make sure that it is really a constant global we are gepping, with an
3518 // initializer, and make sure the first IDX is really 0.
3519 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3520 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3521 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3522 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003523 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524
3525 // Okay, we allow one non-constant index into the GEP instruction.
3526 Value *VarIdx = 0;
3527 std::vector<ConstantInt*> Indexes;
3528 unsigned VarIdxNum = 0;
3529 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3530 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3531 Indexes.push_back(CI);
3532 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003533 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 VarIdx = GEP->getOperand(i);
3535 VarIdxNum = i-2;
3536 Indexes.push_back(0);
3537 }
3538
3539 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3540 // Check to see if X is a loop variant variable value now.
Dan Gohman161ea032009-07-07 17:06:11 +00003541 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003542 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543
3544 // We can only recognize very limited forms of loop index expressions, in
3545 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003546 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3548 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3549 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003550 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003551
3552 unsigned MaxSteps = MaxBruteForceIterations;
3553 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3554 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003555 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003556 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557
3558 // Form the GEP offset.
3559 Indexes[VarIdxNum] = Val;
3560
3561 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3562 if (Result == 0) break; // Cannot compute!
3563
3564 // Evaluate the condition for this iteration.
3565 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3566 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3567 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3568#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003569 errs() << "\n***\n*** Computed loop count " << *ItCst
3570 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3571 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572#endif
3573 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003574 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003575 }
3576 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003577 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578}
3579
3580
3581/// CanConstantFold - Return true if we can constant fold an instruction of the
3582/// specified type, assuming that all operands were constants.
3583static bool CanConstantFold(const Instruction *I) {
3584 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3585 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3586 return true;
3587
3588 if (const CallInst *CI = dyn_cast<CallInst>(I))
3589 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003590 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003591 return false;
3592}
3593
3594/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3595/// in the loop that V is derived from. We allow arbitrary operations along the
3596/// way, but the operands of an operation must either be constants or a value
3597/// derived from a constant PHI. If this expression does not fit with these
3598/// constraints, return null.
3599static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3600 // If this is not an instruction, or if this is an instruction outside of the
3601 // loop, it can't be derived from a loop PHI.
3602 Instruction *I = dyn_cast<Instruction>(V);
3603 if (I == 0 || !L->contains(I->getParent())) return 0;
3604
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003605 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003606 if (L->getHeader() == I->getParent())
3607 return PN;
3608 else
3609 // We don't currently keep track of the control flow needed to evaluate
3610 // PHIs, so we cannot handle PHIs inside of loops.
3611 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003612 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003613
3614 // If we won't be able to constant fold this expression even if the operands
3615 // are constants, return early.
3616 if (!CanConstantFold(I)) return 0;
3617
3618 // Otherwise, we can evaluate this instruction if all of its operands are
3619 // constant or derived from a PHI node themselves.
3620 PHINode *PHI = 0;
3621 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3622 if (!(isa<Constant>(I->getOperand(Op)) ||
3623 isa<GlobalValue>(I->getOperand(Op)))) {
3624 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3625 if (P == 0) return 0; // Not evolving from PHI
3626 if (PHI == 0)
3627 PHI = P;
3628 else if (PHI != P)
3629 return 0; // Evolving from multiple different PHIs.
3630 }
3631
3632 // This is a expression evolving from a constant PHI!
3633 return PHI;
3634}
3635
3636/// EvaluateExpression - Given an expression that passes the
3637/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3638/// in the loop has the value PHIVal. If we can't fold this expression for some
3639/// reason, return null.
3640static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3641 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003642 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003643 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644 Instruction *I = cast<Instruction>(V);
Owen Anderson5349f052009-07-06 23:00:19 +00003645 LLVMContext *Context = I->getParent()->getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003646
3647 std::vector<Constant*> Operands;
3648 Operands.resize(I->getNumOperands());
3649
3650 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3651 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3652 if (Operands[i] == 0) return 0;
3653 }
3654
Chris Lattnerd6e56912007-12-10 22:53:04 +00003655 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3656 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003657 &Operands[0], Operands.size(),
3658 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003659 else
3660 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003661 &Operands[0], Operands.size(),
3662 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663}
3664
3665/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3666/// in the header of its containing loop, we know the loop executes a
3667/// constant number of times, and the PHI node is just a recurrence
3668/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003669Constant *
3670ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3671 const APInt& BEs,
3672 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003673 std::map<PHINode*, Constant*>::iterator I =
3674 ConstantEvolutionLoopExitValue.find(PN);
3675 if (I != ConstantEvolutionLoopExitValue.end())
3676 return I->second;
3677
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003678 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3680
3681 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3682
3683 // Since the loop is canonicalized, the PHI node must have two entries. One
3684 // entry must be a constant (coming in from outside of the loop), and the
3685 // second must be derived from the same PHI.
3686 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3687 Constant *StartCST =
3688 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3689 if (StartCST == 0)
3690 return RetVal = 0; // Must be a constant.
3691
3692 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3693 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3694 if (PN2 != PN)
3695 return RetVal = 0; // Not derived from same PHI.
3696
3697 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003698 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3700
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003701 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702 unsigned IterationNum = 0;
3703 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3704 if (IterationNum == NumIterations)
3705 return RetVal = PHIVal; // Got exit value!
3706
3707 // Compute the value of the PHI node for the next iteration.
3708 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3709 if (NextPHI == PHIVal)
3710 return RetVal = NextPHI; // Stopped evolving!
3711 if (NextPHI == 0)
3712 return 0; // Couldn't evaluate!
3713 PHIVal = NextPHI;
3714 }
3715}
3716
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003717/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718/// constant number of times (the condition evolves only from constants),
3719/// try to evaluate a few iterations of the loop until we get the exit
3720/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003721/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003722const SCEV *
3723ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3724 Value *Cond,
3725 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003726 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003727 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728
3729 // Since the loop is canonicalized, the PHI node must have two entries. One
3730 // entry must be a constant (coming in from outside of the loop), and the
3731 // second must be derived from the same PHI.
3732 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3733 Constant *StartCST =
3734 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003735 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736
3737 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3738 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003739 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003740
3741 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3742 // the loop symbolically to determine when the condition gets a value of
3743 // "ExitWhen".
3744 unsigned IterationNum = 0;
3745 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3746 for (Constant *PHIVal = StartCST;
3747 IterationNum != MaxIterations; ++IterationNum) {
3748 ConstantInt *CondVal =
3749 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3750
3751 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003752 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003753
3754 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003756 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003757 }
3758
3759 // Compute the value of the PHI node for the next iteration.
3760 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3761 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003762 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003763 PHIVal = NextPHI;
3764 }
3765
3766 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003767 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003768}
3769
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003770/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3771/// at the specified scope in the program. The L value specifies a loop
3772/// nest to evaluate the expression at, where null is the top-level or a
3773/// specified loop is immediately inside of the loop.
3774///
3775/// This method can be used to compute the exit value for a variable defined
3776/// in a loop by querying what the value will hold in the parent loop.
3777///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003778/// In the case that a relevant loop exit value cannot be computed, the
3779/// original value V is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003780const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781 // FIXME: this should be turned into a virtual method on SCEV!
3782
3783 if (isa<SCEVConstant>(V)) return V;
3784
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003785 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003786 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003787 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003788 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003789 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3791 if (PHINode *PN = dyn_cast<PHINode>(I))
3792 if (PN->getParent() == LI->getHeader()) {
3793 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003794 // to see if the loop that contains it has a known backedge-taken
3795 // count. If so, we may be able to force computation of the exit
3796 // value.
Dan Gohman161ea032009-07-07 17:06:11 +00003797 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003798 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003799 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003800 // Okay, we know how many times the containing loop executes. If
3801 // this is a constant evolving PHI node, get the final value at
3802 // the specified iteration number.
3803 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003804 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 LI);
Dan Gohman652caf12009-06-29 21:31:18 +00003806 if (RV) return getSCEV(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 }
3808 }
3809
3810 // Okay, this is an expression that we cannot symbolically evaluate
3811 // into a SCEV. Check to see if it's possible to symbolically evaluate
3812 // the arguments into constants, and if so, try to constant propagate the
3813 // result. This is particularly useful for computing loop exit values.
3814 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003815 // Check to see if we've folded this instruction at this loop before.
3816 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3817 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3818 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3819 if (!Pair.second)
Dan Gohman652caf12009-06-29 21:31:18 +00003820 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohmanda0071e2009-05-08 20:47:27 +00003821
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003822 std::vector<Constant*> Operands;
3823 Operands.reserve(I->getNumOperands());
3824 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3825 Value *Op = I->getOperand(i);
3826 if (Constant *C = dyn_cast<Constant>(Op)) {
3827 Operands.push_back(C);
3828 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003829 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003830 // non-integer and non-pointer, don't even try to analyze them
3831 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003832 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003833 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003834
Dan Gohman232756f2009-07-10 16:42:52 +00003835 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003836 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003837 Constant *C = SC->getValue();
3838 if (C->getType() != Op->getType())
3839 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3840 Op->getType(),
3841 false),
3842 C, Op->getType());
3843 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003844 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003845 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3846 if (C->getType() != Op->getType())
3847 C =
3848 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3849 Op->getType(),
3850 false),
3851 C, Op->getType());
3852 Operands.push_back(C);
3853 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003854 return V;
3855 } else {
3856 return V;
3857 }
3858 }
3859 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003860
Chris Lattnerd6e56912007-12-10 22:53:04 +00003861 Constant *C;
3862 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3863 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003864 &Operands[0], Operands.size(),
3865 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003866 else
3867 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003868 &Operands[0], Operands.size(), Context);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003869 Pair.first->second = C;
Dan Gohman652caf12009-06-29 21:31:18 +00003870 return getSCEV(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003871 }
3872 }
3873
3874 // This is some other type of SCEVUnknown, just return it.
3875 return V;
3876 }
3877
Dan Gohmanc76b5452009-05-04 22:02:23 +00003878 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003879 // Avoid performing the look-up in the common case where the specified
3880 // expression has no loop-variant portions.
3881 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00003882 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003883 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003884 // Okay, at least one of these operands is loop variant but might be
3885 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003886 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3887 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003888 NewOps.push_back(OpAtScope);
3889
3890 for (++i; i != e; ++i) {
3891 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003892 NewOps.push_back(OpAtScope);
3893 }
3894 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003895 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003896 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003897 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003898 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003899 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003900 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003901 return getUMaxExpr(NewOps);
Edwin Török675d5622009-07-11 20:10:48 +00003902 LLVM_UNREACHABLE("Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003903 }
3904 }
3905 // If we got here, all operands are loop invariant.
3906 return Comm;
3907 }
3908
Dan Gohmanc76b5452009-05-04 22:02:23 +00003909 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003910 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3911 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003912 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3913 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003914 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003915 }
3916
3917 // If this is a loop recurrence for a loop that does not contain L, then we
3918 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003919 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003920 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3921 // To evaluate this recurrence, we need to know how many times the AddRec
3922 // loop iterates. Compute this now.
Dan Gohman161ea032009-07-07 17:06:11 +00003923 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003924 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925
Eli Friedman7489ec92008-08-04 23:49:06 +00003926 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003927 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003928 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003929 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003930 }
3931
Dan Gohmanc76b5452009-05-04 22:02:23 +00003932 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003933 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003934 if (Op == Cast->getOperand())
3935 return Cast; // must be loop invariant
3936 return getZeroExtendExpr(Op, Cast->getType());
3937 }
3938
Dan Gohmanc76b5452009-05-04 22:02:23 +00003939 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003940 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003941 if (Op == Cast->getOperand())
3942 return Cast; // must be loop invariant
3943 return getSignExtendExpr(Op, Cast->getType());
3944 }
3945
Dan Gohmanc76b5452009-05-04 22:02:23 +00003946 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003947 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003948 if (Op == Cast->getOperand())
3949 return Cast; // must be loop invariant
3950 return getTruncateExpr(Op, Cast->getType());
3951 }
3952
Edwin Török675d5622009-07-11 20:10:48 +00003953 LLVM_UNREACHABLE("Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003954 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003955}
3956
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003957/// getSCEVAtScope - This is a convenience function which does
3958/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman161ea032009-07-07 17:06:11 +00003959const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003960 return getSCEVAtScope(getSCEV(V), L);
3961}
3962
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003963/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3964/// following equation:
3965///
3966/// A * X = B (mod N)
3967///
3968/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3969/// A and B isn't important.
3970///
3971/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003972static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003973 ScalarEvolution &SE) {
3974 uint32_t BW = A.getBitWidth();
3975 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3976 assert(A != 0 && "A must be non-zero.");
3977
3978 // 1. D = gcd(A, N)
3979 //
3980 // The gcd of A and N may have only one prime factor: 2. The number of
3981 // trailing zeros in A is its multiplicity
3982 uint32_t Mult2 = A.countTrailingZeros();
3983 // D = 2^Mult2
3984
3985 // 2. Check if B is divisible by D.
3986 //
3987 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3988 // is not less than multiplicity of this prime factor for D.
3989 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003990 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003991
3992 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3993 // modulo (N / D).
3994 //
3995 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3996 // bit width during computations.
3997 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3998 APInt Mod(BW + 1, 0);
3999 Mod.set(BW - Mult2); // Mod = N / D
4000 APInt I = AD.multiplicativeInverse(Mod);
4001
4002 // 4. Compute the minimum unsigned root of the equation:
4003 // I * (B / D) mod (N / D)
4004 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4005
4006 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4007 // bits.
4008 return SE.getConstant(Result.trunc(BW));
4009}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004010
4011/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4012/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4013/// might be the same) or two SCEVCouldNotCompute objects.
4014///
Dan Gohman161ea032009-07-07 17:06:11 +00004015static std::pair<const SCEV *,const SCEV *>
Dan Gohman89f85052007-10-22 18:31:58 +00004016SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004017 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004018 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4019 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4020 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004021
4022 // We currently can only solve this if the coefficients are constants.
4023 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004024 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004025 return std::make_pair(CNC, CNC);
4026 }
4027
4028 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4029 const APInt &L = LC->getValue()->getValue();
4030 const APInt &M = MC->getValue()->getValue();
4031 const APInt &N = NC->getValue()->getValue();
4032 APInt Two(BitWidth, 2);
4033 APInt Four(BitWidth, 4);
4034
Dan Gohman9bc642f2009-06-24 04:48:43 +00004035 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004036 using namespace APIntOps;
4037 const APInt& C = L;
4038 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4039 // The B coefficient is M-N/2
4040 APInt B(M);
4041 B -= sdiv(N,Two);
4042
4043 // The A coefficient is N/2
4044 APInt A(N.sdiv(Two));
4045
4046 // Compute the B^2-4ac term.
4047 APInt SqrtTerm(B);
4048 SqrtTerm *= B;
4049 SqrtTerm -= Four * (A * C);
4050
4051 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4052 // integer value or else APInt::sqrt() will assert.
4053 APInt SqrtVal(SqrtTerm.sqrt());
4054
Dan Gohman9bc642f2009-06-24 04:48:43 +00004055 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056 // The divisions must be performed as signed divisions.
4057 APInt NegB(-B);
4058 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00004059 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004060 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00004061 return std::make_pair(CNC, CNC);
4062 }
4063
Owen Andersone755b092009-07-06 22:37:39 +00004064 LLVMContext *Context = SE.getContext();
4065
4066 ConstantInt *Solution1 =
4067 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4068 ConstantInt *Solution2 =
4069 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070
Dan Gohman9bc642f2009-06-24 04:48:43 +00004071 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00004072 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004073 } // end APIntOps namespace
4074}
4075
4076/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00004077/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman161ea032009-07-07 17:06:11 +00004078const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004079 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00004080 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004081 // If the value is already zero, the branch will execute zero times.
4082 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004083 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 }
4085
Dan Gohmanbff6b582009-05-04 22:30:44 +00004086 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004087 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004088 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089
4090 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004091 // If this is an affine expression, the execution count of this branch is
4092 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004094 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004095 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004096 // equivalent to:
4097 //
4098 // Step*N = -Start (mod 2^BW)
4099 //
4100 // where BW is the common bit width of Start and Step.
4101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004102 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004103 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4104 L->getParentLoop());
4105 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4106 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004107
Dan Gohmanc76b5452009-05-04 22:02:23 +00004108 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004109 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004110
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004111 // First, handle unitary steps.
4112 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004113 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004114 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4115 return Start; // N = Start (as unsigned)
4116
4117 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004118 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004119 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004120 -StartC->getValue()->getValue(),
4121 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004122 }
4123 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4124 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4125 // the quadratic equation to solve it.
Dan Gohman161ea032009-07-07 17:06:11 +00004126 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004127 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004128 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4129 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004130 if (R1) {
4131#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00004132 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4133 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004134#endif
4135 // Pick the smallest positive root value.
4136 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004137 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004138 R1->getValue(), R2->getValue()))) {
4139 if (CB->getZExtValue() == false)
4140 std::swap(R1, R2); // R1 is the minimum root now.
4141
4142 // We can only use this value if the chrec ends up with an exact zero
4143 // value at this index. When solving for "X*X != 5", for example, we
4144 // should not accept a root of 2.
Dan Gohman161ea032009-07-07 17:06:11 +00004145 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00004146 if (Val->isZero())
4147 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004148 }
4149 }
4150 }
4151
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004152 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004153}
4154
4155/// HowFarToNonZero - Return the number of times a backedge checking the
4156/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004157/// CouldNotCompute
Dan Gohman161ea032009-07-07 17:06:11 +00004158const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004159 // Loops that look like: while (X == 0) are very strange indeed. We don't
4160 // handle them yet except for the trivial case. This could be expanded in the
4161 // future as needed.
4162
4163 // If the value is a constant, check to see if it is known to be non-zero
4164 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004165 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00004166 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004167 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004168 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004169 }
4170
4171 // We could implement others, but I really doubt anyone writes loops like
4172 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004173 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004174}
4175
Dan Gohmanab157b22009-05-18 15:36:09 +00004176/// getLoopPredecessor - If the given loop's header has exactly one unique
4177/// predecessor outside the loop, return it. Otherwise return null.
4178///
4179BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4180 BasicBlock *Header = L->getHeader();
4181 BasicBlock *Pred = 0;
4182 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4183 PI != E; ++PI)
4184 if (!L->contains(*PI)) {
4185 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4186 Pred = *PI;
4187 }
4188 return Pred;
4189}
4190
Dan Gohman1cddf972008-09-15 22:18:04 +00004191/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4192/// (which may not be an immediate predecessor) which has exactly one
4193/// successor from which BB is reachable, or null if no such block is
4194/// found.
4195///
4196BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004197ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00004198 // If the block has a unique predecessor, then there is no path from the
4199 // predecessor to the block that does not go through the direct edge
4200 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00004201 if (BasicBlock *Pred = BB->getSinglePredecessor())
4202 return Pred;
4203
4204 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00004205 // If the header has a unique predecessor outside the loop, it must be
4206 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004207 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00004208 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00004209
4210 return 0;
4211}
4212
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004213/// HasSameValue - SCEV structural equivalence is usually sufficient for
4214/// testing whether two expressions are equal, however for the purposes of
4215/// looking for a condition guarding a loop, it can be useful to be a little
4216/// more general, since a front-end may have replicated the controlling
4217/// expression.
4218///
Dan Gohman161ea032009-07-07 17:06:11 +00004219static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004220 // Quick check to see if they are the same SCEV.
4221 if (A == B) return true;
4222
4223 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4224 // two different instructions with the same value. Check for this case.
4225 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4226 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4227 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4228 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4229 if (AI->isIdenticalTo(BI))
4230 return true;
4231
4232 // Otherwise assume they may have a different value.
4233 return false;
4234}
4235
Dan Gohman232756f2009-07-10 16:42:52 +00004236bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4237 return getSignedRange(S).getSignedMax().isNegative();
4238}
4239
4240bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4241 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4242}
4243
4244bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4245 return !getSignedRange(S).getSignedMin().isNegative();
4246}
4247
4248bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4249 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4250}
4251
4252bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4253 return isKnownNegative(S) || isKnownPositive(S);
4254}
4255
4256bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4257 const SCEV *LHS, const SCEV *RHS) {
4258
4259 if (HasSameValue(LHS, RHS))
4260 return ICmpInst::isTrueWhenEqual(Pred);
4261
4262 switch (Pred) {
4263 default:
Edwin Török675d5622009-07-11 20:10:48 +00004264 LLVM_UNREACHABLE("Unexpected ICmpInst::Predicate value!");
Dan Gohman232756f2009-07-10 16:42:52 +00004265 break;
4266 case ICmpInst::ICMP_SGT:
4267 Pred = ICmpInst::ICMP_SLT;
4268 std::swap(LHS, RHS);
4269 case ICmpInst::ICMP_SLT: {
4270 ConstantRange LHSRange = getSignedRange(LHS);
4271 ConstantRange RHSRange = getSignedRange(RHS);
4272 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4273 return true;
4274 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4275 return false;
4276
4277 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4278 ConstantRange DiffRange = getUnsignedRange(Diff);
4279 if (isKnownNegative(Diff)) {
4280 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4281 return true;
4282 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4283 return false;
4284 } else if (isKnownPositive(Diff)) {
4285 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4286 return true;
4287 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4288 return false;
4289 }
4290 break;
4291 }
4292 case ICmpInst::ICMP_SGE:
4293 Pred = ICmpInst::ICMP_SLE;
4294 std::swap(LHS, RHS);
4295 case ICmpInst::ICMP_SLE: {
4296 ConstantRange LHSRange = getSignedRange(LHS);
4297 ConstantRange RHSRange = getSignedRange(RHS);
4298 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4299 return true;
4300 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4301 return false;
4302
4303 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4304 ConstantRange DiffRange = getUnsignedRange(Diff);
4305 if (isKnownNonPositive(Diff)) {
4306 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4307 return true;
4308 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4309 return false;
4310 } else if (isKnownNonNegative(Diff)) {
4311 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4312 return true;
4313 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4314 return false;
4315 }
4316 break;
4317 }
4318 case ICmpInst::ICMP_UGT:
4319 Pred = ICmpInst::ICMP_ULT;
4320 std::swap(LHS, RHS);
4321 case ICmpInst::ICMP_ULT: {
4322 ConstantRange LHSRange = getUnsignedRange(LHS);
4323 ConstantRange RHSRange = getUnsignedRange(RHS);
4324 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4325 return true;
4326 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4327 return false;
4328
4329 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4330 ConstantRange DiffRange = getUnsignedRange(Diff);
4331 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4332 return true;
4333 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4334 return false;
4335 break;
4336 }
4337 case ICmpInst::ICMP_UGE:
4338 Pred = ICmpInst::ICMP_ULE;
4339 std::swap(LHS, RHS);
4340 case ICmpInst::ICMP_ULE: {
4341 ConstantRange LHSRange = getUnsignedRange(LHS);
4342 ConstantRange RHSRange = getUnsignedRange(RHS);
4343 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4344 return true;
4345 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4346 return false;
4347
4348 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4349 ConstantRange DiffRange = getUnsignedRange(Diff);
4350 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4351 return true;
4352 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4353 return false;
4354 break;
4355 }
4356 case ICmpInst::ICMP_NE: {
4357 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4358 return true;
4359 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4360 return true;
4361
4362 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4363 if (isKnownNonZero(Diff))
4364 return true;
4365 break;
4366 }
4367 case ICmpInst::ICMP_EQ:
4368 break;
4369 }
4370 return false;
4371}
4372
4373/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4374/// protected by a conditional between LHS and RHS. This is used to
4375/// to eliminate casts.
4376bool
4377ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4378 ICmpInst::Predicate Pred,
4379 const SCEV *LHS, const SCEV *RHS) {
4380 // Interpret a null as meaning no loop, where there is obviously no guard
4381 // (interprocedural conditions notwithstanding).
4382 if (!L) return true;
4383
4384 BasicBlock *Latch = L->getLoopLatch();
4385 if (!Latch)
4386 return false;
4387
4388 BranchInst *LoopContinuePredicate =
4389 dyn_cast<BranchInst>(Latch->getTerminator());
4390 if (!LoopContinuePredicate ||
4391 LoopContinuePredicate->isUnconditional())
4392 return false;
4393
4394 return
4395 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4396 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4397}
4398
4399/// isLoopGuardedByCond - Test whether entry to the loop is protected
4400/// by a conditional between LHS and RHS. This is used to help avoid max
4401/// expressions in loop trip counts, and to eliminate casts.
4402bool
4403ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4404 ICmpInst::Predicate Pred,
4405 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004406 // Interpret a null as meaning no loop, where there is obviously no guard
4407 // (interprocedural conditions notwithstanding).
4408 if (!L) return false;
4409
Dan Gohmanab157b22009-05-18 15:36:09 +00004410 BasicBlock *Predecessor = getLoopPredecessor(L);
4411 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004412
Dan Gohmanab157b22009-05-18 15:36:09 +00004413 // Starting at the loop predecessor, climb up the predecessor chain, as long
4414 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004415 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004416 for (; Predecessor;
4417 PredecessorDest = Predecessor,
4418 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004419
4420 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004421 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004422 if (!LoopEntryPredicate ||
4423 LoopEntryPredicate->isUnconditional())
4424 continue;
4425
Dan Gohman423ed6c2009-06-24 01:18:18 +00004426 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4427 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004428 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004429 }
4430
Dan Gohmanab678fb2008-08-12 20:17:31 +00004431 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004432}
4433
Dan Gohman232756f2009-07-10 16:42:52 +00004434/// isNecessaryCond - Test whether the condition described by Pred, LHS,
4435/// and RHS is a necessary condition for the given Cond value to evaluate
4436/// to true.
Dan Gohman423ed6c2009-06-24 01:18:18 +00004437bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4438 ICmpInst::Predicate Pred,
4439 const SCEV *LHS, const SCEV *RHS,
4440 bool Inverse) {
4441 // Recursivly handle And and Or conditions.
4442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4443 if (BO->getOpcode() == Instruction::And) {
4444 if (!Inverse)
4445 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4446 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4447 } else if (BO->getOpcode() == Instruction::Or) {
4448 if (Inverse)
4449 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4450 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4451 }
4452 }
4453
4454 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4455 if (!ICI) return false;
4456
4457 // Now that we found a conditional branch that dominates the loop, check to
4458 // see if it is the comparison we are looking for.
4459 Value *PreCondLHS = ICI->getOperand(0);
4460 Value *PreCondRHS = ICI->getOperand(1);
Dan Gohman232756f2009-07-10 16:42:52 +00004461 ICmpInst::Predicate FoundPred;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004462 if (Inverse)
Dan Gohman232756f2009-07-10 16:42:52 +00004463 FoundPred = ICI->getInversePredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004464 else
Dan Gohman232756f2009-07-10 16:42:52 +00004465 FoundPred = ICI->getPredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004466
Dan Gohman232756f2009-07-10 16:42:52 +00004467 if (FoundPred == Pred)
Dan Gohman423ed6c2009-06-24 01:18:18 +00004468 ; // An exact match.
Dan Gohman232756f2009-07-10 16:42:52 +00004469 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4470 // The actual condition is beyond sufficient.
4471 FoundPred = ICmpInst::ICMP_NE;
4472 // NE is symmetric but the original comparison may not be. Swap
4473 // the operands if necessary so that they match below.
4474 if (isa<SCEVConstant>(LHS))
4475 std::swap(PreCondLHS, PreCondRHS);
4476 } else
Dan Gohman423ed6c2009-06-24 01:18:18 +00004477 // Check a few special cases.
Dan Gohman232756f2009-07-10 16:42:52 +00004478 switch (FoundPred) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00004479 case ICmpInst::ICMP_UGT:
4480 if (Pred == ICmpInst::ICMP_ULT) {
4481 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman232756f2009-07-10 16:42:52 +00004482 FoundPred = ICmpInst::ICMP_ULT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004483 break;
4484 }
4485 return false;
4486 case ICmpInst::ICMP_SGT:
4487 if (Pred == ICmpInst::ICMP_SLT) {
4488 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman232756f2009-07-10 16:42:52 +00004489 FoundPred = ICmpInst::ICMP_SLT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004490 break;
4491 }
4492 return false;
4493 case ICmpInst::ICMP_NE:
4494 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4495 // so check for this case by checking if the NE is comparing against
4496 // a minimum or maximum constant.
4497 if (!ICmpInst::isTrueWhenEqual(Pred))
Dan Gohman232756f2009-07-10 16:42:52 +00004498 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4499 const APInt &A = C->getValue()->getValue();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004500 switch (Pred) {
4501 case ICmpInst::ICMP_SLT:
4502 if (A.isMaxSignedValue()) break;
4503 return false;
4504 case ICmpInst::ICMP_SGT:
4505 if (A.isMinSignedValue()) break;
4506 return false;
4507 case ICmpInst::ICMP_ULT:
4508 if (A.isMaxValue()) break;
4509 return false;
4510 case ICmpInst::ICMP_UGT:
4511 if (A.isMinValue()) break;
4512 return false;
4513 default:
4514 return false;
4515 }
Dan Gohman232756f2009-07-10 16:42:52 +00004516 FoundPred = Pred;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004517 // NE is symmetric but the original comparison may not be. Swap
4518 // the operands if necessary so that they match below.
4519 if (isa<SCEVConstant>(LHS))
4520 std::swap(PreCondLHS, PreCondRHS);
4521 break;
4522 }
4523 return false;
4524 default:
4525 // We weren't able to reconcile the condition.
4526 return false;
4527 }
4528
Dan Gohman232756f2009-07-10 16:42:52 +00004529 assert(Pred == FoundPred && "Conditions were not reconciled!");
Dan Gohman423ed6c2009-06-24 01:18:18 +00004530
Dan Gohman232756f2009-07-10 16:42:52 +00004531 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4532 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4533
4534 // Balance the types.
4535 if (getTypeSizeInBits(LHS->getType()) >
4536 getTypeSizeInBits(FoundLHS->getType())) {
4537 if (CmpInst::isSigned(Pred)) {
4538 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4539 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4540 } else {
4541 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4542 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4543 }
4544 } else if (getTypeSizeInBits(LHS->getType()) <
4545 getTypeSizeInBits(FoundLHS->getType())) {
4546 // TODO: Cast LHS and RHS to FoundLHS' type. Currently this can
4547 // result in infinite recursion since the code to construct
4548 // cast expressions may want to know things about the loop
4549 // iteration in order to do simplifications.
4550 return false;
4551 }
4552
4553 return isNecessaryCondOperands(Pred, LHS, RHS,
4554 FoundLHS, FoundRHS) ||
4555 // ~x < ~y --> x > y
4556 isNecessaryCondOperands(Pred, LHS, RHS,
4557 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4558}
4559
4560/// isNecessaryCondOperands - Test whether the condition described by Pred,
4561/// LHS, and RHS is a necessary condition for the condition described by
4562/// Pred, FoundLHS, and FoundRHS to evaluate to true.
4563bool
4564ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4565 const SCEV *LHS, const SCEV *RHS,
4566 const SCEV *FoundLHS,
4567 const SCEV *FoundRHS) {
4568 switch (Pred) {
4569 default: break;
4570 case ICmpInst::ICMP_SLT:
4571 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4572 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4573 return true;
4574 break;
4575 case ICmpInst::ICMP_SGT:
4576 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4577 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4578 return true;
4579 break;
4580 case ICmpInst::ICMP_ULT:
4581 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4582 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4583 return true;
4584 break;
4585 case ICmpInst::ICMP_UGT:
4586 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4587 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4588 return true;
4589 break;
4590 }
4591
4592 return false;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004593}
4594
Dan Gohmand2b62c42009-06-21 23:46:38 +00004595/// getBECount - Subtract the end and start values and divide by the step,
4596/// rounding up, to get the number of times the backedge is executed. Return
4597/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman161ea032009-07-07 17:06:11 +00004598const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4599 const SCEV *End,
4600 const SCEV *Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004601 const Type *Ty = Start->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00004602 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4603 const SCEV *Diff = getMinusSCEV(End, Start);
4604 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004605
4606 // Add an adjustment to the difference between End and Start so that
4607 // the division will effectively round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004608 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004609
4610 // Check Add for unsigned overflow.
4611 // TODO: More sophisticated things could be done here.
Owen Andersone755b092009-07-06 22:37:39 +00004612 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman161ea032009-07-07 17:06:11 +00004613 const SCEV *OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004614 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4615 getZeroExtendExpr(RoundUp, WideTy));
4616 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004617 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004618
4619 return getUDivExpr(Add, Step);
4620}
4621
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004622/// HowManyLessThans - Return the number of times a backedge containing the
4623/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004624/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004625ScalarEvolution::BackedgeTakenInfo
4626ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4627 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004628 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004629 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004630
Dan Gohmanbff6b582009-05-04 22:30:44 +00004631 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004632 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004633 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004634
4635 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004636 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004637 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004638 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004639
4640 // TODO: handle non-constant strides.
4641 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4642 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004643 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004644 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004645 // With unit stride, the iteration never steps past the limit value.
4646 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4647 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4648 // Test whether a positive iteration iteration can step past the limit
4649 // value and past the maximum value for its type in a single step.
4650 if (isSigned) {
4651 APInt Max = APInt::getSignedMaxValue(BitWidth);
4652 if ((Max - CStep->getValue()->getValue())
4653 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004654 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004655 } else {
4656 APInt Max = APInt::getMaxValue(BitWidth);
4657 if ((Max - CStep->getValue()->getValue())
4658 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004659 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004660 }
4661 } else
4662 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004663 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004664 } else
4665 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004666 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004667
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004668 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4669 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4670 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004671 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004673 // First, we get the value of the LHS in the first iteration: n
Dan Gohman161ea032009-07-07 17:06:11 +00004674 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004675
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004676 // Determine the minimum constant start value.
Dan Gohman232756f2009-07-10 16:42:52 +00004677 const SCEV *MinStart = getConstant(isSigned ?
4678 getSignedRange(Start).getSignedMin() :
4679 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004680
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004681 // If we know that the condition is true in order to enter the loop,
4682 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004683 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4684 // the division must round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004685 const SCEV *End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004686 if (!isLoopGuardedByCond(L,
Dan Gohman232756f2009-07-10 16:42:52 +00004687 isSigned ? ICmpInst::ICMP_SLT :
4688 ICmpInst::ICMP_ULT,
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004689 getMinusSCEV(Start, Step), RHS))
4690 End = isSigned ? getSMaxExpr(RHS, Start)
4691 : getUMaxExpr(RHS, Start);
4692
4693 // Determine the maximum constant end value.
Dan Gohman232756f2009-07-10 16:42:52 +00004694 const SCEV *MaxEnd = getConstant(isSigned ?
4695 getSignedRange(End).getSignedMax() :
4696 getUnsignedRange(End).getUnsignedMax());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004697
4698 // Finally, we subtract these two values and divide, rounding up, to get
4699 // the number of times the backedge is executed.
Dan Gohman161ea032009-07-07 17:06:11 +00004700 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004701
4702 // The maximum backedge count is similar, except using the minimum start
4703 // value and the maximum end value.
Dan Gohman161ea032009-07-07 17:06:11 +00004704 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004705
4706 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004707 }
4708
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004709 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004710}
4711
4712/// getNumIterationsInRange - Return the number of iterations of this loop that
4713/// produce values in the specified constant range. Another way of looking at
4714/// this is that it returns the first iteration number where the value is not in
4715/// the condition, thus computing the exit count. If the iteration count can't
4716/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00004717const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004718 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004719 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004720 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004721
4722 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004724 if (!SC->getValue()->isZero()) {
Dan Gohman161ea032009-07-07 17:06:11 +00004725 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004726 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004727 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004728 if (const SCEVAddRecExpr *ShiftedAddRec =
4729 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004730 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004731 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004732 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004733 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004734 }
4735
4736 // The only time we can solve this is when we have all constant indices.
4737 // Otherwise, we cannot determine the overflow conditions.
4738 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4739 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004740 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004741
4742
4743 // Okay at this point we know that all elements of the chrec are constants and
4744 // that the start element is zero.
4745
4746 // First check to see if the range contains zero. If not, the first
4747 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004748 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004749 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004750 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751
4752 if (isAffine()) {
4753 // If this is an affine expression then we have this situation:
4754 // Solve {0,+,A} in Range === Ax in Range
4755
4756 // We know that zero is in the range. If A is positive then we know that
4757 // the upper value of the range must be the first possible exit value.
4758 // If A is negative then the lower of the range is the last possible loop
4759 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004760 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004761 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4762 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4763
4764 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004765 APInt ExitVal = (End + A).udiv(A);
Owen Andersone755b092009-07-06 22:37:39 +00004766 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004767
4768 // Evaluate at the exit value. If we really did fall out of the valid
4769 // range, then we computed our trip count, otherwise wrap around or other
4770 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004771 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004773 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004774
4775 // Ensure that the previous value is in the range. This is a sanity check.
4776 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004777 EvaluateConstantChrecAtConstant(this,
Owen Andersone755b092009-07-06 22:37:39 +00004778 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004779 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004780 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781 } else if (isQuadratic()) {
4782 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4783 // quadratic equation to solve it. To do this, we must frame our problem in
4784 // terms of figuring out when zero is crossed, instead of when
4785 // Range.getUpper() is crossed.
Dan Gohman161ea032009-07-07 17:06:11 +00004786 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004787 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman161ea032009-07-07 17:06:11 +00004788 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004789
4790 // Next, solve the constructed addrec
Dan Gohman161ea032009-07-07 17:06:11 +00004791 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004792 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004793 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4794 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004795 if (R1) {
4796 // Pick the smallest positive root value.
4797 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004798 dyn_cast<ConstantInt>(
4799 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4800 R1->getValue(), R2->getValue()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004801 if (CB->getZExtValue() == false)
4802 std::swap(R1, R2); // R1 is the minimum root now.
4803
4804 // Make sure the root is not off by one. The returned iteration should
4805 // not be in the range, but the previous one should be. When solving
4806 // for "X*X < 5", for example, we should not return a root of 2.
4807 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004808 R1->getValue(),
4809 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004810 if (Range.contains(R1Val->getValue())) {
4811 // The next iteration must be out of the range...
Owen Andersone755b092009-07-06 22:37:39 +00004812 ConstantInt *NextVal =
4813 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004814
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()))
Dan Gohman89f85052007-10-22 18:31:58 +00004817 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004818 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004819 }
4820
4821 // If R1 was not in the range, then it is a good return value. Make
4822 // sure that R1-1 WAS in the range though, just in case.
Owen Andersone755b092009-07-06 22:37:39 +00004823 ConstantInt *NextVal =
4824 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004825 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004826 if (Range.contains(R1Val->getValue()))
4827 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004828 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004829 }
4830 }
4831 }
4832
Dan Gohman0ad08b02009-04-18 17:58:19 +00004833 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834}
4835
4836
4837
4838//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004839// SCEVCallbackVH Class Implementation
4840//===----------------------------------------------------------------------===//
4841
Dan Gohman999d14e2009-05-19 19:22:47 +00004842void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004843 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4844 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4845 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004846 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4847 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004848 SE->Scalars.erase(getValPtr());
4849 // this now dangles!
4850}
4851
Dan Gohman999d14e2009-05-19 19:22:47 +00004852void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004853 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4854
4855 // Forget all the expressions associated with users of the old value,
4856 // so that future queries will recompute the expressions using the new
4857 // value.
4858 SmallVector<User *, 16> Worklist;
4859 Value *Old = getValPtr();
4860 bool DeleteOld = false;
4861 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4862 UI != UE; ++UI)
4863 Worklist.push_back(*UI);
4864 while (!Worklist.empty()) {
4865 User *U = Worklist.pop_back_val();
4866 // Deleting the Old value will cause this to dangle. Postpone
4867 // that until everything else is done.
4868 if (U == Old) {
4869 DeleteOld = true;
4870 continue;
4871 }
4872 if (PHINode *PN = dyn_cast<PHINode>(U))
4873 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004874 if (Instruction *I = dyn_cast<Instruction>(U))
4875 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004876 if (SE->Scalars.erase(U))
4877 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4878 UI != UE; ++UI)
4879 Worklist.push_back(*UI);
4880 }
4881 if (DeleteOld) {
4882 if (PHINode *PN = dyn_cast<PHINode>(Old))
4883 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004884 if (Instruction *I = dyn_cast<Instruction>(Old))
4885 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004886 SE->Scalars.erase(Old);
4887 // this now dangles!
4888 }
4889 // this may dangle!
4890}
4891
Dan Gohman999d14e2009-05-19 19:22:47 +00004892ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004893 : CallbackVH(V), SE(se) {}
4894
4895//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004896// ScalarEvolution Class Implementation
4897//===----------------------------------------------------------------------===//
4898
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004899ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004900 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004901}
4902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004903bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004904 this->F = &F;
4905 LI = &getAnalysis<LoopInfo>();
4906 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004907 return false;
4908}
4909
4910void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004911 Scalars.clear();
4912 BackedgeTakenCounts.clear();
4913 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004914 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004915 UniqueSCEVs.clear();
4916 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004917}
4918
4919void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4920 AU.setPreservesAll();
4921 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004922}
4923
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004924bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004925 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004926}
4927
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004928static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004929 const Loop *L) {
4930 // Print all inner loops first
4931 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4932 PrintLoopInfo(OS, SE, *I);
4933
Nick Lewyckye5da1912008-01-02 02:49:20 +00004934 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004935
Devang Patel02451fa2007-08-21 00:31:24 +00004936 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004937 L->getExitBlocks(ExitBlocks);
4938 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004939 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004940
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004941 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4942 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004943 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004944 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004945 }
4946
Nick Lewyckye5da1912008-01-02 02:49:20 +00004947 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004948 OS << "Loop " << L->getHeader()->getName() << ": ";
4949
4950 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4951 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4952 } else {
4953 OS << "Unpredictable max backedge-taken count. ";
4954 }
4955
4956 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004957}
4958
Dan Gohman13058cc2009-04-21 00:47:46 +00004959void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004960 // ScalarEvolution's implementaiton of the print method is to print
4961 // out SCEV values of all instructions that are interesting. Doing
4962 // this potentially causes it to create new SCEV objects though,
4963 // which technically conflicts with the const qualifier. This isn't
Dan Gohmanac2a9d62009-07-10 20:25:29 +00004964 // observable from outside the class though, so casting away the
4965 // const isn't dangerous.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004966 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004967
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004968 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004969 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004970 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004971 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004972 OS << " --> ";
Dan Gohman161ea032009-07-07 17:06:11 +00004973 const SCEV *SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004974 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004975
Dan Gohman8db598a2009-06-19 17:49:54 +00004976 const Loop *L = LI->getLoopFor((*I).getParent());
4977
Dan Gohman161ea032009-07-07 17:06:11 +00004978 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004979 if (AtUse != SV) {
4980 OS << " --> ";
4981 AtUse->print(OS);
4982 }
4983
4984 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004985 OS << "\t\t" "Exits: ";
Dan Gohman161ea032009-07-07 17:06:11 +00004986 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004987 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004988 OS << "<<Unknown>>";
4989 } else {
4990 OS << *ExitValue;
4991 }
4992 }
4993
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004994 OS << "\n";
4995 }
4996
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004997 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4998 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4999 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005000}
Dan Gohman13058cc2009-04-21 00:47:46 +00005001
5002void ScalarEvolution::print(std::ostream &o, const Module *M) const {
5003 raw_os_ostream OS(o);
5004 print(OS, M);
5005}