blob: 62f3aa1dcae4d64f29dc7b10ff0dde8141b9e9ef [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
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 Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/ConstantRange.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000121 print(errs());
122 errs() << '\n';
123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000181 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000182 UniqueSCEVs.InsertNode(S, IP);
183 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman0bba49c2009-07-07 17:06:11 +0000186const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000187 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Dan Gohman0bba49c2009-07-07 17:06:11 +0000190const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000192 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohman6e70e312009-09-27 15:26:03 +0000210bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
212}
213
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000217 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
218 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000229 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
230 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000234void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000241 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
242 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000243 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
Dan Gohmanecb403a2009-05-07 14:00:19 +0000259bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
262 return false;
263 }
264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
270 return false;
271 }
272 return true;
273}
274
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000275bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
277}
278
Dan Gohman6e70e312009-09-27 15:26:03 +0000279bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
281}
282
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000283void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000284 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000285}
286
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294}
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000297 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000298 if (!QueryLoop)
299 return false;
300
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
302 if (QueryLoop->contains(L->getHeader()))
303 return false;
304
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
306 // are variant.
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
309 return false;
310
311 // Otherwise it's loop-invariant.
312 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000313}
314
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000315void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316 OS << "{" << *Operands[0];
317 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
318 OS << ",+," << *Operands[i];
319 OS << "}<" << L->getHeader()->getName() + ">";
320}
Chris Lattner53e677a2004-04-02 20:23:17 +0000321
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000322void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
323 // LLVM struct fields don't have names, so just print the field number.
324 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
325}
326
327void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
328 OS << "sizeof(" << *AllocTy << ")";
329}
330
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
332 // All non-instruction values are loop invariant. All instructions are loop
333 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000334 // Instructions are never considered invariant in the function body
335 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000337 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338 return true;
339}
Chris Lattner53e677a2004-04-02 20:23:17 +0000340
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000341bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
342 if (Instruction *I = dyn_cast<Instruction>(getValue()))
343 return DT->dominates(I->getParent(), BB);
344 return true;
345}
346
Dan Gohman6e70e312009-09-27 15:26:03 +0000347bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
348 if (Instruction *I = dyn_cast<Instruction>(getValue()))
349 return DT->properlyDominates(I->getParent(), BB);
350 return true;
351}
352
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000353const Type *SCEVUnknown::getType() const {
354 return V->getType();
355}
Chris Lattner53e677a2004-04-02 20:23:17 +0000356
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000357void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000358 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000359}
360
Chris Lattner8d741b82004-06-20 06:23:15 +0000361//===----------------------------------------------------------------------===//
362// SCEV Utilities
363//===----------------------------------------------------------------------===//
364
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000365static bool CompareTypes(const Type *A, const Type *B) {
366 if (A->getTypeID() != B->getTypeID())
367 return A->getTypeID() < B->getTypeID();
368 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
369 const IntegerType *BI = cast<IntegerType>(B);
370 return AI->getBitWidth() < BI->getBitWidth();
371 }
372 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
373 const PointerType *BI = cast<PointerType>(B);
374 return CompareTypes(AI->getElementType(), BI->getElementType());
375 }
376 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
377 const ArrayType *BI = cast<ArrayType>(B);
378 if (AI->getNumElements() != BI->getNumElements())
379 return AI->getNumElements() < BI->getNumElements();
380 return CompareTypes(AI->getElementType(), BI->getElementType());
381 }
382 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
383 const VectorType *BI = cast<VectorType>(B);
384 if (AI->getNumElements() != BI->getNumElements())
385 return AI->getNumElements() < BI->getNumElements();
386 return CompareTypes(AI->getElementType(), BI->getElementType());
387 }
388 if (const StructType *AI = dyn_cast<StructType>(A)) {
389 const StructType *BI = cast<StructType>(B);
390 if (AI->getNumElements() != BI->getNumElements())
391 return AI->getNumElements() < BI->getNumElements();
392 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
393 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
394 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
395 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
396 }
397 return false;
398}
399
Chris Lattner8d741b82004-06-20 06:23:15 +0000400namespace {
401 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
402 /// than the complexity of the RHS. This comparator is used to canonicalize
403 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000404 class VISIBILITY_HIDDEN SCEVComplexityCompare {
405 LoopInfo *LI;
406 public:
407 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
408
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000409 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000410 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
411 if (LHS == RHS)
412 return false;
413
Dan Gohman72861302009-05-07 14:39:04 +0000414 // Primarily, sort the SCEVs by their getSCEVType().
415 if (LHS->getSCEVType() != RHS->getSCEVType())
416 return LHS->getSCEVType() < RHS->getSCEVType();
417
418 // Aside from the getSCEVType() ordering, the particular ordering
419 // isn't very important except that it's beneficial to be consistent,
420 // so that (a + b) and (b + a) don't end up as different expressions.
421
422 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
423 // not as complete as it could be.
424 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
425 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
426
Dan Gohman5be18e82009-05-19 02:15:55 +0000427 // Order pointer values after integer values. This helps SCEVExpander
428 // form GEPs.
429 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
430 return false;
431 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
432 return true;
433
Dan Gohman72861302009-05-07 14:39:04 +0000434 // Compare getValueID values.
435 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
436 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
437
438 // Sort arguments by their position.
439 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
440 const Argument *RA = cast<Argument>(RU->getValue());
441 return LA->getArgNo() < RA->getArgNo();
442 }
443
444 // For instructions, compare their loop depth, and their opcode.
445 // This is pretty loose.
446 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
447 Instruction *RV = cast<Instruction>(RU->getValue());
448
449 // Compare loop depths.
450 if (LI->getLoopDepth(LV->getParent()) !=
451 LI->getLoopDepth(RV->getParent()))
452 return LI->getLoopDepth(LV->getParent()) <
453 LI->getLoopDepth(RV->getParent());
454
455 // Compare opcodes.
456 if (LV->getOpcode() != RV->getOpcode())
457 return LV->getOpcode() < RV->getOpcode();
458
459 // Compare the number of operands.
460 if (LV->getNumOperands() != RV->getNumOperands())
461 return LV->getNumOperands() < RV->getNumOperands();
462 }
463
464 return false;
465 }
466
Dan Gohman4dfad292009-06-14 22:51:25 +0000467 // Compare constant values.
468 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
469 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000470 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
471 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000472 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
473 }
474
475 // Compare addrec loop depths.
476 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
477 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
478 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
479 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
480 }
Dan Gohman72861302009-05-07 14:39:04 +0000481
482 // Lexicographically compare n-ary expressions.
483 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
484 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
485 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
486 if (i >= RC->getNumOperands())
487 return false;
488 if (operator()(LC->getOperand(i), RC->getOperand(i)))
489 return true;
490 if (operator()(RC->getOperand(i), LC->getOperand(i)))
491 return false;
492 }
493 return LC->getNumOperands() < RC->getNumOperands();
494 }
495
Dan Gohmana6b35e22009-05-07 19:23:21 +0000496 // Lexicographically compare udiv expressions.
497 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
498 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
499 if (operator()(LC->getLHS(), RC->getLHS()))
500 return true;
501 if (operator()(RC->getLHS(), LC->getLHS()))
502 return false;
503 if (operator()(LC->getRHS(), RC->getRHS()))
504 return true;
505 if (operator()(RC->getRHS(), LC->getRHS()))
506 return false;
507 return false;
508 }
509
Dan Gohman72861302009-05-07 14:39:04 +0000510 // Compare cast expressions by operand.
511 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
512 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
513 return operator()(LC->getOperand(), RC->getOperand());
514 }
515
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000516 // Compare offsetof expressions.
517 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
518 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
519 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
520 CompareTypes(RA->getStructType(), LA->getStructType()))
521 return CompareTypes(LA->getStructType(), RA->getStructType());
522 return LA->getFieldNo() < RA->getFieldNo();
523 }
524
525 // Compare sizeof expressions by the allocation type.
526 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
527 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
528 return CompareTypes(LA->getAllocType(), RA->getAllocType());
529 }
530
Torok Edwinc23197a2009-07-14 16:55:14 +0000531 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000532 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000533 }
534 };
535}
536
537/// GroupByComplexity - Given a list of SCEV objects, order them by their
538/// complexity, and group objects of the same complexity together by value.
539/// When this routine is finished, we know that any duplicates in the vector are
540/// consecutive and that complexity is monotonically increasing.
541///
542/// Note that we go take special precautions to ensure that we get determinstic
543/// results from this routine. In other words, we don't want the results of
544/// this to depend on where the addresses of various SCEV objects happened to
545/// land in memory.
546///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000547static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000548 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000549 if (Ops.size() < 2) return; // Noop
550 if (Ops.size() == 2) {
551 // This is the common case, which also happens to be trivially simple.
552 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000553 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000554 std::swap(Ops[0], Ops[1]);
555 return;
556 }
557
558 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000559 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000560
561 // Now that we are sorted by complexity, group elements of the same
562 // complexity. Note that this is, at worst, N^2, but the vector is likely to
563 // be extremely short in practice. Note that we take this approach because we
564 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000565 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000566 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000567 unsigned Complexity = S->getSCEVType();
568
569 // If there are any objects of the same complexity and same value as this
570 // one, group them.
571 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
572 if (Ops[j] == S) { // Found a duplicate.
573 // Move it to immediately after i'th element.
574 std::swap(Ops[i+1], Ops[j]);
575 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000576 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000577 }
578 }
579 }
580}
581
Chris Lattner53e677a2004-04-02 20:23:17 +0000582
Chris Lattner53e677a2004-04-02 20:23:17 +0000583
584//===----------------------------------------------------------------------===//
585// Simple SCEV method implementations
586//===----------------------------------------------------------------------===//
587
Eli Friedmanb42a6262008-08-04 23:49:06 +0000588/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000589/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000590static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000591 ScalarEvolution &SE,
592 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000593 // Handle the simplest case efficiently.
594 if (K == 1)
595 return SE.getTruncateOrZeroExtend(It, ResultTy);
596
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000597 // We are using the following formula for BC(It, K):
598 //
599 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
600 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000601 // Suppose, W is the bitwidth of the return value. We must be prepared for
602 // overflow. Hence, we must assure that the result of our computation is
603 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
604 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000605 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000606 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000607 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000608 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
609 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000610 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000611 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000613 // This formula is trivially equivalent to the previous formula. However,
614 // this formula can be implemented much more efficiently. The trick is that
615 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
616 // arithmetic. To do exact division in modular arithmetic, all we have
617 // to do is multiply by the inverse. Therefore, this step can be done at
618 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000619 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000620 // The next issue is how to safely do the division by 2^T. The way this
621 // is done is by doing the multiplication step at a width of at least W + T
622 // bits. This way, the bottom W+T bits of the product are accurate. Then,
623 // when we perform the division by 2^T (which is equivalent to a right shift
624 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
625 // truncated out after the division by 2^T.
626 //
627 // In comparison to just directly using the first formula, this technique
628 // is much more efficient; using the first formula requires W * K bits,
629 // but this formula less than W + K bits. Also, the first formula requires
630 // a division step, whereas this formula only requires multiplies and shifts.
631 //
632 // It doesn't matter whether the subtraction step is done in the calculation
633 // width or the input iteration count's width; if the subtraction overflows,
634 // the result must be zero anyway. We prefer here to do it in the width of
635 // the induction variable because it helps a lot for certain cases; CodeGen
636 // isn't smart enough to ignore the overflow, which leads to much less
637 // efficient code if the width of the subtraction is wider than the native
638 // register width.
639 //
640 // (It's possible to not widen at all by pulling out factors of 2 before
641 // the multiplication; for example, K=2 can be calculated as
642 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
643 // extra arithmetic, so it's not an obvious win, and it gets
644 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000645
Eli Friedmanb42a6262008-08-04 23:49:06 +0000646 // Protection from insane SCEVs; this bound is conservative,
647 // but it probably doesn't matter.
648 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000649 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000650
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000651 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000652
Eli Friedmanb42a6262008-08-04 23:49:06 +0000653 // Calculate K! / 2^T and T; we divide out the factors of two before
654 // multiplying for calculating K! / 2^T to avoid overflow.
655 // Other overflow doesn't matter because we only care about the bottom
656 // W bits of the result.
657 APInt OddFactorial(W, 1);
658 unsigned T = 1;
659 for (unsigned i = 3; i <= K; ++i) {
660 APInt Mult(W, i);
661 unsigned TwoFactors = Mult.countTrailingZeros();
662 T += TwoFactors;
663 Mult = Mult.lshr(TwoFactors);
664 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000665 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000666
Eli Friedmanb42a6262008-08-04 23:49:06 +0000667 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000668 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000669
670 // Calcuate 2^T, at width T+W.
671 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
672
673 // Calculate the multiplicative inverse of K! / 2^T;
674 // this multiplication factor will perform the exact division by
675 // K! / 2^T.
676 APInt Mod = APInt::getSignedMinValue(W+1);
677 APInt MultiplyFactor = OddFactorial.zext(W+1);
678 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
679 MultiplyFactor = MultiplyFactor.trunc(W);
680
681 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000682 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
683 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000684 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000685 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000686 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000687 Dividend = SE.getMulExpr(Dividend,
688 SE.getTruncateOrZeroExtend(S, CalculationTy));
689 }
690
691 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000692 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000693
694 // Truncate the result, and divide by K! / 2^T.
695
696 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
697 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000698}
699
Chris Lattner53e677a2004-04-02 20:23:17 +0000700/// evaluateAtIteration - Return the value of this chain of recurrences at
701/// the specified iteration number. We can evaluate this recurrence by
702/// multiplying each element in the chain by the binomial coefficient
703/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
704///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000705/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000706///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000707/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000708///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000709const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000710 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000711 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000712 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000713 // The computation is correct in the face of overflow provided that the
714 // multiplication is performed _after_ the evaluation of the binomial
715 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000716 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000717 if (isa<SCEVCouldNotCompute>(Coeff))
718 return Coeff;
719
720 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000721 }
722 return Result;
723}
724
Chris Lattner53e677a2004-04-02 20:23:17 +0000725//===----------------------------------------------------------------------===//
726// SCEV Expression folder implementations
727//===----------------------------------------------------------------------===//
728
Dan Gohman0bba49c2009-07-07 17:06:11 +0000729const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000730 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000731 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000732 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000733 assert(isSCEVable(Ty) &&
734 "This is not a conversion to a SCEVable type!");
735 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000736
Dan Gohmanc050fd92009-07-13 20:50:19 +0000737 FoldingSetNodeID ID;
738 ID.AddInteger(scTruncate);
739 ID.AddPointer(Op);
740 ID.AddPointer(Ty);
741 void *IP = 0;
742 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
743
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000744 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000745 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000746 return getConstant(
747 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000748
Dan Gohman20900ca2009-04-22 16:20:48 +0000749 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000750 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000751 return getTruncateExpr(ST->getOperand(), Ty);
752
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000753 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000754 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000755 return getTruncateOrSignExtend(SS->getOperand(), Ty);
756
757 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000758 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000759 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
760
Dan Gohman6864db62009-06-18 16:24:47 +0000761 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000762 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000763 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000764 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000765 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
766 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000767 }
768
Dan Gohmanc050fd92009-07-13 20:50:19 +0000769 // The cast wasn't folded; create an explicit cast node.
770 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000771 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
772 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000773 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000774 UniqueSCEVs.InsertNode(S, IP);
775 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000776}
777
Dan Gohman0bba49c2009-07-07 17:06:11 +0000778const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000779 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000780 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000781 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000782 assert(isSCEVable(Ty) &&
783 "This is not a conversion to a SCEVable type!");
784 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000785
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000786 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000787 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000788 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000789 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
790 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000791 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000792 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000793
Dan Gohman20900ca2009-04-22 16:20:48 +0000794 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000795 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000796 return getZeroExtendExpr(SZ->getOperand(), Ty);
797
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000798 // Before doing any expensive analysis, check to see if we've already
799 // computed a SCEV for this Op and Ty.
800 FoldingSetNodeID ID;
801 ID.AddInteger(scZeroExtend);
802 ID.AddPointer(Op);
803 ID.AddPointer(Ty);
804 void *IP = 0;
805 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
806
Dan Gohman01ecca22009-04-27 20:16:15 +0000807 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000808 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000809 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000811 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000812 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000813 const SCEV *Start = AR->getStart();
814 const SCEV *Step = AR->getStepRecurrence(*this);
815 unsigned BitWidth = getTypeSizeInBits(AR->getType());
816 const Loop *L = AR->getLoop();
817
Dan Gohmaneb490a72009-07-25 01:22:26 +0000818 // If we have special knowledge that this addrec won't overflow,
819 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000820 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000821 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
822 getZeroExtendExpr(Step, Ty),
823 L);
824
Dan Gohman01ecca22009-04-27 20:16:15 +0000825 // Check whether the backedge-taken count is SCEVCouldNotCompute.
826 // Note that this serves two purposes: It filters out loops that are
827 // simply not analyzable, and it covers the case where this code is
828 // being called from within backedge-taken count analysis, such that
829 // attempting to ask for the backedge-taken count would likely result
830 // in infinite recursion. In the later case, the analysis code will
831 // cope with a conservative value, and it will take care to purge
832 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000833 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000834 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000835 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000836 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000837
838 // Check whether the backedge-taken count can be losslessly casted to
839 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000841 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000842 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000843 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
844 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000845 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000846 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000847 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000848 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000849 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000850 const SCEV *Add = getAddExpr(Start, ZMul);
851 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000852 getAddExpr(getZeroExtendExpr(Start, WideTy),
853 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
854 getZeroExtendExpr(Step, WideTy)));
855 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000856 // Return the expression with the addrec on the outside.
857 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
858 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000859 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000860
861 // Similar to above, only this time treat the step value as signed.
862 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000863 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000864 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000865 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000866 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000867 OperandExtendedAdd =
868 getAddExpr(getZeroExtendExpr(Start, WideTy),
869 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
870 getSignExtendExpr(Step, WideTy)));
871 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000872 // Return the expression with the addrec on the outside.
873 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
874 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000875 L);
876 }
877
878 // If the backedge is guarded by a comparison with the pre-inc value
879 // the addrec is safe. Also, if the entry is guarded by a comparison
880 // with the start value and the backedge is guarded by a comparison
881 // with the post-inc value, the addrec is safe.
882 if (isKnownPositive(Step)) {
883 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
884 getUnsignedRange(Step).getUnsignedMax());
885 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
886 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
887 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
888 AR->getPostIncExpr(*this), N)))
889 // Return the expression with the addrec on the outside.
890 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
891 getZeroExtendExpr(Step, Ty),
892 L);
893 } else if (isKnownNegative(Step)) {
894 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
895 getSignedRange(Step).getSignedMin());
896 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
897 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
898 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
899 AR->getPostIncExpr(*this), N)))
900 // Return the expression with the addrec on the outside.
901 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
902 getSignExtendExpr(Step, Ty),
903 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000904 }
905 }
906 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000907
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000908 // The cast wasn't folded; create an explicit cast node.
909 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000910 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
911 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000912 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000913 UniqueSCEVs.InsertNode(S, IP);
914 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000915}
916
Dan Gohman0bba49c2009-07-07 17:06:11 +0000917const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000918 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000919 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000920 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000921 assert(isSCEVable(Ty) &&
922 "This is not a conversion to a SCEVable type!");
923 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000924
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000925 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000926 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000927 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000928 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
929 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000930 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000931 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000932
Dan Gohman20900ca2009-04-22 16:20:48 +0000933 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000934 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000935 return getSignExtendExpr(SS->getOperand(), Ty);
936
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000937 // Before doing any expensive analysis, check to see if we've already
938 // computed a SCEV for this Op and Ty.
939 FoldingSetNodeID ID;
940 ID.AddInteger(scSignExtend);
941 ID.AddPointer(Op);
942 ID.AddPointer(Ty);
943 void *IP = 0;
944 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
945
Dan Gohman01ecca22009-04-27 20:16:15 +0000946 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000947 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000948 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000949 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000950 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000951 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000952 const SCEV *Start = AR->getStart();
953 const SCEV *Step = AR->getStepRecurrence(*this);
954 unsigned BitWidth = getTypeSizeInBits(AR->getType());
955 const Loop *L = AR->getLoop();
956
Dan Gohmaneb490a72009-07-25 01:22:26 +0000957 // If we have special knowledge that this addrec won't overflow,
958 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000959 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000960 return getAddRecExpr(getSignExtendExpr(Start, Ty),
961 getSignExtendExpr(Step, Ty),
962 L);
963
Dan Gohman01ecca22009-04-27 20:16:15 +0000964 // Check whether the backedge-taken count is SCEVCouldNotCompute.
965 // Note that this serves two purposes: It filters out loops that are
966 // simply not analyzable, and it covers the case where this code is
967 // being called from within backedge-taken count analysis, such that
968 // attempting to ask for the backedge-taken count would likely result
969 // in infinite recursion. In the later case, the analysis code will
970 // cope with a conservative value, and it will take care to purge
971 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000972 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000973 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000974 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000975 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000976
977 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000978 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000979 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000980 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000981 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000982 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
983 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000984 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000985 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000986 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000987 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000988 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000989 const SCEV *Add = getAddExpr(Start, SMul);
990 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000991 getAddExpr(getSignExtendExpr(Start, WideTy),
992 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
993 getSignExtendExpr(Step, WideTy)));
994 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000995 // Return the expression with the addrec on the outside.
996 return getAddRecExpr(getSignExtendExpr(Start, Ty),
997 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000998 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000999
1000 // Similar to above, only this time treat the step value as unsigned.
1001 // This covers loops that count up with an unsigned step.
1002 const SCEV *UMul =
1003 getMulExpr(CastedMaxBECount,
1004 getTruncateOrZeroExtend(Step, Start->getType()));
1005 Add = getAddExpr(Start, UMul);
1006 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001007 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001008 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1009 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001010 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001011 // Return the expression with the addrec on the outside.
1012 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1013 getZeroExtendExpr(Step, Ty),
1014 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001015 }
1016
1017 // If the backedge is guarded by a comparison with the pre-inc value
1018 // the addrec is safe. Also, if the entry is guarded by a comparison
1019 // with the start value and the backedge is guarded by a comparison
1020 // with the post-inc value, the addrec is safe.
1021 if (isKnownPositive(Step)) {
1022 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1023 getSignedRange(Step).getSignedMax());
1024 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1025 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1026 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1027 AR->getPostIncExpr(*this), N)))
1028 // Return the expression with the addrec on the outside.
1029 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1030 getSignExtendExpr(Step, Ty),
1031 L);
1032 } else if (isKnownNegative(Step)) {
1033 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1034 getSignedRange(Step).getSignedMin());
1035 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1036 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1037 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1038 AR->getPostIncExpr(*this), N)))
1039 // Return the expression with the addrec on the outside.
1040 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1041 getSignExtendExpr(Step, Ty),
1042 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001043 }
1044 }
1045 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001046
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001047 // The cast wasn't folded; create an explicit cast node.
1048 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001049 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1050 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001051 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001052 UniqueSCEVs.InsertNode(S, IP);
1053 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001054}
1055
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001056/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1057/// unspecified bits out to the given type.
1058///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001059const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001060 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001061 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1062 "This is not an extending conversion!");
1063 assert(isSCEVable(Ty) &&
1064 "This is not a conversion to a SCEVable type!");
1065 Ty = getEffectiveSCEVType(Ty);
1066
1067 // Sign-extend negative constants.
1068 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1069 if (SC->getValue()->getValue().isNegative())
1070 return getSignExtendExpr(Op, Ty);
1071
1072 // Peel off a truncate cast.
1073 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001074 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001075 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1076 return getAnyExtendExpr(NewOp, Ty);
1077 return getTruncateOrNoop(NewOp, Ty);
1078 }
1079
1080 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001081 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001082 if (!isa<SCEVZeroExtendExpr>(ZExt))
1083 return ZExt;
1084
1085 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001086 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001087 if (!isa<SCEVSignExtendExpr>(SExt))
1088 return SExt;
1089
1090 // If the expression is obviously signed, use the sext cast value.
1091 if (isa<SCEVSMaxExpr>(Op))
1092 return SExt;
1093
1094 // Absent any other information, use the zext cast value.
1095 return ZExt;
1096}
1097
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001098/// CollectAddOperandsWithScales - Process the given Ops list, which is
1099/// a list of operands to be added under the given scale, update the given
1100/// map. This is a helper function for getAddRecExpr. As an example of
1101/// what it does, given a sequence of operands that would form an add
1102/// expression like this:
1103///
1104/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1105///
1106/// where A and B are constants, update the map with these values:
1107///
1108/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1109///
1110/// and add 13 + A*B*29 to AccumulatedConstant.
1111/// This will allow getAddRecExpr to produce this:
1112///
1113/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1114///
1115/// This form often exposes folding opportunities that are hidden in
1116/// the original operand list.
1117///
1118/// Return true iff it appears that any interesting folding opportunities
1119/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1120/// the common case where no interesting opportunities are present, and
1121/// is also used as a check to avoid infinite recursion.
1122///
1123static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001124CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1125 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001126 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001127 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001128 const APInt &Scale,
1129 ScalarEvolution &SE) {
1130 bool Interesting = false;
1131
1132 // Iterate over the add operands.
1133 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1134 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1135 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1136 APInt NewScale =
1137 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1138 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1139 // A multiplication of a constant with another add; recurse.
1140 Interesting |=
1141 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1142 cast<SCEVAddExpr>(Mul->getOperand(1))
1143 ->getOperands(),
1144 NewScale, SE);
1145 } else {
1146 // A multiplication of a constant with some other value. Update
1147 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001148 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1149 const SCEV *Key = SE.getMulExpr(MulOps);
1150 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001151 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001152 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001153 NewOps.push_back(Pair.first->first);
1154 } else {
1155 Pair.first->second += NewScale;
1156 // The map already had an entry for this value, which may indicate
1157 // a folding opportunity.
1158 Interesting = true;
1159 }
1160 }
1161 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1162 // Pull a buried constant out to the outside.
1163 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1164 Interesting = true;
1165 AccumulatedConstant += Scale * C->getValue()->getValue();
1166 } else {
1167 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001168 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001169 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001170 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001171 NewOps.push_back(Pair.first->first);
1172 } else {
1173 Pair.first->second += Scale;
1174 // The map already had an entry for this value, which may indicate
1175 // a folding opportunity.
1176 Interesting = true;
1177 }
1178 }
1179 }
1180
1181 return Interesting;
1182}
1183
1184namespace {
1185 struct APIntCompare {
1186 bool operator()(const APInt &LHS, const APInt &RHS) const {
1187 return LHS.ult(RHS);
1188 }
1189 };
1190}
1191
Dan Gohman6c0866c2009-05-24 23:45:28 +00001192/// getAddExpr - Get a canonical add expression, or something simpler if
1193/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001194const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1195 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001196 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001197 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001198#ifndef NDEBUG
1199 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1200 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1201 getEffectiveSCEVType(Ops[0]->getType()) &&
1202 "SCEVAddExpr operand types don't match!");
1203#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001204
1205 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001206 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001207
1208 // If there are any constants, fold them together.
1209 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001210 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001211 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001212 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001213 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001214 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001215 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1216 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001217 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001218 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001219 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001220 }
1221
1222 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001223 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001224 Ops.erase(Ops.begin());
1225 --Idx;
1226 }
1227 }
1228
Chris Lattner627018b2004-04-07 16:16:11 +00001229 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001230
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 // Okay, check to see if the same value occurs in the operand list twice. If
1232 // so, merge them together into an multiply expression. Since we sorted the
1233 // list, these values are required to be adjacent.
1234 const Type *Ty = Ops[0]->getType();
1235 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1236 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1237 // Found a match, merge the two values into a multiply, and add any
1238 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001239 const SCEV *Two = getIntegerSCEV(2, Ty);
1240 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001241 if (Ops.size() == 2)
1242 return Mul;
1243 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1244 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001245 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001246 }
1247
Dan Gohman728c7f32009-05-08 21:03:19 +00001248 // Check for truncates. If all the operands are truncated from the same
1249 // type, see if factoring out the truncate would permit the result to be
1250 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1251 // if the contents of the resulting outer trunc fold to something simple.
1252 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1253 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1254 const Type *DstType = Trunc->getType();
1255 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001256 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001257 bool Ok = true;
1258 // Check all the operands to see if they can be represented in the
1259 // source type of the truncate.
1260 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1261 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1262 if (T->getOperand()->getType() != SrcType) {
1263 Ok = false;
1264 break;
1265 }
1266 LargeOps.push_back(T->getOperand());
1267 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1268 // This could be either sign or zero extension, but sign extension
1269 // is much more likely to be foldable here.
1270 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1271 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001272 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001273 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1274 if (const SCEVTruncateExpr *T =
1275 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1276 if (T->getOperand()->getType() != SrcType) {
1277 Ok = false;
1278 break;
1279 }
1280 LargeMulOps.push_back(T->getOperand());
1281 } else if (const SCEVConstant *C =
1282 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1283 // This could be either sign or zero extension, but sign extension
1284 // is much more likely to be foldable here.
1285 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1286 } else {
1287 Ok = false;
1288 break;
1289 }
1290 }
1291 if (Ok)
1292 LargeOps.push_back(getMulExpr(LargeMulOps));
1293 } else {
1294 Ok = false;
1295 break;
1296 }
1297 }
1298 if (Ok) {
1299 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001300 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001301 // If it folds to something simple, use it. Otherwise, don't.
1302 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1303 return getTruncateExpr(Fold, DstType);
1304 }
1305 }
1306
1307 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001308 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1309 ++Idx;
1310
1311 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001312 if (Idx < Ops.size()) {
1313 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001314 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001315 // If we have an add, expand the add operands onto the end of the operands
1316 // list.
1317 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1318 Ops.erase(Ops.begin()+Idx);
1319 DeletedAdd = true;
1320 }
1321
1322 // If we deleted at least one add, we added operands to the end of the list,
1323 // and they are not necessarily sorted. Recurse to resort and resimplify
1324 // any operands we just aquired.
1325 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001326 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001327 }
1328
1329 // Skip over the add expression until we get to a multiply.
1330 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1331 ++Idx;
1332
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001333 // Check to see if there are any folding opportunities present with
1334 // operands multiplied by constant values.
1335 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1336 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001337 DenseMap<const SCEV *, APInt> M;
1338 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001339 APInt AccumulatedConstant(BitWidth, 0);
1340 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1341 Ops, APInt(BitWidth, 1), *this)) {
1342 // Some interesting folding opportunity is present, so its worthwhile to
1343 // re-generate the operands list. Group the operands by constant scale,
1344 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001345 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1346 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001347 E = NewOps.end(); I != E; ++I)
1348 MulOpLists[M.find(*I)->second].push_back(*I);
1349 // Re-generate the operands list.
1350 Ops.clear();
1351 if (AccumulatedConstant != 0)
1352 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001353 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1354 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001355 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001356 Ops.push_back(getMulExpr(getConstant(I->first),
1357 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001358 if (Ops.empty())
1359 return getIntegerSCEV(0, Ty);
1360 if (Ops.size() == 1)
1361 return Ops[0];
1362 return getAddExpr(Ops);
1363 }
1364 }
1365
Chris Lattner53e677a2004-04-02 20:23:17 +00001366 // If we are adding something to a multiply expression, make sure the
1367 // something is not already an operand of the multiply. If so, merge it into
1368 // the multiply.
1369 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001370 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001371 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001372 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001373 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001374 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001375 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001376 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 if (Mul->getNumOperands() != 2) {
1378 // If the multiply has more than two operands, we must get the
1379 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001380 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001381 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001382 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001383 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001384 const SCEV *One = getIntegerSCEV(1, Ty);
1385 const SCEV *AddOne = getAddExpr(InnerMul, One);
1386 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001387 if (Ops.size() == 2) return OuterMul;
1388 if (AddOp < Idx) {
1389 Ops.erase(Ops.begin()+AddOp);
1390 Ops.erase(Ops.begin()+Idx-1);
1391 } else {
1392 Ops.erase(Ops.begin()+Idx);
1393 Ops.erase(Ops.begin()+AddOp-1);
1394 }
1395 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001396 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001397 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001398
Chris Lattner53e677a2004-04-02 20:23:17 +00001399 // Check this multiply against other multiplies being added together.
1400 for (unsigned OtherMulIdx = Idx+1;
1401 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1402 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001403 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // If MulOp occurs in OtherMul, we can fold the two multiplies
1405 // together.
1406 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1407 OMulOp != e; ++OMulOp)
1408 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1409 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001410 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001412 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1413 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001414 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001415 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001416 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001417 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001419 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1420 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001421 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001422 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001423 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001424 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1425 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001426 if (Ops.size() == 2) return OuterMul;
1427 Ops.erase(Ops.begin()+Idx);
1428 Ops.erase(Ops.begin()+OtherMulIdx-1);
1429 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001430 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001431 }
1432 }
1433 }
1434 }
1435
1436 // If there are any add recurrences in the operands list, see if any other
1437 // added values are loop invariant. If so, we can fold them into the
1438 // recurrence.
1439 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1440 ++Idx;
1441
1442 // Scan over all recurrences, trying to fold loop invariants into them.
1443 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1444 // Scan all of the other operands to this add and add them to the vector if
1445 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001446 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001447 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001448 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1449 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1450 LIOps.push_back(Ops[i]);
1451 Ops.erase(Ops.begin()+i);
1452 --i; --e;
1453 }
1454
1455 // If we found some loop invariants, fold them into the recurrence.
1456 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001457 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001458 LIOps.push_back(AddRec->getStart());
1459
Dan Gohman0bba49c2009-07-07 17:06:11 +00001460 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001461 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001462 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001463
Dan Gohman0bba49c2009-07-07 17:06:11 +00001464 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 // If all of the other operands were loop invariant, we are done.
1466 if (Ops.size() == 1) return NewRec;
1467
1468 // Otherwise, add the folded AddRec by the non-liv parts.
1469 for (unsigned i = 0;; ++i)
1470 if (Ops[i] == AddRec) {
1471 Ops[i] = NewRec;
1472 break;
1473 }
Dan Gohman246b2562007-10-22 18:31:58 +00001474 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001475 }
1476
1477 // Okay, if there weren't any loop invariants to be folded, check to see if
1478 // there are multiple AddRec's with the same loop induction variable being
1479 // added together. If so, we can fold them.
1480 for (unsigned OtherIdx = Idx+1;
1481 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1482 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001483 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001484 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1485 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001486 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1487 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001488 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1489 if (i >= NewOps.size()) {
1490 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1491 OtherAddRec->op_end());
1492 break;
1493 }
Dan Gohman246b2562007-10-22 18:31:58 +00001494 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001495 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001496 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001497
1498 if (Ops.size() == 2) return NewAddRec;
1499
1500 Ops.erase(Ops.begin()+Idx);
1501 Ops.erase(Ops.begin()+OtherIdx-1);
1502 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001503 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 }
1505 }
1506
1507 // Otherwise couldn't fold anything into this recurrence. Move onto the
1508 // next one.
1509 }
1510
1511 // Okay, it looks like we really DO need an add expr. Check to see if we
1512 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001513 FoldingSetNodeID ID;
1514 ID.AddInteger(scAddExpr);
1515 ID.AddInteger(Ops.size());
1516 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1517 ID.AddPointer(Ops[i]);
1518 void *IP = 0;
1519 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3645b012009-10-09 00:10:36 +00001520 SCEVAddExpr *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001521 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001522 UniqueSCEVs.InsertNode(S, IP);
Dan Gohman3645b012009-10-09 00:10:36 +00001523 if (HasNUW) S->setHasNoUnsignedWrap(true);
1524 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001525 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001526}
1527
1528
Dan Gohman6c0866c2009-05-24 23:45:28 +00001529/// getMulExpr - Get a canonical multiply expression, or something simpler if
1530/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001531const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1532 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001534#ifndef NDEBUG
1535 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1536 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1537 getEffectiveSCEVType(Ops[0]->getType()) &&
1538 "SCEVMulExpr operand types don't match!");
1539#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001540
1541 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001542 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001543
1544 // If there are any constants, fold them together.
1545 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001546 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001547
1548 // C1*(C2+V) -> C1*C2 + C1*V
1549 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001550 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001551 if (Add->getNumOperands() == 2 &&
1552 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001553 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1554 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001555
1556
1557 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001558 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001559 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001560 ConstantInt *Fold = ConstantInt::get(getContext(),
1561 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001562 RHSC->getValue()->getValue());
1563 Ops[0] = getConstant(Fold);
1564 Ops.erase(Ops.begin()+1); // Erase the folded element
1565 if (Ops.size() == 1) return Ops[0];
1566 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 }
1568
1569 // If we are left with a constant one being multiplied, strip it off.
1570 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1571 Ops.erase(Ops.begin());
1572 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001573 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001574 // If we have a multiply of zero, it will always be zero.
1575 return Ops[0];
1576 }
1577 }
1578
1579 // Skip over the add expression until we get to a multiply.
1580 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1581 ++Idx;
1582
1583 if (Ops.size() == 1)
1584 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001585
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 // If there are mul operands inline them all into this expression.
1587 if (Idx < Ops.size()) {
1588 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001589 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 // If we have an mul, expand the mul operands onto the end of the operands
1591 // list.
1592 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1593 Ops.erase(Ops.begin()+Idx);
1594 DeletedMul = true;
1595 }
1596
1597 // If we deleted at least one mul, we added operands to the end of the list,
1598 // and they are not necessarily sorted. Recurse to resort and resimplify
1599 // any operands we just aquired.
1600 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001601 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 }
1603
1604 // If there are any add recurrences in the operands list, see if any other
1605 // added values are loop invariant. If so, we can fold them into the
1606 // recurrence.
1607 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1608 ++Idx;
1609
1610 // Scan over all recurrences, trying to fold loop invariants into them.
1611 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1612 // Scan all of the other operands to this mul and add them to the vector if
1613 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001614 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001615 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001616 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1617 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1618 LIOps.push_back(Ops[i]);
1619 Ops.erase(Ops.begin()+i);
1620 --i; --e;
1621 }
1622
1623 // If we found some loop invariants, fold them into the recurrence.
1624 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001625 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001626 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 NewOps.reserve(AddRec->getNumOperands());
1628 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001629 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001631 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001632 } else {
1633 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001634 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001636 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001637 }
1638 }
1639
Dan Gohman0bba49c2009-07-07 17:06:11 +00001640 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001641
1642 // If all of the other operands were loop invariant, we are done.
1643 if (Ops.size() == 1) return NewRec;
1644
1645 // Otherwise, multiply the folded AddRec by the non-liv parts.
1646 for (unsigned i = 0;; ++i)
1647 if (Ops[i] == AddRec) {
1648 Ops[i] = NewRec;
1649 break;
1650 }
Dan Gohman246b2562007-10-22 18:31:58 +00001651 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001652 }
1653
1654 // Okay, if there weren't any loop invariants to be folded, check to see if
1655 // there are multiple AddRec's with the same loop induction variable being
1656 // multiplied together. If so, we can fold them.
1657 for (unsigned OtherIdx = Idx+1;
1658 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1659 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001660 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001661 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1662 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001663 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001664 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001665 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001666 const SCEV *B = F->getStepRecurrence(*this);
1667 const SCEV *D = G->getStepRecurrence(*this);
1668 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001669 getMulExpr(G, B),
1670 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001671 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001672 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 if (Ops.size() == 2) return NewAddRec;
1674
1675 Ops.erase(Ops.begin()+Idx);
1676 Ops.erase(Ops.begin()+OtherIdx-1);
1677 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001678 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001679 }
1680 }
1681
1682 // Otherwise couldn't fold anything into this recurrence. Move onto the
1683 // next one.
1684 }
1685
1686 // Okay, it looks like we really DO need an mul expr. Check to see if we
1687 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001688 FoldingSetNodeID ID;
1689 ID.AddInteger(scMulExpr);
1690 ID.AddInteger(Ops.size());
1691 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1692 ID.AddPointer(Ops[i]);
1693 void *IP = 0;
1694 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3645b012009-10-09 00:10:36 +00001695 SCEVMulExpr *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001696 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001697 UniqueSCEVs.InsertNode(S, IP);
Dan Gohman3645b012009-10-09 00:10:36 +00001698 if (HasNUW) S->setHasNoUnsignedWrap(true);
1699 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001700 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001701}
1702
Andreas Bolka8a11c982009-08-07 22:55:26 +00001703/// getUDivExpr - Get a canonical unsigned division expression, or something
1704/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001705const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1706 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001707 assert(getEffectiveSCEVType(LHS->getType()) ==
1708 getEffectiveSCEVType(RHS->getType()) &&
1709 "SCEVUDivExpr operand types don't match!");
1710
Dan Gohman622ed672009-05-04 22:02:23 +00001711 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001712 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001713 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001714 if (RHSC->isZero())
1715 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001716
Dan Gohman185cf032009-05-08 20:18:49 +00001717 // Determine if the division can be folded into the operands of
1718 // its operands.
1719 // TODO: Generalize this to non-constants by using known-bits information.
1720 const Type *Ty = LHS->getType();
1721 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1722 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1723 // For non-power-of-two values, effectively round the value up to the
1724 // nearest power of two.
1725 if (!RHSC->getValue()->getValue().isPowerOf2())
1726 ++MaxShiftAmt;
1727 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001728 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001729 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1730 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1731 if (const SCEVConstant *Step =
1732 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1733 if (!Step->getValue()->getValue()
1734 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001735 getZeroExtendExpr(AR, ExtTy) ==
1736 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1737 getZeroExtendExpr(Step, ExtTy),
1738 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001739 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001740 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1741 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1742 return getAddRecExpr(Operands, AR->getLoop());
1743 }
1744 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001745 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001746 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001747 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1748 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1749 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001750 // Find an operand that's safely divisible.
1751 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001752 const SCEV *Op = M->getOperand(i);
1753 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001754 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001755 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1756 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001757 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001758 Operands[i] = Div;
1759 return getMulExpr(Operands);
1760 }
1761 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001762 }
Dan Gohman185cf032009-05-08 20:18:49 +00001763 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001764 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001765 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001766 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1767 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1768 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1769 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001770 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001771 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001772 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1773 break;
1774 Operands.push_back(Op);
1775 }
1776 if (Operands.size() == A->getNumOperands())
1777 return getAddExpr(Operands);
1778 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001779 }
Dan Gohman185cf032009-05-08 20:18:49 +00001780
1781 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001782 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001783 Constant *LHSCV = LHSC->getValue();
1784 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001785 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001786 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001787 }
1788 }
1789
Dan Gohman1c343752009-06-27 21:21:31 +00001790 FoldingSetNodeID ID;
1791 ID.AddInteger(scUDivExpr);
1792 ID.AddPointer(LHS);
1793 ID.AddPointer(RHS);
1794 void *IP = 0;
1795 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1796 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001797 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001798 UniqueSCEVs.InsertNode(S, IP);
1799 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001800}
1801
1802
Dan Gohman6c0866c2009-05-24 23:45:28 +00001803/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1804/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001805const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001806 const SCEV *Step, const Loop *L,
1807 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001808 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001809 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001810 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001811 if (StepChrec->getLoop() == L) {
1812 Operands.insert(Operands.end(), StepChrec->op_begin(),
1813 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001814 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001815 }
1816
1817 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001818 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001819}
1820
Dan Gohman6c0866c2009-05-24 23:45:28 +00001821/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1822/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001823const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001824ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001825 const Loop *L,
1826 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001827 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001828#ifndef NDEBUG
1829 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1830 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1831 getEffectiveSCEVType(Operands[0]->getType()) &&
1832 "SCEVAddRecExpr operand types don't match!");
1833#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001834
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001835 if (Operands.back()->isZero()) {
1836 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001837 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001838 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001839
Dan Gohmand9cc7492008-08-08 18:33:12 +00001840 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001841 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001842 const Loop* NestedLoop = NestedAR->getLoop();
1843 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001844 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001845 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001846 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001847 // AddRecs require their operands be loop-invariant with respect to their
1848 // loops. Don't perform this transformation if it would break this
1849 // requirement.
1850 bool AllInvariant = true;
1851 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1852 if (!Operands[i]->isLoopInvariant(L)) {
1853 AllInvariant = false;
1854 break;
1855 }
1856 if (AllInvariant) {
1857 NestedOperands[0] = getAddRecExpr(Operands, L);
1858 AllInvariant = true;
1859 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1860 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1861 AllInvariant = false;
1862 break;
1863 }
1864 if (AllInvariant)
1865 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00001866 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00001867 }
1868 // Reset Operands to its original state.
1869 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001870 }
1871 }
1872
Dan Gohman1c343752009-06-27 21:21:31 +00001873 FoldingSetNodeID ID;
1874 ID.AddInteger(scAddRecExpr);
1875 ID.AddInteger(Operands.size());
1876 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1877 ID.AddPointer(Operands[i]);
1878 ID.AddPointer(L);
1879 void *IP = 0;
1880 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3645b012009-10-09 00:10:36 +00001881 SCEVAddRecExpr *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001882 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001883 UniqueSCEVs.InsertNode(S, IP);
Dan Gohman3645b012009-10-09 00:10:36 +00001884 if (HasNUW) S->setHasNoUnsignedWrap(true);
1885 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001886 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001887}
1888
Dan Gohman9311ef62009-06-24 14:49:00 +00001889const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1890 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001891 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001892 Ops.push_back(LHS);
1893 Ops.push_back(RHS);
1894 return getSMaxExpr(Ops);
1895}
1896
Dan Gohman0bba49c2009-07-07 17:06:11 +00001897const SCEV *
1898ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001899 assert(!Ops.empty() && "Cannot get empty smax!");
1900 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001901#ifndef NDEBUG
1902 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1903 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1904 getEffectiveSCEVType(Ops[0]->getType()) &&
1905 "SCEVSMaxExpr operand types don't match!");
1906#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001907
1908 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001909 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001910
1911 // If there are any constants, fold them together.
1912 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001913 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001914 ++Idx;
1915 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001916 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001917 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001918 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001919 APIntOps::smax(LHSC->getValue()->getValue(),
1920 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001921 Ops[0] = getConstant(Fold);
1922 Ops.erase(Ops.begin()+1); // Erase the folded element
1923 if (Ops.size() == 1) return Ops[0];
1924 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001925 }
1926
Dan Gohmane5aceed2009-06-24 14:46:22 +00001927 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001928 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1929 Ops.erase(Ops.begin());
1930 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001931 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1932 // If we have an smax with a constant maximum-int, it will always be
1933 // maximum-int.
1934 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001935 }
1936 }
1937
1938 if (Ops.size() == 1) return Ops[0];
1939
1940 // Find the first SMax
1941 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1942 ++Idx;
1943
1944 // Check to see if one of the operands is an SMax. If so, expand its operands
1945 // onto our operand list, and recurse to simplify.
1946 if (Idx < Ops.size()) {
1947 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001948 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001949 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1950 Ops.erase(Ops.begin()+Idx);
1951 DeletedSMax = true;
1952 }
1953
1954 if (DeletedSMax)
1955 return getSMaxExpr(Ops);
1956 }
1957
1958 // Okay, check to see if the same value occurs in the operand list twice. If
1959 // so, delete one. Since we sorted the list, these values are required to
1960 // be adjacent.
1961 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1962 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1963 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1964 --i; --e;
1965 }
1966
1967 if (Ops.size() == 1) return Ops[0];
1968
1969 assert(!Ops.empty() && "Reduced smax down to nothing!");
1970
Nick Lewycky3e630762008-02-20 06:48:22 +00001971 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001972 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001973 FoldingSetNodeID ID;
1974 ID.AddInteger(scSMaxExpr);
1975 ID.AddInteger(Ops.size());
1976 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1977 ID.AddPointer(Ops[i]);
1978 void *IP = 0;
1979 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1980 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001981 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001982 UniqueSCEVs.InsertNode(S, IP);
1983 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001984}
1985
Dan Gohman9311ef62009-06-24 14:49:00 +00001986const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1987 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001988 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001989 Ops.push_back(LHS);
1990 Ops.push_back(RHS);
1991 return getUMaxExpr(Ops);
1992}
1993
Dan Gohman0bba49c2009-07-07 17:06:11 +00001994const SCEV *
1995ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001996 assert(!Ops.empty() && "Cannot get empty umax!");
1997 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001998#ifndef NDEBUG
1999 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2000 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2001 getEffectiveSCEVType(Ops[0]->getType()) &&
2002 "SCEVUMaxExpr operand types don't match!");
2003#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002004
2005 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002006 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002007
2008 // If there are any constants, fold them together.
2009 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002010 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002011 ++Idx;
2012 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002013 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002014 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002015 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002016 APIntOps::umax(LHSC->getValue()->getValue(),
2017 RHSC->getValue()->getValue()));
2018 Ops[0] = getConstant(Fold);
2019 Ops.erase(Ops.begin()+1); // Erase the folded element
2020 if (Ops.size() == 1) return Ops[0];
2021 LHSC = cast<SCEVConstant>(Ops[0]);
2022 }
2023
Dan Gohmane5aceed2009-06-24 14:46:22 +00002024 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002025 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2026 Ops.erase(Ops.begin());
2027 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002028 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2029 // If we have an umax with a constant maximum-int, it will always be
2030 // maximum-int.
2031 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002032 }
2033 }
2034
2035 if (Ops.size() == 1) return Ops[0];
2036
2037 // Find the first UMax
2038 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2039 ++Idx;
2040
2041 // Check to see if one of the operands is a UMax. If so, expand its operands
2042 // onto our operand list, and recurse to simplify.
2043 if (Idx < Ops.size()) {
2044 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002045 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002046 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2047 Ops.erase(Ops.begin()+Idx);
2048 DeletedUMax = true;
2049 }
2050
2051 if (DeletedUMax)
2052 return getUMaxExpr(Ops);
2053 }
2054
2055 // Okay, check to see if the same value occurs in the operand list twice. If
2056 // so, delete one. Since we sorted the list, these values are required to
2057 // be adjacent.
2058 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2059 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2060 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2061 --i; --e;
2062 }
2063
2064 if (Ops.size() == 1) return Ops[0];
2065
2066 assert(!Ops.empty() && "Reduced umax down to nothing!");
2067
2068 // Okay, it looks like we really DO need a umax expr. Check to see if we
2069 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002070 FoldingSetNodeID ID;
2071 ID.AddInteger(scUMaxExpr);
2072 ID.AddInteger(Ops.size());
2073 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2074 ID.AddPointer(Ops[i]);
2075 void *IP = 0;
2076 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2077 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002078 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002079 UniqueSCEVs.InsertNode(S, IP);
2080 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002081}
2082
Dan Gohman9311ef62009-06-24 14:49:00 +00002083const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2084 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002085 // ~smax(~x, ~y) == smin(x, y).
2086 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2087}
2088
Dan Gohman9311ef62009-06-24 14:49:00 +00002089const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2090 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002091 // ~umax(~x, ~y) == umin(x, y)
2092 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2093}
2094
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002095const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2096 unsigned FieldNo) {
2097 // If we have TargetData we can determine the constant offset.
2098 if (TD) {
2099 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2100 const StructLayout &SL = *TD->getStructLayout(STy);
2101 uint64_t Offset = SL.getElementOffset(FieldNo);
2102 return getIntegerSCEV(Offset, IntPtrTy);
2103 }
2104
2105 // Field 0 is always at offset 0.
2106 if (FieldNo == 0) {
2107 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2108 return getIntegerSCEV(0, Ty);
2109 }
2110
2111 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2112 // already have one, otherwise create a new one.
2113 FoldingSetNodeID ID;
2114 ID.AddInteger(scFieldOffset);
2115 ID.AddPointer(STy);
2116 ID.AddInteger(FieldNo);
2117 void *IP = 0;
2118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2119 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2120 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2121 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2122 UniqueSCEVs.InsertNode(S, IP);
2123 return S;
2124}
2125
2126const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2127 // If we have TargetData we can determine the constant size.
2128 if (TD && AllocTy->isSized()) {
2129 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2130 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2131 }
2132
2133 // Expand an array size into the element size times the number
2134 // of elements.
2135 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2136 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2137 return getMulExpr(
2138 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2139 ATy->getNumElements())));
2140 }
2141
2142 // Expand a vector size into the element size times the number
2143 // of elements.
2144 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2145 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2146 return getMulExpr(
2147 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2148 VTy->getNumElements())));
2149 }
2150
2151 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2152 // already have one, otherwise create a new one.
2153 FoldingSetNodeID ID;
2154 ID.AddInteger(scAllocSize);
2155 ID.AddPointer(AllocTy);
2156 void *IP = 0;
2157 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2158 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2159 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2160 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2161 UniqueSCEVs.InsertNode(S, IP);
2162 return S;
2163}
2164
Dan Gohman0bba49c2009-07-07 17:06:11 +00002165const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002166 // Don't attempt to do anything other than create a SCEVUnknown object
2167 // here. createSCEV only calls getUnknown after checking for all other
2168 // interesting possibilities, and any other code that calls getUnknown
2169 // is doing so in order to hide a value from SCEV canonicalization.
2170
Dan Gohman1c343752009-06-27 21:21:31 +00002171 FoldingSetNodeID ID;
2172 ID.AddInteger(scUnknown);
2173 ID.AddPointer(V);
2174 void *IP = 0;
2175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2176 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002177 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002178 UniqueSCEVs.InsertNode(S, IP);
2179 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002180}
2181
Chris Lattner53e677a2004-04-02 20:23:17 +00002182//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002183// Basic SCEV Analysis and PHI Idiom Recognition Code
2184//
2185
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002186/// isSCEVable - Test if values of the given type are analyzable within
2187/// the SCEV framework. This primarily includes integer types, and it
2188/// can optionally include pointer types if the ScalarEvolution class
2189/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002190bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002191 // Integers and pointers are always SCEVable.
2192 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002193}
2194
2195/// getTypeSizeInBits - Return the size in bits of the specified type,
2196/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002197uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002198 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2199
2200 // If we have a TargetData, use it!
2201 if (TD)
2202 return TD->getTypeSizeInBits(Ty);
2203
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002204 // Integer types have fixed sizes.
2205 if (Ty->isInteger())
2206 return Ty->getPrimitiveSizeInBits();
2207
2208 // The only other support type is pointer. Without TargetData, conservatively
2209 // assume pointers are 64-bit.
2210 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2211 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002212}
2213
2214/// getEffectiveSCEVType - Return a type with the same bitwidth as
2215/// the given type and which represents how SCEV will treat the given
2216/// type, for which isSCEVable must return true. For pointer types,
2217/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002218const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002219 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2220
2221 if (Ty->isInteger())
2222 return Ty;
2223
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002224 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002225 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002226 if (TD) return TD->getIntPtrType(getContext());
2227
2228 // Without TargetData, conservatively assume pointers are 64-bit.
2229 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002230}
Chris Lattner53e677a2004-04-02 20:23:17 +00002231
Dan Gohman0bba49c2009-07-07 17:06:11 +00002232const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002233 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002234}
2235
Chris Lattner53e677a2004-04-02 20:23:17 +00002236/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2237/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002238const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002239 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002240
Dan Gohman0bba49c2009-07-07 17:06:11 +00002241 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002242 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002243 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002244 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002245 return S;
2246}
2247
Dan Gohman6bbcba12009-06-24 00:54:57 +00002248/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002249/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002250const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002251 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002252 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002253}
2254
2255/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2256///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002257const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002258 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002259 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002260 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002261
2262 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002263 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002264 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002265 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002266}
2267
2268/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002269const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002270 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002271 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002272 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002273
2274 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002275 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002276 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002277 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002278 return getMinusSCEV(AllOnes, V);
2279}
2280
2281/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2282///
Dan Gohman9311ef62009-06-24 14:49:00 +00002283const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2284 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002285 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002286 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002287}
2288
2289/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2290/// input value to the specified type. If the type must be extended, it is zero
2291/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002292const SCEV *
2293ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002294 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002295 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002296 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2297 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002298 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002299 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002300 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002301 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002302 return getTruncateExpr(V, Ty);
2303 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002304}
2305
2306/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2307/// input value to the specified type. If the type must be extended, it is sign
2308/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002309const SCEV *
2310ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002311 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002312 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002313 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2314 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002315 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002316 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002317 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002318 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002319 return getTruncateExpr(V, Ty);
2320 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002321}
2322
Dan Gohman467c4302009-05-13 03:46:30 +00002323/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2324/// input value to the specified type. If the type must be extended, it is zero
2325/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002326const SCEV *
2327ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002328 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002329 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2330 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002331 "Cannot noop or zero extend with non-integer arguments!");
2332 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2333 "getNoopOrZeroExtend cannot truncate!");
2334 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2335 return V; // No conversion
2336 return getZeroExtendExpr(V, Ty);
2337}
2338
2339/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2340/// input value to the specified type. If the type must be extended, it is sign
2341/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002342const SCEV *
2343ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002344 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002345 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2346 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002347 "Cannot noop or sign extend with non-integer arguments!");
2348 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2349 "getNoopOrSignExtend cannot truncate!");
2350 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2351 return V; // No conversion
2352 return getSignExtendExpr(V, Ty);
2353}
2354
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002355/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2356/// the input value to the specified type. If the type must be extended,
2357/// it is extended with unspecified bits. The conversion must not be
2358/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002359const SCEV *
2360ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002361 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002362 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2363 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002364 "Cannot noop or any extend with non-integer arguments!");
2365 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2366 "getNoopOrAnyExtend cannot truncate!");
2367 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2368 return V; // No conversion
2369 return getAnyExtendExpr(V, Ty);
2370}
2371
Dan Gohman467c4302009-05-13 03:46:30 +00002372/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2373/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002374const SCEV *
2375ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002376 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002377 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2378 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002379 "Cannot truncate or noop with non-integer arguments!");
2380 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2381 "getTruncateOrNoop cannot extend!");
2382 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2383 return V; // No conversion
2384 return getTruncateExpr(V, Ty);
2385}
2386
Dan Gohmana334aa72009-06-22 00:31:57 +00002387/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2388/// the types using zero-extension, and then perform a umax operation
2389/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002390const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2391 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002392 const SCEV *PromotedLHS = LHS;
2393 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002394
2395 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2396 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2397 else
2398 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2399
2400 return getUMaxExpr(PromotedLHS, PromotedRHS);
2401}
2402
Dan Gohmanc9759e82009-06-22 15:03:27 +00002403/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2404/// the types using zero-extension, and then perform a umin operation
2405/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002406const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2407 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002408 const SCEV *PromotedLHS = LHS;
2409 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002410
2411 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2412 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2413 else
2414 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2415
2416 return getUMinExpr(PromotedLHS, PromotedRHS);
2417}
2418
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002419/// PushDefUseChildren - Push users of the given Instruction
2420/// onto the given Worklist.
2421static void
2422PushDefUseChildren(Instruction *I,
2423 SmallVectorImpl<Instruction *> &Worklist) {
2424 // Push the def-use children onto the Worklist stack.
2425 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2426 UI != UE; ++UI)
2427 Worklist.push_back(cast<Instruction>(UI));
2428}
2429
2430/// ForgetSymbolicValue - This looks up computed SCEV values for all
2431/// instructions that depend on the given instruction and removes them from
2432/// the Scalars map if they reference SymName. This is used during PHI
2433/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002434void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002435ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2436 SmallVector<Instruction *, 16> Worklist;
2437 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002438
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002439 SmallPtrSet<Instruction *, 8> Visited;
2440 Visited.insert(I);
2441 while (!Worklist.empty()) {
2442 Instruction *I = Worklist.pop_back_val();
2443 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002444
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002445 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2446 Scalars.find(static_cast<Value *>(I));
2447 if (It != Scalars.end()) {
2448 // Short-circuit the def-use traversal if the symbolic name
2449 // ceases to appear in expressions.
2450 if (!It->second->hasOperand(SymName))
2451 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002452
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002453 // SCEVUnknown for a PHI either means that it has an unrecognized
2454 // structure, or it's a PHI that's in the progress of being computed
2455 // by createNodeForPHI. In the former case, additional loop trip
2456 // count information isn't going to change anything. In the later
2457 // case, createNodeForPHI will perform the necessary updates on its
2458 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002459 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2460 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002461 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002462 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002463 }
2464
2465 PushDefUseChildren(I, Worklist);
2466 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002467}
Chris Lattner53e677a2004-04-02 20:23:17 +00002468
2469/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2470/// a loop header, making it a potential recurrence, or it doesn't.
2471///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002472const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002473 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002474 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002475 if (L->getHeader() == PN->getParent()) {
2476 // If it lives in the loop header, it has two incoming values, one
2477 // from outside the loop, and one from inside.
2478 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2479 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002480
Chris Lattner53e677a2004-04-02 20:23:17 +00002481 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002482 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002483 assert(Scalars.find(PN) == Scalars.end() &&
2484 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002485 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002486
2487 // Using this symbolic name for the PHI, analyze the value coming around
2488 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002489 Value *BEValueV = PN->getIncomingValue(BackEdge);
2490 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002491
2492 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2493 // has a special value for the first iteration of the loop.
2494
2495 // If the value coming around the backedge is an add with the symbolic
2496 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002497 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002498 // If there is a single occurrence of the symbolic value, replace it
2499 // with a recurrence.
2500 unsigned FoundIndex = Add->getNumOperands();
2501 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2502 if (Add->getOperand(i) == SymbolicName)
2503 if (FoundIndex == e) {
2504 FoundIndex = i;
2505 break;
2506 }
2507
2508 if (FoundIndex != Add->getNumOperands()) {
2509 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002510 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002511 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2512 if (i != FoundIndex)
2513 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002514 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002515
2516 // This is not a valid addrec if the step amount is varying each
2517 // loop iteration, but is not itself an addrec in this loop.
2518 if (Accum->isLoopInvariant(L) ||
2519 (isa<SCEVAddRecExpr>(Accum) &&
2520 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002521 const SCEV *StartVal =
2522 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmaneb490a72009-07-25 01:22:26 +00002523 const SCEVAddRecExpr *PHISCEV =
2524 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2525
2526 // If the increment doesn't overflow, then neither the addrec nor the
2527 // post-increment will overflow.
2528 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2529 if (OBO->getOperand(0) == PN &&
2530 getSCEV(OBO->getOperand(1)) ==
2531 PHISCEV->getStepRecurrence(*this)) {
2532 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
Dan Gohman5078f842009-08-20 17:11:38 +00002533 if (OBO->hasNoUnsignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002534 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002535 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002536 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002537 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002538 }
Dan Gohman5078f842009-08-20 17:11:38 +00002539 if (OBO->hasNoSignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002540 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002541 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002542 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002543 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002544 }
2545 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002546
2547 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002548 // to be symbolic. We now need to go back and purge all of the
2549 // entries for the scalars that use the symbolic expression.
2550 ForgetSymbolicName(PN, SymbolicName);
2551 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002552 return PHISCEV;
2553 }
2554 }
Dan Gohman622ed672009-05-04 22:02:23 +00002555 } else if (const SCEVAddRecExpr *AddRec =
2556 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002557 // Otherwise, this could be a loop like this:
2558 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2559 // In this case, j = {1,+,1} and BEValue is j.
2560 // Because the other in-value of i (0) fits the evolution of BEValue
2561 // i really is an addrec evolution.
2562 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002563 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002564
2565 // If StartVal = j.start - j.stride, we can use StartVal as the
2566 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002567 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002568 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002569 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002570 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002571
2572 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002573 // to be symbolic. We now need to go back and purge all of the
2574 // entries for the scalars that use the symbolic expression.
2575 ForgetSymbolicName(PN, SymbolicName);
2576 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002577 return PHISCEV;
2578 }
2579 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002580 }
2581
2582 return SymbolicName;
2583 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002584
Dan Gohmana653fc52009-07-14 14:06:25 +00002585 // It's tempting to recognize PHIs with a unique incoming value, however
2586 // this leads passes like indvars to break LCSSA form. Fortunately, such
2587 // PHIs are rare, as instcombine zaps them.
2588
Chris Lattner53e677a2004-04-02 20:23:17 +00002589 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002590 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002591}
2592
Dan Gohman26466c02009-05-08 20:26:55 +00002593/// createNodeForGEP - Expand GEP instructions into add and multiply
2594/// operations. This allows them to be analyzed by regular SCEV code.
2595///
Dan Gohmanca178902009-07-17 20:47:02 +00002596const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002597
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002598 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002599 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002600 // Don't attempt to analyze GEPs over unsized objects.
2601 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2602 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002603 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002604 gep_type_iterator GTI = gep_type_begin(GEP);
2605 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2606 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002607 I != E; ++I) {
2608 Value *Index = *I;
2609 // Compute the (potentially symbolic) offset in bytes for this index.
2610 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2611 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002612 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002613 TotalOffset = getAddExpr(TotalOffset,
2614 getFieldOffsetExpr(STy, FieldNo));
Dan Gohman26466c02009-05-08 20:26:55 +00002615 } else {
2616 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002617 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002618 if (!isa<PointerType>(LocalOffset->getType()))
2619 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002620 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002621 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI));
Dan Gohman26466c02009-05-08 20:26:55 +00002622 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2623 }
2624 }
2625 return getAddExpr(getSCEV(Base), TotalOffset);
2626}
2627
Nick Lewycky83bb0052007-11-22 07:59:40 +00002628/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2629/// guaranteed to end in (at every loop iteration). It is, at the same time,
2630/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2631/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002632uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002633ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002634 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002635 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002636
Dan Gohman622ed672009-05-04 22:02:23 +00002637 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002638 return std::min(GetMinTrailingZeros(T->getOperand()),
2639 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002640
Dan Gohman622ed672009-05-04 22:02:23 +00002641 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002642 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2643 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2644 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002645 }
2646
Dan Gohman622ed672009-05-04 22:02:23 +00002647 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002648 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2649 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2650 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002651 }
2652
Dan Gohman622ed672009-05-04 22:02:23 +00002653 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002654 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002655 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002656 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002657 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002658 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002659 }
2660
Dan Gohman622ed672009-05-04 22:02:23 +00002661 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002662 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002663 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2664 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002665 for (unsigned i = 1, e = M->getNumOperands();
2666 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002667 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002668 BitWidth);
2669 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002670 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002671
Dan Gohman622ed672009-05-04 22:02:23 +00002672 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002673 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002674 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002675 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002676 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002677 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002678 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002679
Dan Gohman622ed672009-05-04 22:02:23 +00002680 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002681 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002682 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002683 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002684 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002685 return MinOpRes;
2686 }
2687
Dan Gohman622ed672009-05-04 22:02:23 +00002688 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002689 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002690 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002691 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002692 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002693 return MinOpRes;
2694 }
2695
Dan Gohman2c364ad2009-06-19 23:29:04 +00002696 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2697 // For a SCEVUnknown, ask ValueTracking.
2698 unsigned BitWidth = getTypeSizeInBits(U->getType());
2699 APInt Mask = APInt::getAllOnesValue(BitWidth);
2700 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2701 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2702 return Zeros.countTrailingOnes();
2703 }
2704
2705 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002706 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002707}
Chris Lattner53e677a2004-04-02 20:23:17 +00002708
Dan Gohman85b05a22009-07-13 21:35:55 +00002709/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2710///
2711ConstantRange
2712ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002713
2714 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002715 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002716
Dan Gohman85b05a22009-07-13 21:35:55 +00002717 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2718 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2719 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2720 X = X.add(getUnsignedRange(Add->getOperand(i)));
2721 return X;
2722 }
2723
2724 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2725 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2726 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2727 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2728 return X;
2729 }
2730
2731 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2732 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2733 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2734 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2735 return X;
2736 }
2737
2738 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2739 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2740 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2741 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2742 return X;
2743 }
2744
2745 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2746 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2747 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2748 return X.udiv(Y);
2749 }
2750
2751 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2752 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2753 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2754 }
2755
2756 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2757 ConstantRange X = getUnsignedRange(SExt->getOperand());
2758 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2759 }
2760
2761 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2762 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2763 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2764 }
2765
2766 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2767
2768 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2769 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2770 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2771 if (!Trip) return FullSet;
2772
2773 // TODO: non-affine addrec
2774 if (AddRec->isAffine()) {
2775 const Type *Ty = AddRec->getType();
2776 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2777 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2778 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2779
2780 const SCEV *Start = AddRec->getStart();
Dan Gohmana16b5762009-07-21 00:42:47 +00002781 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002782 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2783
2784 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002785 // TODO: This is very conservative.
2786 if (!(Step->isOne() &&
2787 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2788 !(Step->isAllOnesValue() &&
2789 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
Dan Gohman85b05a22009-07-13 21:35:55 +00002790 return FullSet;
2791
2792 ConstantRange StartRange = getUnsignedRange(Start);
2793 ConstantRange EndRange = getUnsignedRange(End);
2794 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2795 EndRange.getUnsignedMin());
2796 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2797 EndRange.getUnsignedMax());
2798 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman0d5bae42009-07-20 22:41:51 +00002799 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002800 return ConstantRange(Min, Max+1);
2801 }
2802 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002803 }
2804
2805 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2806 // For a SCEVUnknown, ask ValueTracking.
2807 unsigned BitWidth = getTypeSizeInBits(U->getType());
2808 APInt Mask = APInt::getAllOnesValue(BitWidth);
2809 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2810 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002811 if (Ones == ~Zeros + 1)
2812 return FullSet;
2813 return ConstantRange(Ones, ~Zeros + 1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002814 }
2815
Dan Gohman85b05a22009-07-13 21:35:55 +00002816 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002817}
2818
Dan Gohman85b05a22009-07-13 21:35:55 +00002819/// getSignedRange - Determine the signed range for a particular SCEV.
2820///
2821ConstantRange
2822ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002823
Dan Gohman85b05a22009-07-13 21:35:55 +00002824 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2825 return ConstantRange(C->getValue()->getValue());
2826
2827 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2828 ConstantRange X = getSignedRange(Add->getOperand(0));
2829 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2830 X = X.add(getSignedRange(Add->getOperand(i)));
2831 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002832 }
2833
Dan Gohman85b05a22009-07-13 21:35:55 +00002834 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2835 ConstantRange X = getSignedRange(Mul->getOperand(0));
2836 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2837 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2838 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002839 }
2840
Dan Gohman85b05a22009-07-13 21:35:55 +00002841 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2842 ConstantRange X = getSignedRange(SMax->getOperand(0));
2843 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2844 X = X.smax(getSignedRange(SMax->getOperand(i)));
2845 return X;
2846 }
Dan Gohman62849c02009-06-24 01:05:09 +00002847
Dan Gohman85b05a22009-07-13 21:35:55 +00002848 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2849 ConstantRange X = getSignedRange(UMax->getOperand(0));
2850 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2851 X = X.umax(getSignedRange(UMax->getOperand(i)));
2852 return X;
2853 }
Dan Gohman62849c02009-06-24 01:05:09 +00002854
Dan Gohman85b05a22009-07-13 21:35:55 +00002855 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2856 ConstantRange X = getSignedRange(UDiv->getLHS());
2857 ConstantRange Y = getSignedRange(UDiv->getRHS());
2858 return X.udiv(Y);
2859 }
Dan Gohman62849c02009-06-24 01:05:09 +00002860
Dan Gohman85b05a22009-07-13 21:35:55 +00002861 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2862 ConstantRange X = getSignedRange(ZExt->getOperand());
2863 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2864 }
2865
2866 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2867 ConstantRange X = getSignedRange(SExt->getOperand());
2868 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2869 }
2870
2871 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2872 ConstantRange X = getSignedRange(Trunc->getOperand());
2873 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2874 }
2875
2876 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2877
2878 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2879 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2880 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2881 if (!Trip) return FullSet;
2882
2883 // TODO: non-affine addrec
2884 if (AddRec->isAffine()) {
2885 const Type *Ty = AddRec->getType();
2886 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2887 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2888 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2889
2890 const SCEV *Start = AddRec->getStart();
2891 const SCEV *Step = AddRec->getStepRecurrence(*this);
2892 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2893
2894 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002895 // TODO: This is very conservative.
2896 if (!(Step->isOne() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002897 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
Dan Gohmana16b5762009-07-21 00:42:47 +00002898 !(Step->isAllOnesValue() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002899 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2900 return FullSet;
2901
2902 ConstantRange StartRange = getSignedRange(Start);
2903 ConstantRange EndRange = getSignedRange(End);
2904 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2905 EndRange.getSignedMin());
2906 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2907 EndRange.getSignedMax());
2908 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmanc268e7c2009-07-21 00:37:45 +00002909 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002910 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002911 }
Dan Gohman62849c02009-06-24 01:05:09 +00002912 }
Dan Gohman62849c02009-06-24 01:05:09 +00002913 }
2914
Dan Gohman2c364ad2009-06-19 23:29:04 +00002915 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2916 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002917 unsigned BitWidth = getTypeSizeInBits(U->getType());
2918 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2919 if (NS == 1)
2920 return FullSet;
2921 return
2922 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2923 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002924 }
2925
Dan Gohman85b05a22009-07-13 21:35:55 +00002926 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002927}
2928
Chris Lattner53e677a2004-04-02 20:23:17 +00002929/// createSCEV - We know that there is no SCEV for the specified value.
2930/// Analyze the expression.
2931///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002932const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002933 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002934 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002935
Dan Gohman6c459a22008-06-22 19:56:46 +00002936 unsigned Opcode = Instruction::UserOp1;
2937 if (Instruction *I = dyn_cast<Instruction>(V))
2938 Opcode = I->getOpcode();
2939 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2940 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002941 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2942 return getConstant(CI);
2943 else if (isa<ConstantPointerNull>(V))
2944 return getIntegerSCEV(0, V->getType());
2945 else if (isa<UndefValue>(V))
2946 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00002947 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
2948 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00002949 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002950 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002951
Dan Gohmanca178902009-07-17 20:47:02 +00002952 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00002953 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00002954 case Instruction::Add:
2955 // Don't transfer the NSW and NUW bits from the Add instruction to the
2956 // Add expression, because the Instruction may be guarded by control
2957 // flow and the no-overflow bits may not be valid for the expression in
2958 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002959 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00002960 getSCEV(U->getOperand(1)));
2961 case Instruction::Mul:
2962 // Don't transfer the NSW and NUW bits from the Mul instruction to the
2963 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002964 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00002965 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002966 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002967 return getUDivExpr(getSCEV(U->getOperand(0)),
2968 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002969 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002970 return getMinusSCEV(getSCEV(U->getOperand(0)),
2971 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002972 case Instruction::And:
2973 // For an expression like x&255 that merely masks off the high bits,
2974 // use zext(trunc(x)) as the SCEV expression.
2975 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002976 if (CI->isNullValue())
2977 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002978 if (CI->isAllOnesValue())
2979 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002980 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002981
2982 // Instcombine's ShrinkDemandedConstant may strip bits out of
2983 // constants, obscuring what would otherwise be a low-bits mask.
2984 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2985 // knew about to reconstruct a low-bits mask value.
2986 unsigned LZ = A.countLeadingZeros();
2987 unsigned BitWidth = A.getBitWidth();
2988 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2989 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2990 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2991
2992 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2993
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002994 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002995 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002996 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00002997 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002998 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002999 }
3000 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003001
Dan Gohman6c459a22008-06-22 19:56:46 +00003002 case Instruction::Or:
3003 // If the RHS of the Or is a constant, we may have something like:
3004 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3005 // optimizations will transparently handle this case.
3006 //
3007 // In order for this transformation to be safe, the LHS must be of the
3008 // form X*(2^n) and the Or constant must be less than 2^n.
3009 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003010 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003011 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003012 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003013 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3014 // Build a plain add SCEV.
3015 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3016 // If the LHS of the add was an addrec and it has no-wrap flags,
3017 // transfer the no-wrap flags, since an or won't introduce a wrap.
3018 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3019 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3020 if (OldAR->hasNoUnsignedWrap())
3021 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3022 if (OldAR->hasNoSignedWrap())
3023 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3024 }
3025 return S;
3026 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003027 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003028 break;
3029 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003030 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003031 // If the RHS of the xor is a signbit, then this is just an add.
3032 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003033 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003034 return getAddExpr(getSCEV(U->getOperand(0)),
3035 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003036
3037 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003038 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003039 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003040
3041 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3042 // This is a variant of the check for xor with -1, and it handles
3043 // the case where instcombine has trimmed non-demanded bits out
3044 // of an xor with -1.
3045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3046 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3047 if (BO->getOpcode() == Instruction::And &&
3048 LCI->getValue() == CI->getValue())
3049 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003050 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003051 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003052 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003053 const Type *Z0Ty = Z0->getType();
3054 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3055
3056 // If C is a low-bits mask, the zero extend is zerving to
3057 // mask off the high bits. Complement the operand and
3058 // re-apply the zext.
3059 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3060 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3061
3062 // If C is a single bit, it may be in the sign-bit position
3063 // before the zero-extend. In this case, represent the xor
3064 // using an add, which is equivalent, and re-apply the zext.
3065 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3066 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3067 Trunc.isSignBit())
3068 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3069 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003070 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003071 }
3072 break;
3073
3074 case Instruction::Shl:
3075 // Turn shift left of a constant amount into a multiply.
3076 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3077 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003078 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003079 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003080 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003081 }
3082 break;
3083
Nick Lewycky01eaf802008-07-07 06:15:49 +00003084 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003085 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003086 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3087 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003088 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003089 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003090 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003091 }
3092 break;
3093
Dan Gohman4ee29af2009-04-21 02:26:00 +00003094 case Instruction::AShr:
3095 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3096 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3097 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3098 if (L->getOpcode() == Instruction::Shl &&
3099 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003100 unsigned BitWidth = getTypeSizeInBits(U->getType());
3101 uint64_t Amt = BitWidth - CI->getZExtValue();
3102 if (Amt == BitWidth)
3103 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3104 if (Amt > BitWidth)
3105 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003106 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003107 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003108 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003109 U->getType());
3110 }
3111 break;
3112
Dan Gohman6c459a22008-06-22 19:56:46 +00003113 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003114 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003115
3116 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003117 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003118
3119 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003120 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003121
3122 case Instruction::BitCast:
3123 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003124 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003125 return getSCEV(U->getOperand(0));
3126 break;
3127
Dan Gohmanf2411742009-07-20 17:43:30 +00003128 // It's tempting to handle inttoptr and ptrtoint, however this can
3129 // lead to pointer expressions which cannot be expanded to GEPs
3130 // (because they may overflow). For now, the only pointer-typed
3131 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00003132
Dan Gohman26466c02009-05-08 20:26:55 +00003133 case Instruction::GetElementPtr:
Dan Gohmanfb791602009-05-08 20:58:38 +00003134 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00003135
Dan Gohman6c459a22008-06-22 19:56:46 +00003136 case Instruction::PHI:
3137 return createNodeForPHI(cast<PHINode>(U));
3138
3139 case Instruction::Select:
3140 // This could be a smax or umax that was lowered earlier.
3141 // Try to recover it.
3142 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3143 Value *LHS = ICI->getOperand(0);
3144 Value *RHS = ICI->getOperand(1);
3145 switch (ICI->getPredicate()) {
3146 case ICmpInst::ICMP_SLT:
3147 case ICmpInst::ICMP_SLE:
3148 std::swap(LHS, RHS);
3149 // fall through
3150 case ICmpInst::ICMP_SGT:
3151 case ICmpInst::ICMP_SGE:
3152 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003153 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003154 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003155 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003156 break;
3157 case ICmpInst::ICMP_ULT:
3158 case ICmpInst::ICMP_ULE:
3159 std::swap(LHS, RHS);
3160 // fall through
3161 case ICmpInst::ICMP_UGT:
3162 case ICmpInst::ICMP_UGE:
3163 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003164 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003165 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003166 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003167 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003168 case ICmpInst::ICMP_NE:
3169 // n != 0 ? n : 1 -> umax(n, 1)
3170 if (LHS == U->getOperand(1) &&
3171 isa<ConstantInt>(U->getOperand(2)) &&
3172 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3173 isa<ConstantInt>(RHS) &&
3174 cast<ConstantInt>(RHS)->isZero())
3175 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3176 break;
3177 case ICmpInst::ICMP_EQ:
3178 // n == 0 ? 1 : n -> umax(n, 1)
3179 if (LHS == U->getOperand(2) &&
3180 isa<ConstantInt>(U->getOperand(1)) &&
3181 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3182 isa<ConstantInt>(RHS) &&
3183 cast<ConstantInt>(RHS)->isZero())
3184 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3185 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003186 default:
3187 break;
3188 }
3189 }
3190
3191 default: // We cannot analyze this expression.
3192 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003193 }
3194
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003195 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003196}
3197
3198
3199
3200//===----------------------------------------------------------------------===//
3201// Iteration Count Computation Code
3202//
3203
Dan Gohman46bdfb02009-02-24 18:55:53 +00003204/// getBackedgeTakenCount - If the specified loop has a predictable
3205/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3206/// object. The backedge-taken count is the number of times the loop header
3207/// will be branched to from within the loop. This is one less than the
3208/// trip count of the loop, since it doesn't count the first iteration,
3209/// when the header is branched to from outside the loop.
3210///
3211/// Note that it is not valid to call this method on a loop without a
3212/// loop-invariant backedge-taken count (see
3213/// hasLoopInvariantBackedgeTakenCount).
3214///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003215const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003216 return getBackedgeTakenInfo(L).Exact;
3217}
3218
3219/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3220/// return the least SCEV value that is known never to be less than the
3221/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003222const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003223 return getBackedgeTakenInfo(L).Max;
3224}
3225
Dan Gohman59ae6b92009-07-08 19:23:34 +00003226/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3227/// onto the given Worklist.
3228static void
3229PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3230 BasicBlock *Header = L->getHeader();
3231
3232 // Push all Loop-header PHIs onto the Worklist stack.
3233 for (BasicBlock::iterator I = Header->begin();
3234 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3235 Worklist.push_back(PN);
3236}
3237
Dan Gohmana1af7572009-04-30 20:47:05 +00003238const ScalarEvolution::BackedgeTakenInfo &
3239ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003240 // Initially insert a CouldNotCompute for this loop. If the insertion
3241 // succeeds, procede to actually compute a backedge-taken count and
3242 // update the value. The temporary CouldNotCompute value tells SCEV
3243 // code elsewhere that it shouldn't attempt to request a new
3244 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003245 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003246 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3247 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003248 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003249 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003250 assert(ItCount.Exact->isLoopInvariant(L) &&
3251 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003252 "Computed trip count isn't loop invariant for loop!");
3253 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003254
Dan Gohman01ecca22009-04-27 20:16:15 +00003255 // Update the value in the map.
3256 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003257 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003258 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003259 // Update the value in the map.
3260 Pair.first->second = ItCount;
3261 if (isa<PHINode>(L->getHeader()->begin()))
3262 // Only count loops that have phi nodes as not being computable.
3263 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003264 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003265
3266 // Now that we know more about the trip count for this loop, forget any
3267 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003268 // conservative estimates made without the benefit of trip count
3269 // information. This is similar to the code in
3270 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3271 // nodes specially.
3272 if (ItCount.hasAnyInfo()) {
3273 SmallVector<Instruction *, 16> Worklist;
3274 PushLoopPHIs(L, Worklist);
3275
3276 SmallPtrSet<Instruction *, 8> Visited;
3277 while (!Worklist.empty()) {
3278 Instruction *I = Worklist.pop_back_val();
3279 if (!Visited.insert(I)) continue;
3280
3281 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3282 Scalars.find(static_cast<Value *>(I));
3283 if (It != Scalars.end()) {
3284 // SCEVUnknown for a PHI either means that it has an unrecognized
3285 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003286 // by createNodeForPHI. In the former case, additional loop trip
3287 // count information isn't going to change anything. In the later
3288 // case, createNodeForPHI will perform the necessary updates on its
3289 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003290 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3291 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003292 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003293 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003294 if (PHINode *PN = dyn_cast<PHINode>(I))
3295 ConstantEvolutionLoopExitValue.erase(PN);
3296 }
3297
3298 PushDefUseChildren(I, Worklist);
3299 }
3300 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003301 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003302 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003303}
3304
Dan Gohman46bdfb02009-02-24 18:55:53 +00003305/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003306/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003307/// ScalarEvolution's ability to compute a trip count, or if the loop
3308/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003309void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003310 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003311
Dan Gohman35738ac2009-05-04 22:30:44 +00003312 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003313 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003314
Dan Gohman59ae6b92009-07-08 19:23:34 +00003315 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003316 while (!Worklist.empty()) {
3317 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003318 if (!Visited.insert(I)) continue;
3319
3320 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3321 Scalars.find(static_cast<Value *>(I));
3322 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003323 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003324 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003325 if (PHINode *PN = dyn_cast<PHINode>(I))
3326 ConstantEvolutionLoopExitValue.erase(PN);
3327 }
3328
3329 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003330 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003331}
3332
Dan Gohman46bdfb02009-02-24 18:55:53 +00003333/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3334/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003335ScalarEvolution::BackedgeTakenInfo
3336ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003337 SmallVector<BasicBlock*, 8> ExitingBlocks;
3338 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003339
Dan Gohmana334aa72009-06-22 00:31:57 +00003340 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003341 const SCEV *BECount = getCouldNotCompute();
3342 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003343 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003344 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3345 BackedgeTakenInfo NewBTI =
3346 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003347
Dan Gohman1c343752009-06-27 21:21:31 +00003348 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003349 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003350 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003351 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003352 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003353 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003354 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003355 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003356 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003357 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003358 }
Dan Gohman1c343752009-06-27 21:21:31 +00003359 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003360 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003361 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003362 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003363 }
3364
3365 return BackedgeTakenInfo(BECount, MaxBECount);
3366}
3367
3368/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3369/// of the specified loop will execute if it exits via the specified block.
3370ScalarEvolution::BackedgeTakenInfo
3371ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3372 BasicBlock *ExitingBlock) {
3373
3374 // Okay, we've chosen an exiting block. See what condition causes us to
3375 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003376 //
3377 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003378 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003379 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003380 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003381
Chris Lattner8b0e3602007-01-07 02:24:26 +00003382 // At this point, we know we have a conditional branch that determines whether
3383 // the loop is exited. However, we don't know if the branch is executed each
3384 // time through the loop. If not, then the execution count of the branch will
3385 // not be equal to the trip count of the loop.
3386 //
3387 // Currently we check for this by checking to see if the Exit branch goes to
3388 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003389 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003390 // loop header. This is common for un-rotated loops.
3391 //
3392 // If both of those tests fail, walk up the unique predecessor chain to the
3393 // header, stopping if there is an edge that doesn't exit the loop. If the
3394 // header is reached, the execution count of the branch will be equal to the
3395 // trip count of the loop.
3396 //
3397 // More extensive analysis could be done to handle more cases here.
3398 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003399 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003400 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003401 ExitBr->getParent() != L->getHeader()) {
3402 // The simple checks failed, try climbing the unique predecessor chain
3403 // up to the header.
3404 bool Ok = false;
3405 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3406 BasicBlock *Pred = BB->getUniquePredecessor();
3407 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003408 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003409 TerminatorInst *PredTerm = Pred->getTerminator();
3410 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3411 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3412 if (PredSucc == BB)
3413 continue;
3414 // If the predecessor has a successor that isn't BB and isn't
3415 // outside the loop, assume the worst.
3416 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003417 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003418 }
3419 if (Pred == L->getHeader()) {
3420 Ok = true;
3421 break;
3422 }
3423 BB = Pred;
3424 }
3425 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003426 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003427 }
3428
3429 // Procede to the next level to examine the exit condition expression.
3430 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3431 ExitBr->getSuccessor(0),
3432 ExitBr->getSuccessor(1));
3433}
3434
3435/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3436/// backedge of the specified loop will execute if its exit condition
3437/// were a conditional branch of ExitCond, TBB, and FBB.
3438ScalarEvolution::BackedgeTakenInfo
3439ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3440 Value *ExitCond,
3441 BasicBlock *TBB,
3442 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003443 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003444 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3445 if (BO->getOpcode() == Instruction::And) {
3446 // Recurse on the operands of the and.
3447 BackedgeTakenInfo BTI0 =
3448 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3449 BackedgeTakenInfo BTI1 =
3450 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003451 const SCEV *BECount = getCouldNotCompute();
3452 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003453 if (L->contains(TBB)) {
3454 // Both conditions must be true for the loop to continue executing.
3455 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003456 if (BTI0.Exact == getCouldNotCompute() ||
3457 BTI1.Exact == getCouldNotCompute())
3458 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003459 else
3460 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003461 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003462 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003463 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003464 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003465 else
3466 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003467 } else {
3468 // Both conditions must be true for the loop to exit.
3469 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003470 if (BTI0.Exact != getCouldNotCompute() &&
3471 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003472 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003473 if (BTI0.Max != getCouldNotCompute() &&
3474 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003475 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3476 }
3477
3478 return BackedgeTakenInfo(BECount, MaxBECount);
3479 }
3480 if (BO->getOpcode() == Instruction::Or) {
3481 // Recurse on the operands of the or.
3482 BackedgeTakenInfo BTI0 =
3483 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3484 BackedgeTakenInfo BTI1 =
3485 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003486 const SCEV *BECount = getCouldNotCompute();
3487 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003488 if (L->contains(FBB)) {
3489 // Both conditions must be false for the loop to continue executing.
3490 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003491 if (BTI0.Exact == getCouldNotCompute() ||
3492 BTI1.Exact == getCouldNotCompute())
3493 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003494 else
3495 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003496 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003497 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003498 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003499 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003500 else
3501 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003502 } else {
3503 // Both conditions must be false for the loop to exit.
3504 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003505 if (BTI0.Exact != getCouldNotCompute() &&
3506 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003507 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003508 if (BTI0.Max != getCouldNotCompute() &&
3509 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003510 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3511 }
3512
3513 return BackedgeTakenInfo(BECount, MaxBECount);
3514 }
3515 }
3516
3517 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3518 // Procede to the next level to examine the icmp.
3519 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3520 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003521
Eli Friedman361e54d2009-05-09 12:32:42 +00003522 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003523 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3524}
3525
3526/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3527/// backedge of the specified loop will execute if its exit condition
3528/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3529ScalarEvolution::BackedgeTakenInfo
3530ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3531 ICmpInst *ExitCond,
3532 BasicBlock *TBB,
3533 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003534
Reid Spencere4d87aa2006-12-23 06:05:41 +00003535 // If the condition was exit on true, convert the condition to exit on false
3536 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003537 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003538 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003539 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003540 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003541
3542 // Handle common loops like: for (X = "string"; *X; ++X)
3543 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3544 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003545 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003546 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003547 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3548 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3549 return BackedgeTakenInfo(ItCnt,
3550 isa<SCEVConstant>(ItCnt) ? ItCnt :
3551 getConstant(APInt::getMaxValue(BitWidth)-1));
3552 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003553 }
3554
Dan Gohman0bba49c2009-07-07 17:06:11 +00003555 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3556 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003557
3558 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003559 LHS = getSCEVAtScope(LHS, L);
3560 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003561
Dan Gohman64a845e2009-06-24 04:48:43 +00003562 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003563 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003564 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3565 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003566 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003567 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003568 }
3569
Chris Lattner53e677a2004-04-02 20:23:17 +00003570 // If we have a comparison of a chrec against a constant, try to use value
3571 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003572 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3573 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003574 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003575 // Form the constant range.
3576 ConstantRange CompRange(
3577 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003578
Dan Gohman0bba49c2009-07-07 17:06:11 +00003579 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003580 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003581 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003582
Chris Lattner53e677a2004-04-02 20:23:17 +00003583 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003584 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003585 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003586 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003587 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003588 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003589 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003590 case ICmpInst::ICMP_EQ: { // while (X == Y)
3591 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003592 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003593 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003594 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003595 }
3596 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003597 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3598 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003599 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003600 }
3601 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003602 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3603 getNotSCEV(RHS), L, true);
3604 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003605 break;
3606 }
3607 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003608 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3609 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003610 break;
3611 }
3612 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003613 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3614 getNotSCEV(RHS), L, false);
3615 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003616 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003617 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003618 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003619#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003620 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003621 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003622 errs() << "[unsigned] ";
3623 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003624 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003626#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003627 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003628 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003629 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003630 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003631}
3632
Chris Lattner673e02b2004-10-12 01:49:27 +00003633static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003634EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3635 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003636 const SCEV *InVal = SE.getConstant(C);
3637 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003638 assert(isa<SCEVConstant>(Val) &&
3639 "Evaluation of SCEV at constant didn't fold correctly?");
3640 return cast<SCEVConstant>(Val)->getValue();
3641}
3642
3643/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3644/// and a GEP expression (missing the pointer index) indexing into it, return
3645/// the addressed element of the initializer or null if the index expression is
3646/// invalid.
3647static Constant *
Owen Andersone922c022009-07-22 00:24:57 +00003648GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003649 const std::vector<ConstantInt*> &Indices) {
3650 Constant *Init = GV->getInitializer();
3651 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003652 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003653 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3654 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3655 Init = cast<Constant>(CS->getOperand(Idx));
3656 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3657 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3658 Init = cast<Constant>(CA->getOperand(Idx));
3659 } else if (isa<ConstantAggregateZero>(Init)) {
3660 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3661 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003662 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003663 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3664 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003665 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003666 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003667 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003668 }
3669 return 0;
3670 } else {
3671 return 0; // Unknown initializer type
3672 }
3673 }
3674 return Init;
3675}
3676
Dan Gohman46bdfb02009-02-24 18:55:53 +00003677/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3678/// 'icmp op load X, cst', try to see if we can compute the backedge
3679/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003680const SCEV *
3681ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3682 LoadInst *LI,
3683 Constant *RHS,
3684 const Loop *L,
3685 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003686 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003687
3688 // Check to see if the loaded pointer is a getelementptr of a global.
3689 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003690 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003691
3692 // Make sure that it is really a constant global we are gepping, with an
3693 // initializer, and make sure the first IDX is really 0.
3694 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003695 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003696 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3697 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003698 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003699
3700 // Okay, we allow one non-constant index into the GEP instruction.
3701 Value *VarIdx = 0;
3702 std::vector<ConstantInt*> Indexes;
3703 unsigned VarIdxNum = 0;
3704 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3705 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3706 Indexes.push_back(CI);
3707 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003708 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003709 VarIdx = GEP->getOperand(i);
3710 VarIdxNum = i-2;
3711 Indexes.push_back(0);
3712 }
3713
3714 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3715 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003716 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003717 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003718
3719 // We can only recognize very limited forms of loop index expressions, in
3720 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003721 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003722 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3723 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3724 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003725 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003726
3727 unsigned MaxSteps = MaxBruteForceIterations;
3728 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003729 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003730 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003731 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003732
3733 // Form the GEP offset.
3734 Indexes[VarIdxNum] = Val;
3735
Owen Andersone922c022009-07-22 00:24:57 +00003736 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003737 if (Result == 0) break; // Cannot compute!
3738
3739 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003740 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003741 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003742 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003743#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003744 errs() << "\n***\n*** Computed loop count " << *ItCst
3745 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3746 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003747#endif
3748 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003749 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003750 }
3751 }
Dan Gohman1c343752009-06-27 21:21:31 +00003752 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003753}
3754
3755
Chris Lattner3221ad02004-04-17 22:58:41 +00003756/// CanConstantFold - Return true if we can constant fold an instruction of the
3757/// specified type, assuming that all operands were constants.
3758static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003759 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003760 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3761 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003762
Chris Lattner3221ad02004-04-17 22:58:41 +00003763 if (const CallInst *CI = dyn_cast<CallInst>(I))
3764 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003765 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003766 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003767}
3768
Chris Lattner3221ad02004-04-17 22:58:41 +00003769/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3770/// in the loop that V is derived from. We allow arbitrary operations along the
3771/// way, but the operands of an operation must either be constants or a value
3772/// derived from a constant PHI. If this expression does not fit with these
3773/// constraints, return null.
3774static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3775 // If this is not an instruction, or if this is an instruction outside of the
3776 // loop, it can't be derived from a loop PHI.
3777 Instruction *I = dyn_cast<Instruction>(V);
3778 if (I == 0 || !L->contains(I->getParent())) return 0;
3779
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003780 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003781 if (L->getHeader() == I->getParent())
3782 return PN;
3783 else
3784 // We don't currently keep track of the control flow needed to evaluate
3785 // PHIs, so we cannot handle PHIs inside of loops.
3786 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003787 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003788
3789 // If we won't be able to constant fold this expression even if the operands
3790 // are constants, return early.
3791 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003792
Chris Lattner3221ad02004-04-17 22:58:41 +00003793 // Otherwise, we can evaluate this instruction if all of its operands are
3794 // constant or derived from a PHI node themselves.
3795 PHINode *PHI = 0;
3796 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3797 if (!(isa<Constant>(I->getOperand(Op)) ||
3798 isa<GlobalValue>(I->getOperand(Op)))) {
3799 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3800 if (P == 0) return 0; // Not evolving from PHI
3801 if (PHI == 0)
3802 PHI = P;
3803 else if (PHI != P)
3804 return 0; // Evolving from multiple different PHIs.
3805 }
3806
3807 // This is a expression evolving from a constant PHI!
3808 return PHI;
3809}
3810
3811/// EvaluateExpression - Given an expression that passes the
3812/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3813/// in the loop has the value PHIVal. If we can't fold this expression for some
3814/// reason, return null.
3815static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3816 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003817 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003818 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003819 Instruction *I = cast<Instruction>(V);
Owen Andersone922c022009-07-22 00:24:57 +00003820 LLVMContext &Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003821
3822 std::vector<Constant*> Operands;
3823 Operands.resize(I->getNumOperands());
3824
3825 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3826 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3827 if (Operands[i] == 0) return 0;
3828 }
3829
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003830 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3831 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003832 &Operands[0], Operands.size(),
3833 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003834 else
3835 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003836 &Operands[0], Operands.size(),
3837 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003838}
3839
3840/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3841/// in the header of its containing loop, we know the loop executes a
3842/// constant number of times, and the PHI node is just a recurrence
3843/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003844Constant *
3845ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3846 const APInt& BEs,
3847 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003848 std::map<PHINode*, Constant*>::iterator I =
3849 ConstantEvolutionLoopExitValue.find(PN);
3850 if (I != ConstantEvolutionLoopExitValue.end())
3851 return I->second;
3852
Dan Gohman46bdfb02009-02-24 18:55:53 +00003853 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003854 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3855
3856 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3857
3858 // Since the loop is canonicalized, the PHI node must have two entries. One
3859 // entry must be a constant (coming in from outside of the loop), and the
3860 // second must be derived from the same PHI.
3861 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3862 Constant *StartCST =
3863 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3864 if (StartCST == 0)
3865 return RetVal = 0; // Must be a constant.
3866
3867 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3868 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3869 if (PN2 != PN)
3870 return RetVal = 0; // Not derived from same PHI.
3871
3872 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003873 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003874 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003875
Dan Gohman46bdfb02009-02-24 18:55:53 +00003876 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003877 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003878 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3879 if (IterationNum == NumIterations)
3880 return RetVal = PHIVal; // Got exit value!
3881
3882 // Compute the value of the PHI node for the next iteration.
3883 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3884 if (NextPHI == PHIVal)
3885 return RetVal = NextPHI; // Stopped evolving!
3886 if (NextPHI == 0)
3887 return 0; // Couldn't evaluate!
3888 PHIVal = NextPHI;
3889 }
3890}
3891
Dan Gohman07ad19b2009-07-27 16:09:48 +00003892/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003893/// constant number of times (the condition evolves only from constants),
3894/// try to evaluate a few iterations of the loop until we get the exit
3895/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003896/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003897const SCEV *
3898ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3899 Value *Cond,
3900 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003901 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003902 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003903
3904 // Since the loop is canonicalized, the PHI node must have two entries. One
3905 // entry must be a constant (coming in from outside of the loop), and the
3906 // second must be derived from the same PHI.
3907 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3908 Constant *StartCST =
3909 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003910 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003911
3912 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3913 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003914 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003915
3916 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3917 // the loop symbolically to determine when the condition gets a value of
3918 // "ExitWhen".
3919 unsigned IterationNum = 0;
3920 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3921 for (Constant *PHIVal = StartCST;
3922 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003923 ConstantInt *CondVal =
3924 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003925
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003926 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003927 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003928
Reid Spencere8019bb2007-03-01 07:25:48 +00003929 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003930 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00003931 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003932 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003933
Chris Lattner3221ad02004-04-17 22:58:41 +00003934 // Compute the value of the PHI node for the next iteration.
3935 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3936 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003937 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003938 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003939 }
3940
3941 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003942 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003943}
3944
Dan Gohmane7125f42009-09-03 15:00:26 +00003945/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00003946/// at the specified scope in the program. The L value specifies a loop
3947/// nest to evaluate the expression at, where null is the top-level or a
3948/// specified loop is immediately inside of the loop.
3949///
3950/// This method can be used to compute the exit value for a variable defined
3951/// in a loop by querying what the value will hold in the parent loop.
3952///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003953/// In the case that a relevant loop exit value cannot be computed, the
3954/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003955const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00003956 // Check to see if we've folded this expression at this loop before.
3957 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
3958 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
3959 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
3960 if (!Pair.second)
3961 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00003962
Dan Gohman42214892009-08-31 21:15:23 +00003963 // Otherwise compute it.
3964 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00003965 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00003966 return C;
3967}
3968
3969const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003970 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003971
Nick Lewycky3e630762008-02-20 06:48:22 +00003972 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003973 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003974 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003975 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003976 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003977 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3978 if (PHINode *PN = dyn_cast<PHINode>(I))
3979 if (PN->getParent() == LI->getHeader()) {
3980 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003981 // to see if the loop that contains it has a known backedge-taken
3982 // count. If so, we may be able to force computation of the exit
3983 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003984 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003985 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003986 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003987 // Okay, we know how many times the containing loop executes. If
3988 // this is a constant evolving PHI node, get the final value at
3989 // the specified iteration number.
3990 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003991 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003992 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003993 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003994 }
3995 }
3996
Reid Spencer09906f32006-12-04 21:33:23 +00003997 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003998 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003999 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004000 // result. This is particularly useful for computing loop exit values.
4001 if (CanConstantFold(I)) {
4002 std::vector<Constant*> Operands;
4003 Operands.reserve(I->getNumOperands());
4004 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4005 Value *Op = I->getOperand(i);
4006 if (Constant *C = dyn_cast<Constant>(Op)) {
4007 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004008 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004009 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004010 // non-integer and non-pointer, don't even try to analyze them
4011 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004012 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004013 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004014
Dan Gohman85b05a22009-07-13 21:35:55 +00004015 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004016 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004017 Constant *C = SC->getValue();
4018 if (C->getType() != Op->getType())
4019 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4020 Op->getType(),
4021 false),
4022 C, Op->getType());
4023 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004024 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004025 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4026 if (C->getType() != Op->getType())
4027 C =
4028 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4029 Op->getType(),
4030 false),
4031 C, Op->getType());
4032 Operands.push_back(C);
4033 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004034 return V;
4035 } else {
4036 return V;
4037 }
4038 }
4039 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004040
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004041 Constant *C;
4042 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4043 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00004044 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00004045 getContext());
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004046 else
4047 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004048 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00004049 getContext());
Dan Gohman09987962009-06-29 21:31:18 +00004050 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004051 }
4052 }
4053
4054 // This is some other type of SCEVUnknown, just return it.
4055 return V;
4056 }
4057
Dan Gohman622ed672009-05-04 22:02:23 +00004058 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004059 // Avoid performing the look-up in the common case where the specified
4060 // expression has no loop-variant portions.
4061 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004062 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004063 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004064 // Okay, at least one of these operands is loop variant but might be
4065 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004066 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4067 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004068 NewOps.push_back(OpAtScope);
4069
4070 for (++i; i != e; ++i) {
4071 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004072 NewOps.push_back(OpAtScope);
4073 }
4074 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004075 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004076 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004077 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004078 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004079 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004080 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004081 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004082 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004083 }
4084 }
4085 // If we got here, all operands are loop invariant.
4086 return Comm;
4087 }
4088
Dan Gohman622ed672009-05-04 22:02:23 +00004089 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004090 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4091 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004092 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4093 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004094 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004095 }
4096
4097 // If this is a loop recurrence for a loop that does not contain L, then we
4098 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004099 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004100 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
4101 // To evaluate this recurrence, we need to know how many times the AddRec
4102 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004103 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004104 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004105
Eli Friedmanb42a6262008-08-04 23:49:06 +00004106 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004107 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004108 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004109 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004110 }
4111
Dan Gohman622ed672009-05-04 22:02:23 +00004112 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004113 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004114 if (Op == Cast->getOperand())
4115 return Cast; // must be loop invariant
4116 return getZeroExtendExpr(Op, Cast->getType());
4117 }
4118
Dan Gohman622ed672009-05-04 22:02:23 +00004119 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004120 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004121 if (Op == Cast->getOperand())
4122 return Cast; // must be loop invariant
4123 return getSignExtendExpr(Op, Cast->getType());
4124 }
4125
Dan Gohman622ed672009-05-04 22:02:23 +00004126 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004127 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004128 if (Op == Cast->getOperand())
4129 return Cast; // must be loop invariant
4130 return getTruncateExpr(Op, Cast->getType());
4131 }
4132
Dan Gohmanc40f17b2009-08-18 16:46:41 +00004133 if (isa<SCEVTargetDataConstant>(V))
4134 return V;
4135
Torok Edwinc23197a2009-07-14 16:55:14 +00004136 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004137 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004138}
4139
Dan Gohman66a7e852009-05-08 20:38:54 +00004140/// getSCEVAtScope - This is a convenience function which does
4141/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004142const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004143 return getSCEVAtScope(getSCEV(V), L);
4144}
4145
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004146/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4147/// following equation:
4148///
4149/// A * X = B (mod N)
4150///
4151/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4152/// A and B isn't important.
4153///
4154/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004155static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004156 ScalarEvolution &SE) {
4157 uint32_t BW = A.getBitWidth();
4158 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4159 assert(A != 0 && "A must be non-zero.");
4160
4161 // 1. D = gcd(A, N)
4162 //
4163 // The gcd of A and N may have only one prime factor: 2. The number of
4164 // trailing zeros in A is its multiplicity
4165 uint32_t Mult2 = A.countTrailingZeros();
4166 // D = 2^Mult2
4167
4168 // 2. Check if B is divisible by D.
4169 //
4170 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4171 // is not less than multiplicity of this prime factor for D.
4172 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004173 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004174
4175 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4176 // modulo (N / D).
4177 //
4178 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4179 // bit width during computations.
4180 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4181 APInt Mod(BW + 1, 0);
4182 Mod.set(BW - Mult2); // Mod = N / D
4183 APInt I = AD.multiplicativeInverse(Mod);
4184
4185 // 4. Compute the minimum unsigned root of the equation:
4186 // I * (B / D) mod (N / D)
4187 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4188
4189 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4190 // bits.
4191 return SE.getConstant(Result.trunc(BW));
4192}
Chris Lattner53e677a2004-04-02 20:23:17 +00004193
4194/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4195/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4196/// might be the same) or two SCEVCouldNotCompute objects.
4197///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004198static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004199SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004200 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004201 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4202 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4203 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004204
Chris Lattner53e677a2004-04-02 20:23:17 +00004205 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004206 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004207 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004208 return std::make_pair(CNC, CNC);
4209 }
4210
Reid Spencere8019bb2007-03-01 07:25:48 +00004211 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004212 const APInt &L = LC->getValue()->getValue();
4213 const APInt &M = MC->getValue()->getValue();
4214 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004215 APInt Two(BitWidth, 2);
4216 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004217
Dan Gohman64a845e2009-06-24 04:48:43 +00004218 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004219 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004220 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004221 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4222 // The B coefficient is M-N/2
4223 APInt B(M);
4224 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004225
Reid Spencere8019bb2007-03-01 07:25:48 +00004226 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004227 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004228
Reid Spencere8019bb2007-03-01 07:25:48 +00004229 // Compute the B^2-4ac term.
4230 APInt SqrtTerm(B);
4231 SqrtTerm *= B;
4232 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004233
Reid Spencere8019bb2007-03-01 07:25:48 +00004234 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4235 // integer value or else APInt::sqrt() will assert.
4236 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004237
Dan Gohman64a845e2009-06-24 04:48:43 +00004238 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004239 // The divisions must be performed as signed divisions.
4240 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004241 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004242 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004243 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004244 return std::make_pair(CNC, CNC);
4245 }
4246
Owen Andersone922c022009-07-22 00:24:57 +00004247 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004248
4249 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004250 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004251 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004252 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004253
Dan Gohman64a845e2009-06-24 04:48:43 +00004254 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004255 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004256 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004257}
4258
4259/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004260/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004261const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004262 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004263 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004264 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004265 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004266 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004267 }
4268
Dan Gohman35738ac2009-05-04 22:30:44 +00004269 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004270 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004271 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004272
4273 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004274 // If this is an affine expression, the execution count of this branch is
4275 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004276 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004277 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004278 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004279 // equivalent to:
4280 //
4281 // Step*N = -Start (mod 2^BW)
4282 //
4283 // where BW is the common bit width of Start and Step.
4284
Chris Lattner53e677a2004-04-02 20:23:17 +00004285 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004286 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4287 L->getParentLoop());
4288 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4289 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004290
Dan Gohman622ed672009-05-04 22:02:23 +00004291 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004292 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004293
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004294 // First, handle unitary steps.
4295 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004296 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004297 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4298 return Start; // N = Start (as unsigned)
4299
4300 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004301 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004302 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004303 -StartC->getValue()->getValue(),
4304 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004305 }
Chris Lattner42a75512007-01-15 02:27:26 +00004306 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004307 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4308 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004309 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004310 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004311 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4312 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004313 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004314#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004315 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4316 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004317#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004318 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004319 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004320 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004321 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004322 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004323 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004324
Chris Lattner53e677a2004-04-02 20:23:17 +00004325 // We can only use this value if the chrec ends up with an exact zero
4326 // value at this index. When solving for "X*X != 5", for example, we
4327 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004328 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004329 if (Val->isZero())
4330 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004331 }
4332 }
4333 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004334
Dan Gohman1c343752009-06-27 21:21:31 +00004335 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004336}
4337
4338/// HowFarToNonZero - Return the number of times a backedge checking the
4339/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004340/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004341const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004342 // Loops that look like: while (X == 0) are very strange indeed. We don't
4343 // handle them yet except for the trivial case. This could be expanded in the
4344 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004345
Chris Lattner53e677a2004-04-02 20:23:17 +00004346 // If the value is a constant, check to see if it is known to be non-zero
4347 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004348 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004349 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004350 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004351 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004352 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004353
Chris Lattner53e677a2004-04-02 20:23:17 +00004354 // We could implement others, but I really doubt anyone writes loops like
4355 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004356 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004357}
4358
Dan Gohman859b4822009-05-18 15:36:09 +00004359/// getLoopPredecessor - If the given loop's header has exactly one unique
4360/// predecessor outside the loop, return it. Otherwise return null.
4361///
4362BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4363 BasicBlock *Header = L->getHeader();
4364 BasicBlock *Pred = 0;
4365 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4366 PI != E; ++PI)
4367 if (!L->contains(*PI)) {
4368 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4369 Pred = *PI;
4370 }
4371 return Pred;
4372}
4373
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004374/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4375/// (which may not be an immediate predecessor) which has exactly one
4376/// successor from which BB is reachable, or null if no such block is
4377/// found.
4378///
4379BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004380ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004381 // If the block has a unique predecessor, then there is no path from the
4382 // predecessor to the block that does not go through the direct edge
4383 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004384 if (BasicBlock *Pred = BB->getSinglePredecessor())
4385 return Pred;
4386
4387 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004388 // If the header has a unique predecessor outside the loop, it must be
4389 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004390 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004391 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004392
4393 return 0;
4394}
4395
Dan Gohman763bad12009-06-20 00:35:32 +00004396/// HasSameValue - SCEV structural equivalence is usually sufficient for
4397/// testing whether two expressions are equal, however for the purposes of
4398/// looking for a condition guarding a loop, it can be useful to be a little
4399/// more general, since a front-end may have replicated the controlling
4400/// expression.
4401///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004402static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004403 // Quick check to see if they are the same SCEV.
4404 if (A == B) return true;
4405
4406 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4407 // two different instructions with the same value. Check for this case.
4408 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4409 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4410 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4411 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004412 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004413 return true;
4414
4415 // Otherwise assume they may have a different value.
4416 return false;
4417}
4418
Dan Gohman85b05a22009-07-13 21:35:55 +00004419bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4420 return getSignedRange(S).getSignedMax().isNegative();
4421}
4422
4423bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4424 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4425}
4426
4427bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4428 return !getSignedRange(S).getSignedMin().isNegative();
4429}
4430
4431bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4432 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4433}
4434
4435bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4436 return isKnownNegative(S) || isKnownPositive(S);
4437}
4438
4439bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4440 const SCEV *LHS, const SCEV *RHS) {
4441
4442 if (HasSameValue(LHS, RHS))
4443 return ICmpInst::isTrueWhenEqual(Pred);
4444
4445 switch (Pred) {
4446 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004447 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004448 break;
4449 case ICmpInst::ICMP_SGT:
4450 Pred = ICmpInst::ICMP_SLT;
4451 std::swap(LHS, RHS);
4452 case ICmpInst::ICMP_SLT: {
4453 ConstantRange LHSRange = getSignedRange(LHS);
4454 ConstantRange RHSRange = getSignedRange(RHS);
4455 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4456 return true;
4457 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4458 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004459 break;
4460 }
4461 case ICmpInst::ICMP_SGE:
4462 Pred = ICmpInst::ICMP_SLE;
4463 std::swap(LHS, RHS);
4464 case ICmpInst::ICMP_SLE: {
4465 ConstantRange LHSRange = getSignedRange(LHS);
4466 ConstantRange RHSRange = getSignedRange(RHS);
4467 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4468 return true;
4469 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4470 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004471 break;
4472 }
4473 case ICmpInst::ICMP_UGT:
4474 Pred = ICmpInst::ICMP_ULT;
4475 std::swap(LHS, RHS);
4476 case ICmpInst::ICMP_ULT: {
4477 ConstantRange LHSRange = getUnsignedRange(LHS);
4478 ConstantRange RHSRange = getUnsignedRange(RHS);
4479 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4480 return true;
4481 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4482 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004483 break;
4484 }
4485 case ICmpInst::ICMP_UGE:
4486 Pred = ICmpInst::ICMP_ULE;
4487 std::swap(LHS, RHS);
4488 case ICmpInst::ICMP_ULE: {
4489 ConstantRange LHSRange = getUnsignedRange(LHS);
4490 ConstantRange RHSRange = getUnsignedRange(RHS);
4491 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4492 return true;
4493 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4494 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004495 break;
4496 }
4497 case ICmpInst::ICMP_NE: {
4498 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4499 return true;
4500 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4501 return true;
4502
4503 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4504 if (isKnownNonZero(Diff))
4505 return true;
4506 break;
4507 }
4508 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004509 // The check at the top of the function catches the case where
4510 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004511 break;
4512 }
4513 return false;
4514}
4515
4516/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4517/// protected by a conditional between LHS and RHS. This is used to
4518/// to eliminate casts.
4519bool
4520ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4521 ICmpInst::Predicate Pred,
4522 const SCEV *LHS, const SCEV *RHS) {
4523 // Interpret a null as meaning no loop, where there is obviously no guard
4524 // (interprocedural conditions notwithstanding).
4525 if (!L) return true;
4526
4527 BasicBlock *Latch = L->getLoopLatch();
4528 if (!Latch)
4529 return false;
4530
4531 BranchInst *LoopContinuePredicate =
4532 dyn_cast<BranchInst>(Latch->getTerminator());
4533 if (!LoopContinuePredicate ||
4534 LoopContinuePredicate->isUnconditional())
4535 return false;
4536
Dan Gohman0f4b2852009-07-21 23:03:19 +00004537 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4538 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004539}
4540
4541/// isLoopGuardedByCond - Test whether entry to the loop is protected
4542/// by a conditional between LHS and RHS. This is used to help avoid max
4543/// expressions in loop trip counts, and to eliminate casts.
4544bool
4545ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4546 ICmpInst::Predicate Pred,
4547 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004548 // Interpret a null as meaning no loop, where there is obviously no guard
4549 // (interprocedural conditions notwithstanding).
4550 if (!L) return false;
4551
Dan Gohman859b4822009-05-18 15:36:09 +00004552 BasicBlock *Predecessor = getLoopPredecessor(L);
4553 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004554
Dan Gohman859b4822009-05-18 15:36:09 +00004555 // Starting at the loop predecessor, climb up the predecessor chain, as long
4556 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004557 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004558 for (; Predecessor;
4559 PredecessorDest = Predecessor,
4560 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004561
4562 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004563 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004564 if (!LoopEntryPredicate ||
4565 LoopEntryPredicate->isUnconditional())
4566 continue;
4567
Dan Gohman0f4b2852009-07-21 23:03:19 +00004568 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4569 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004570 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004571 }
4572
Dan Gohman38372182008-08-12 20:17:31 +00004573 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004574}
4575
Dan Gohman0f4b2852009-07-21 23:03:19 +00004576/// isImpliedCond - Test whether the condition described by Pred, LHS,
4577/// and RHS is true whenever the given Cond value evaluates to true.
4578bool ScalarEvolution::isImpliedCond(Value *CondValue,
4579 ICmpInst::Predicate Pred,
4580 const SCEV *LHS, const SCEV *RHS,
4581 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004582 // Recursivly handle And and Or conditions.
4583 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4584 if (BO->getOpcode() == Instruction::And) {
4585 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004586 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4587 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004588 } else if (BO->getOpcode() == Instruction::Or) {
4589 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004590 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4591 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004592 }
4593 }
4594
4595 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4596 if (!ICI) return false;
4597
Dan Gohman85b05a22009-07-13 21:35:55 +00004598 // Bail if the ICmp's operands' types are wider than the needed type
4599 // before attempting to call getSCEV on them. This avoids infinite
4600 // recursion, since the analysis of widening casts can require loop
4601 // exit condition information for overflow checking, which would
4602 // lead back here.
4603 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004604 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004605 return false;
4606
Dan Gohman0f4b2852009-07-21 23:03:19 +00004607 // Now that we found a conditional branch that dominates the loop, check to
4608 // see if it is the comparison we are looking for.
4609 ICmpInst::Predicate FoundPred;
4610 if (Inverse)
4611 FoundPred = ICI->getInversePredicate();
4612 else
4613 FoundPred = ICI->getPredicate();
4614
4615 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4616 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004617
4618 // Balance the types. The case where FoundLHS' type is wider than
4619 // LHS' type is checked for above.
4620 if (getTypeSizeInBits(LHS->getType()) >
4621 getTypeSizeInBits(FoundLHS->getType())) {
4622 if (CmpInst::isSigned(Pred)) {
4623 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4624 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4625 } else {
4626 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4627 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4628 }
4629 }
4630
Dan Gohman0f4b2852009-07-21 23:03:19 +00004631 // Canonicalize the query to match the way instcombine will have
4632 // canonicalized the comparison.
4633 // First, put a constant operand on the right.
4634 if (isa<SCEVConstant>(LHS)) {
4635 std::swap(LHS, RHS);
4636 Pred = ICmpInst::getSwappedPredicate(Pred);
4637 }
4638 // Then, canonicalize comparisons with boundary cases.
4639 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4640 const APInt &RA = RC->getValue()->getValue();
4641 switch (Pred) {
4642 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4643 case ICmpInst::ICMP_EQ:
4644 case ICmpInst::ICMP_NE:
4645 break;
4646 case ICmpInst::ICMP_UGE:
4647 if ((RA - 1).isMinValue()) {
4648 Pred = ICmpInst::ICMP_NE;
4649 RHS = getConstant(RA - 1);
4650 break;
4651 }
4652 if (RA.isMaxValue()) {
4653 Pred = ICmpInst::ICMP_EQ;
4654 break;
4655 }
4656 if (RA.isMinValue()) return true;
4657 break;
4658 case ICmpInst::ICMP_ULE:
4659 if ((RA + 1).isMaxValue()) {
4660 Pred = ICmpInst::ICMP_NE;
4661 RHS = getConstant(RA + 1);
4662 break;
4663 }
4664 if (RA.isMinValue()) {
4665 Pred = ICmpInst::ICMP_EQ;
4666 break;
4667 }
4668 if (RA.isMaxValue()) return true;
4669 break;
4670 case ICmpInst::ICMP_SGE:
4671 if ((RA - 1).isMinSignedValue()) {
4672 Pred = ICmpInst::ICMP_NE;
4673 RHS = getConstant(RA - 1);
4674 break;
4675 }
4676 if (RA.isMaxSignedValue()) {
4677 Pred = ICmpInst::ICMP_EQ;
4678 break;
4679 }
4680 if (RA.isMinSignedValue()) return true;
4681 break;
4682 case ICmpInst::ICMP_SLE:
4683 if ((RA + 1).isMaxSignedValue()) {
4684 Pred = ICmpInst::ICMP_NE;
4685 RHS = getConstant(RA + 1);
4686 break;
4687 }
4688 if (RA.isMinSignedValue()) {
4689 Pred = ICmpInst::ICMP_EQ;
4690 break;
4691 }
4692 if (RA.isMaxSignedValue()) return true;
4693 break;
4694 case ICmpInst::ICMP_UGT:
4695 if (RA.isMinValue()) {
4696 Pred = ICmpInst::ICMP_NE;
4697 break;
4698 }
4699 if ((RA + 1).isMaxValue()) {
4700 Pred = ICmpInst::ICMP_EQ;
4701 RHS = getConstant(RA + 1);
4702 break;
4703 }
4704 if (RA.isMaxValue()) return false;
4705 break;
4706 case ICmpInst::ICMP_ULT:
4707 if (RA.isMaxValue()) {
4708 Pred = ICmpInst::ICMP_NE;
4709 break;
4710 }
4711 if ((RA - 1).isMinValue()) {
4712 Pred = ICmpInst::ICMP_EQ;
4713 RHS = getConstant(RA - 1);
4714 break;
4715 }
4716 if (RA.isMinValue()) return false;
4717 break;
4718 case ICmpInst::ICMP_SGT:
4719 if (RA.isMinSignedValue()) {
4720 Pred = ICmpInst::ICMP_NE;
4721 break;
4722 }
4723 if ((RA + 1).isMaxSignedValue()) {
4724 Pred = ICmpInst::ICMP_EQ;
4725 RHS = getConstant(RA + 1);
4726 break;
4727 }
4728 if (RA.isMaxSignedValue()) return false;
4729 break;
4730 case ICmpInst::ICMP_SLT:
4731 if (RA.isMaxSignedValue()) {
4732 Pred = ICmpInst::ICMP_NE;
4733 break;
4734 }
4735 if ((RA - 1).isMinSignedValue()) {
4736 Pred = ICmpInst::ICMP_EQ;
4737 RHS = getConstant(RA - 1);
4738 break;
4739 }
4740 if (RA.isMinSignedValue()) return false;
4741 break;
4742 }
4743 }
4744
4745 // Check to see if we can make the LHS or RHS match.
4746 if (LHS == FoundRHS || RHS == FoundLHS) {
4747 if (isa<SCEVConstant>(RHS)) {
4748 std::swap(FoundLHS, FoundRHS);
4749 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4750 } else {
4751 std::swap(LHS, RHS);
4752 Pred = ICmpInst::getSwappedPredicate(Pred);
4753 }
4754 }
4755
4756 // Check whether the found predicate is the same as the desired predicate.
4757 if (FoundPred == Pred)
4758 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4759
4760 // Check whether swapping the found predicate makes it the same as the
4761 // desired predicate.
4762 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4763 if (isa<SCEVConstant>(RHS))
4764 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4765 else
4766 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4767 RHS, LHS, FoundLHS, FoundRHS);
4768 }
4769
4770 // Check whether the actual condition is beyond sufficient.
4771 if (FoundPred == ICmpInst::ICMP_EQ)
4772 if (ICmpInst::isTrueWhenEqual(Pred))
4773 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4774 return true;
4775 if (Pred == ICmpInst::ICMP_NE)
4776 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4777 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4778 return true;
4779
4780 // Otherwise assume the worst.
4781 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004782}
4783
Dan Gohman0f4b2852009-07-21 23:03:19 +00004784/// isImpliedCondOperands - Test whether the condition described by Pred,
4785/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4786/// and FoundRHS is true.
4787bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4788 const SCEV *LHS, const SCEV *RHS,
4789 const SCEV *FoundLHS,
4790 const SCEV *FoundRHS) {
4791 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4792 FoundLHS, FoundRHS) ||
4793 // ~x < ~y --> x > y
4794 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4795 getNotSCEV(FoundRHS),
4796 getNotSCEV(FoundLHS));
4797}
4798
4799/// isImpliedCondOperandsHelper - Test whether the condition described by
4800/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4801/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004802bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004803ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4804 const SCEV *LHS, const SCEV *RHS,
4805 const SCEV *FoundLHS,
4806 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004807 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004808 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4809 case ICmpInst::ICMP_EQ:
4810 case ICmpInst::ICMP_NE:
4811 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4812 return true;
4813 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004814 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004815 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004816 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4817 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4818 return true;
4819 break;
4820 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004821 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004822 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4823 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4824 return true;
4825 break;
4826 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004827 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004828 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4829 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4830 return true;
4831 break;
4832 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004833 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004834 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4835 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4836 return true;
4837 break;
4838 }
4839
4840 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004841}
4842
Dan Gohman51f53b72009-06-21 23:46:38 +00004843/// getBECount - Subtract the end and start values and divide by the step,
4844/// rounding up, to get the number of times the backedge is executed. Return
4845/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004846const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004847 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00004848 const SCEV *Step,
4849 bool NoWrap) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004850 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004851 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4852 const SCEV *Diff = getMinusSCEV(End, Start);
4853 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004854
4855 // Add an adjustment to the difference between End and Start so that
4856 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004857 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004858
Dan Gohman1f96e672009-09-17 18:05:20 +00004859 if (!NoWrap) {
4860 // Check Add for unsigned overflow.
4861 // TODO: More sophisticated things could be done here.
4862 const Type *WideTy = IntegerType::get(getContext(),
4863 getTypeSizeInBits(Ty) + 1);
4864 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4865 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4866 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4867 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4868 return getCouldNotCompute();
4869 }
Dan Gohman51f53b72009-06-21 23:46:38 +00004870
4871 return getUDivExpr(Add, Step);
4872}
4873
Chris Lattnerdb25de42005-08-15 23:33:51 +00004874/// HowManyLessThans - Return the number of times a backedge containing the
4875/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004876/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004877ScalarEvolution::BackedgeTakenInfo
4878ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4879 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004880 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004881 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004882
Dan Gohman35738ac2009-05-04 22:30:44 +00004883 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004884 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004885 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004886
Dan Gohman1f96e672009-09-17 18:05:20 +00004887 // Check to see if we have a flag which makes analysis easy.
4888 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
4889 AddRec->hasNoUnsignedWrap();
4890
Chris Lattnerdb25de42005-08-15 23:33:51 +00004891 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004892 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004893 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004894 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004895
4896 // TODO: handle non-constant strides.
4897 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4898 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004899 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004900 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004901 // With unit stride, the iteration never steps past the limit value.
4902 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
Dan Gohman1f96e672009-09-17 18:05:20 +00004903 if (NoWrap) {
4904 // We know the iteration won't step past the maximum value for its type.
4905 ;
4906 } else if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004907 // Test whether a positive iteration iteration can step past the limit
4908 // value and past the maximum value for its type in a single step.
4909 if (isSigned) {
4910 APInt Max = APInt::getSignedMaxValue(BitWidth);
4911 if ((Max - CStep->getValue()->getValue())
4912 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004913 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004914 } else {
4915 APInt Max = APInt::getMaxValue(BitWidth);
4916 if ((Max - CStep->getValue()->getValue())
4917 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004918 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004919 }
4920 } else
4921 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004922 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004923 } else
4924 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004925 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004926
Dan Gohmana1af7572009-04-30 20:47:05 +00004927 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4928 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4929 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004930 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004931
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004932 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004933 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004934
Dan Gohmana1af7572009-04-30 20:47:05 +00004935 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004936 const SCEV *MinStart = getConstant(isSigned ?
4937 getSignedRange(Start).getSignedMin() :
4938 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004939
Dan Gohmana1af7572009-04-30 20:47:05 +00004940 // If we know that the condition is true in order to enter the loop,
4941 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004942 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4943 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004944 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004945 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004946 isSigned ? ICmpInst::ICMP_SLT :
4947 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004948 getMinusSCEV(Start, Step), RHS))
4949 End = isSigned ? getSMaxExpr(RHS, Start)
4950 : getUMaxExpr(RHS, Start);
4951
4952 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004953 const SCEV *MaxEnd = getConstant(isSigned ?
4954 getSignedRange(End).getSignedMax() :
4955 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004956
4957 // Finally, we subtract these two values and divide, rounding up, to get
4958 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00004959 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00004960
4961 // The maximum backedge count is similar, except using the minimum start
4962 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00004963 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00004964
4965 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004966 }
4967
Dan Gohman1c343752009-06-27 21:21:31 +00004968 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004969}
4970
Chris Lattner53e677a2004-04-02 20:23:17 +00004971/// getNumIterationsInRange - Return the number of iterations of this loop that
4972/// produce values in the specified constant range. Another way of looking at
4973/// this is that it returns the first iteration number where the value is not in
4974/// the condition, thus computing the exit count. If the iteration count can't
4975/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004976const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004977 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004978 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004979 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004980
4981 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004982 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004983 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004984 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004985 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004986 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004987 if (const SCEVAddRecExpr *ShiftedAddRec =
4988 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004989 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004990 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004991 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004992 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004993 }
4994
4995 // The only time we can solve this is when we have all constant indices.
4996 // Otherwise, we cannot determine the overflow conditions.
4997 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4998 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004999 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005000
5001
5002 // Okay at this point we know that all elements of the chrec are constants and
5003 // that the start element is zero.
5004
5005 // First check to see if the range contains zero. If not, the first
5006 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005007 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005008 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005009 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005010
Chris Lattner53e677a2004-04-02 20:23:17 +00005011 if (isAffine()) {
5012 // If this is an affine expression then we have this situation:
5013 // Solve {0,+,A} in Range === Ax in Range
5014
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005015 // We know that zero is in the range. If A is positive then we know that
5016 // the upper value of the range must be the first possible exit value.
5017 // If A is negative then the lower of the range is the last possible loop
5018 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005019 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005020 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5021 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005022
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005023 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005024 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005025 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005026
5027 // Evaluate at the exit value. If we really did fall out of the valid
5028 // range, then we computed our trip count, otherwise wrap around or other
5029 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005030 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005031 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005032 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005033
5034 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005035 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005036 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005037 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005038 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005039 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005040 } else if (isQuadratic()) {
5041 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5042 // quadratic equation to solve it. To do this, we must frame our problem in
5043 // terms of figuring out when zero is crossed, instead of when
5044 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005045 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005046 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005047 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005048
5049 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005050 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005051 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005052 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5053 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005054 if (R1) {
5055 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005056 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005057 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005058 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005059 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005060 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005061
Chris Lattner53e677a2004-04-02 20:23:17 +00005062 // Make sure the root is not off by one. The returned iteration should
5063 // not be in the range, but the previous one should be. When solving
5064 // for "X*X < 5", for example, we should not return a root of 2.
5065 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005066 R1->getValue(),
5067 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005068 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005069 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005070 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005071 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005072
Dan Gohman246b2562007-10-22 18:31:58 +00005073 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005074 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005075 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005076 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005077 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005078
Chris Lattner53e677a2004-04-02 20:23:17 +00005079 // If R1 was not in the range, then it is a good return value. Make
5080 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005081 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005082 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005083 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005084 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005085 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005086 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005087 }
5088 }
5089 }
5090
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005091 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005092}
5093
5094
5095
5096//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005097// SCEVCallbackVH Class Implementation
5098//===----------------------------------------------------------------------===//
5099
Dan Gohman1959b752009-05-19 19:22:47 +00005100void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005101 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005102 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5103 SE->ConstantEvolutionLoopExitValue.erase(PN);
5104 SE->Scalars.erase(getValPtr());
5105 // this now dangles!
5106}
5107
Dan Gohman1959b752009-05-19 19:22:47 +00005108void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005109 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005110
5111 // Forget all the expressions associated with users of the old value,
5112 // so that future queries will recompute the expressions using the new
5113 // value.
5114 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005115 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005116 Value *Old = getValPtr();
5117 bool DeleteOld = false;
5118 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5119 UI != UE; ++UI)
5120 Worklist.push_back(*UI);
5121 while (!Worklist.empty()) {
5122 User *U = Worklist.pop_back_val();
5123 // Deleting the Old value will cause this to dangle. Postpone
5124 // that until everything else is done.
5125 if (U == Old) {
5126 DeleteOld = true;
5127 continue;
5128 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005129 if (!Visited.insert(U))
5130 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005131 if (PHINode *PN = dyn_cast<PHINode>(U))
5132 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005133 SE->Scalars.erase(U);
5134 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5135 UI != UE; ++UI)
5136 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005137 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005138 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005139 if (DeleteOld) {
5140 if (PHINode *PN = dyn_cast<PHINode>(Old))
5141 SE->ConstantEvolutionLoopExitValue.erase(PN);
5142 SE->Scalars.erase(Old);
5143 // this now dangles!
5144 }
5145 // this may dangle!
5146}
5147
Dan Gohman1959b752009-05-19 19:22:47 +00005148ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005149 : CallbackVH(V), SE(se) {}
5150
5151//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005152// ScalarEvolution Class Implementation
5153//===----------------------------------------------------------------------===//
5154
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005155ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005156 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005157}
5158
Chris Lattner53e677a2004-04-02 20:23:17 +00005159bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005160 this->F = &F;
5161 LI = &getAnalysis<LoopInfo>();
5162 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005163 return false;
5164}
5165
5166void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005167 Scalars.clear();
5168 BackedgeTakenCounts.clear();
5169 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005170 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005171 UniqueSCEVs.clear();
5172 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005173}
5174
5175void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5176 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005177 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005178}
5179
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005180bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005181 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005182}
5183
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005184static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005185 const Loop *L) {
5186 // Print all inner loops first
5187 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5188 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005189
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005190 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005191
Devang Patelb7211a22007-08-21 00:31:24 +00005192 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005193 L->getExitBlocks(ExitBlocks);
5194 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005195 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005196
Dan Gohman46bdfb02009-02-24 18:55:53 +00005197 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5198 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005199 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005200 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005201 }
5202
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005203 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005204 OS << "Loop " << L->getHeader()->getName() << ": ";
5205
5206 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5207 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5208 } else {
5209 OS << "Unpredictable max backedge-taken count. ";
5210 }
5211
5212 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005213}
5214
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005215void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005216 // ScalarEvolution's implementaiton of the print method is to print
5217 // out SCEV values of all instructions that are interesting. Doing
5218 // this potentially causes it to create new SCEV objects though,
5219 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005220 // observable from outside the class though, so casting away the
5221 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005222 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005223
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005224 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005225 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005226 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005227 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005228 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005229 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005230 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005231
Dan Gohman0c689c52009-06-19 17:49:54 +00005232 const Loop *L = LI->getLoopFor((*I).getParent());
5233
Dan Gohman0bba49c2009-07-07 17:06:11 +00005234 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005235 if (AtUse != SV) {
5236 OS << " --> ";
5237 AtUse->print(OS);
5238 }
5239
5240 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005241 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005242 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005243 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005244 OS << "<<Unknown>>";
5245 } else {
5246 OS << *ExitValue;
5247 }
5248 }
5249
Chris Lattner53e677a2004-04-02 20:23:17 +00005250 OS << "\n";
5251 }
5252
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005253 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5254 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5255 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005256}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005257