blob: 1e6c8561b026c5c34a6c7a2df98e29649ccdea12 [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 Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.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
Owen Andersond13db2c2010-07-21 22:09:45 +0000106INITIALIZE_PASS(ScalarEvolution, "scalar-evolution",
107 "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 {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
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 Gohman3bf63762010-06-18 19:54:20 +0000144 SCEV(FoldingSetNodeIDRef(), 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;
Dan Gohman3bf63762010-06-18 19:54:20 +0000180 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000181 UniqueSCEVs.InsertNode(S, IP);
182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000186 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Dan Gohman0bba49c2009-07-07 17:06:11 +0000189const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000191 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
192 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000193}
194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Dan Gohman3bf63762010-06-18 19:54:20 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000204
Dan Gohman84923602009-04-21 01:25:57 +0000205bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
207}
208
Dan Gohman6e70e312009-09-27 15:26:03 +0000209bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
211}
212
Dan Gohman3bf63762010-06-18 19:54:20 +0000213SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000215 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000216 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
217 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
Dan Gohman3bf63762010-06-18 19:54:20 +0000225SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000228 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
229 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000233void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
236
Dan Gohman3bf63762010-06-18 19:54:20 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000240 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
241 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000242 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000243}
244
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000245void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000247}
248
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000249void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250 const char *OpStr = getOperationStr();
Dan Gohmana5145c82010-04-16 15:03:25 +0000251 OS << "(";
252 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
253 OS << **I;
Oscar Fuentesee56c422010-08-02 06:00:15 +0000254 if (llvm::next(I) != E)
Dan Gohmana5145c82010-04-16 15:03:25 +0000255 OS << OpStr;
256 }
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000257 OS << ")";
258}
259
Dan Gohmanecb403a2009-05-07 14:00:19 +0000260bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
263 return false;
264 }
265 return true;
266}
267
Dan Gohman6e70e312009-09-27 15:26:03 +0000268bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
270 if (!getOperand(i)->properlyDominates(BB, DT))
271 return false;
272 }
273 return true;
274}
275
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000276bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
277 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
278}
279
Dan Gohman6e70e312009-09-27 15:26:03 +0000280bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
281 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
282}
283
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000284void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000285 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000286}
287
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000288const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000289 // In most cases the types of LHS and RHS will be the same, but in some
290 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
291 // depend on the type for correctness, but handling types carefully can
292 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
293 // a pointer type than the RHS, so use the RHS' type here.
294 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000295}
296
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000298 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000299 if (!QueryLoop)
300 return false;
301
302 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000303 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000304 return false;
305
Dan Gohman71c41442010-08-13 20:11:39 +0000306 // This recurrence is invariant w.r.t. QueryLoop if L contains QueryLoop.
307 if (L->contains(QueryLoop))
308 return true;
309
Dan Gohmane890eea2009-06-26 22:17:21 +0000310 // This recurrence is variant w.r.t. QueryLoop if any of its operands
311 // are variant.
312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
313 if (!getOperand(i)->isLoopInvariant(QueryLoop))
314 return false;
315
316 // Otherwise it's loop-invariant.
317 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000318}
319
Dan Gohman39125d82010-02-13 00:19:39 +0000320bool
321SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
322 return DT->dominates(L->getHeader(), BB) &&
323 SCEVNAryExpr::dominates(BB, DT);
324}
325
326bool
327SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
328 // This uses a "dominates" query instead of "properly dominates" query because
329 // the instruction which produces the addrec's value is a PHI, and a PHI
330 // effectively properly dominates its entire containing block.
331 return DT->dominates(L->getHeader(), BB) &&
332 SCEVNAryExpr::properlyDominates(BB, DT);
333}
334
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000335void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000337 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000339 OS << "}<";
340 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
341 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000342}
Chris Lattner53e677a2004-04-02 20:23:17 +0000343
Dan Gohmanab37f502010-08-02 23:49:30 +0000344void SCEVUnknown::deleted() {
345 // Clear this SCEVUnknown from ValuesAtScopes.
346 SE->ValuesAtScopes.erase(this);
347
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
350
351 // Release the value.
352 setValPtr(0);
353}
354
355void SCEVUnknown::allUsesReplacedWith(Value *New) {
356 // Clear this SCEVUnknown from ValuesAtScopes.
357 SE->ValuesAtScopes.erase(this);
358
359 // Remove this SCEVUnknown from the uniquing map.
360 SE->UniqueSCEVs.RemoveNode(this);
361
362 // Update this SCEVUnknown to point to the new value. This is needed
363 // because there may still be outstanding SCEVs which still point to
364 // this SCEVUnknown.
365 setValPtr(New);
366}
367
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000368bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
369 // All non-instruction values are loop invariant. All instructions are loop
370 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000371 // Instructions are never considered invariant in the function body
372 // (null loop) because they are defined within the "loop".
Dan Gohmanab37f502010-08-02 23:49:30 +0000373 if (Instruction *I = dyn_cast<Instruction>(getValue()))
Dan Gohman92329c72009-12-18 01:24:09 +0000374 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375 return true;
376}
Chris Lattner53e677a2004-04-02 20:23:17 +0000377
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000378bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
379 if (Instruction *I = dyn_cast<Instruction>(getValue()))
380 return DT->dominates(I->getParent(), BB);
381 return true;
382}
383
Dan Gohman6e70e312009-09-27 15:26:03 +0000384bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
385 if (Instruction *I = dyn_cast<Instruction>(getValue()))
386 return DT->properlyDominates(I->getParent(), BB);
387 return true;
388}
389
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000390const Type *SCEVUnknown::getType() const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000391 return getValue()->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000392}
Chris Lattner53e677a2004-04-02 20:23:17 +0000393
Dan Gohman0f5efe52010-01-28 02:15:55 +0000394bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000396 if (VCE->getOpcode() == Instruction::PtrToInt)
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000398 if (CE->getOpcode() == Instruction::GetElementPtr &&
399 CE->getOperand(0)->isNullValue() &&
400 CE->getNumOperands() == 2)
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
402 if (CI->isOne()) {
403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
404 ->getElementType();
405 return true;
406 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000407
408 return false;
409}
410
411bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000413 if (VCE->getOpcode() == Instruction::PtrToInt)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000415 if (CE->getOpcode() == Instruction::GetElementPtr &&
416 CE->getOperand(0)->isNullValue()) {
417 const Type *Ty =
418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
419 if (const StructType *STy = dyn_cast<StructType>(Ty))
420 if (!STy->isPacked() &&
421 CE->getNumOperands() == 3 &&
422 CE->getOperand(1)->isNullValue()) {
423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
424 if (CI->isOne() &&
425 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000426 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000427 AllocTy = STy->getElementType(1);
428 return true;
429 }
430 }
431 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000432
433 return false;
434}
435
Dan Gohman4f8eea82010-02-01 18:27:38 +0000436bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(0)->isNullValue() &&
443 CE->getOperand(1)->isNullValue()) {
444 const Type *Ty =
445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
446 // Ignore vector types here so that ScalarEvolutionExpander doesn't
447 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000448 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000449 CTy = Ty;
450 FieldNo = CE->getOperand(2);
451 return true;
452 }
453 }
454
455 return false;
456}
457
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000458void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000459 const Type *AllocTy;
460 if (isSizeOf(AllocTy)) {
461 OS << "sizeof(" << *AllocTy << ")";
462 return;
463 }
464 if (isAlignOf(AllocTy)) {
465 OS << "alignof(" << *AllocTy << ")";
466 return;
467 }
468
Dan Gohman4f8eea82010-02-01 18:27:38 +0000469 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000470 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000471 if (isOffsetOf(CTy, FieldNo)) {
472 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000473 WriteAsOperand(OS, FieldNo, false);
474 OS << ")";
475 return;
476 }
477
478 // Otherwise just print it normally.
Dan Gohmanab37f502010-08-02 23:49:30 +0000479 WriteAsOperand(OS, getValue(), false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000480}
481
Chris Lattner8d741b82004-06-20 06:23:15 +0000482//===----------------------------------------------------------------------===//
483// SCEV Utilities
484//===----------------------------------------------------------------------===//
485
486namespace {
487 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
488 /// than the complexity of the RHS. This comparator is used to canonicalize
489 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000490 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000491 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000492 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000493 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000494
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000495 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000496 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
497 if (LHS == RHS)
498 return false;
499
Dan Gohman72861302009-05-07 14:39:04 +0000500 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000501 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
502 if (LType != RType)
503 return LType < RType;
Dan Gohman72861302009-05-07 14:39:04 +0000504
Dan Gohman3bf63762010-06-18 19:54:20 +0000505 // Aside from the getSCEVType() ordering, the particular ordering
506 // isn't very important except that it's beneficial to be consistent,
507 // so that (a + b) and (b + a) don't end up as different expressions.
508
509 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
510 // not as complete as it could be.
511 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
512 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000513 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000514
515 // Order pointer values after integer values. This helps SCEVExpander
516 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000517 bool LIsPointer = LV->getType()->isPointerTy(),
518 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000519 if (LIsPointer != RIsPointer)
520 return RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000521
522 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000523 unsigned LID = LV->getValueID(),
524 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000525 if (LID != RID)
526 return LID < RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000527
528 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000529 if (const Argument *LA = dyn_cast<Argument>(LV)) {
530 const Argument *RA = cast<Argument>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000531 return LA->getArgNo() < RA->getArgNo();
532 }
533
534 // For instructions, compare their loop depth, and their opcode.
535 // This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000536 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
537 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000538
539 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000540 const BasicBlock *LParent = LInst->getParent(),
541 *RParent = RInst->getParent();
542 if (LParent != RParent) {
543 unsigned LDepth = LI->getLoopDepth(LParent),
544 RDepth = LI->getLoopDepth(RParent);
545 if (LDepth != RDepth)
546 return LDepth < RDepth;
547 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000548
549 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000550 unsigned LNumOps = LInst->getNumOperands(),
551 RNumOps = RInst->getNumOperands();
Dan Gohman304a7a62010-07-23 21:20:52 +0000552 if (LNumOps != RNumOps)
553 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000554 }
555
556 return false;
557 }
558
559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000562 const ConstantInt *LCC = LC->getValue();
563 const ConstantInt *RCC = RC->getValue();
564 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
565 if (LBitWidth != RBitWidth)
566 return LBitWidth < RBitWidth;
567 return LCC->getValue().ult(RCC->getValue());
Dan Gohman3bf63762010-06-18 19:54:20 +0000568 }
569
570 // Compare addrec loop depths.
571 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
572 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000573 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
574 if (LLoop != RLoop) {
575 unsigned LDepth = LLoop->getLoopDepth(),
576 RDepth = RLoop->getLoopDepth();
577 if (LDepth != RDepth)
578 return LDepth < RDepth;
579 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000580 }
581
582 // Lexicographically compare n-ary expressions.
583 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
584 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000585 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
586 for (unsigned i = 0; i != LNumOps; ++i) {
587 if (i >= RNumOps)
Dan Gohman3bf63762010-06-18 19:54:20 +0000588 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000589 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
590 if (operator()(LOp, ROp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000591 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000592 if (operator()(ROp, LOp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000593 return false;
594 }
Dan Gohman304a7a62010-07-23 21:20:52 +0000595 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000596 }
597
598 // Lexicographically compare udiv expressions.
599 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000601 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
602 *RL = RC->getLHS(), *RR = RC->getRHS();
603 if (operator()(LL, RL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000604 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000605 if (operator()(RL, LL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000606 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000607 if (operator()(LR, RR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000608 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000609 if (operator()(RR, LR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000610 return false;
611 return false;
612 }
613
614 // Compare cast expressions by operand.
615 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
616 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
617 return operator()(LC->getOperand(), RC->getOperand());
618 }
619
620 llvm_unreachable("Unknown SCEV kind!");
621 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000622 }
623 };
624}
625
626/// GroupByComplexity - Given a list of SCEV objects, order them by their
627/// complexity, and group objects of the same complexity together by value.
628/// When this routine is finished, we know that any duplicates in the vector are
629/// consecutive and that complexity is monotonically increasing.
630///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000631/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000632/// results from this routine. In other words, we don't want the results of
633/// this to depend on where the addresses of various SCEV objects happened to
634/// land in memory.
635///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000636static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000637 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000638 if (Ops.size() < 2) return; // Noop
639 if (Ops.size() == 2) {
640 // This is the common case, which also happens to be trivially simple.
641 // Special case it.
Dan Gohman3bf63762010-06-18 19:54:20 +0000642 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000643 std::swap(Ops[0], Ops[1]);
644 return;
645 }
646
Dan Gohman3bf63762010-06-18 19:54:20 +0000647 // Do the rough sort by complexity.
648 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
649
650 // Now that we are sorted by complexity, group elements of the same
651 // complexity. Note that this is, at worst, N^2, but the vector is likely to
652 // be extremely short in practice. Note that we take this approach because we
653 // do not want to depend on the addresses of the objects we are grouping.
654 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
655 const SCEV *S = Ops[i];
656 unsigned Complexity = S->getSCEVType();
657
658 // If there are any objects of the same complexity and same value as this
659 // one, group them.
660 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
661 if (Ops[j] == S) { // Found a duplicate.
662 // Move it to immediately after i'th element.
663 std::swap(Ops[i+1], Ops[j]);
664 ++i; // no need to rescan it.
665 if (i == e-2) return; // Done!
666 }
667 }
668 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000669}
670
Chris Lattner53e677a2004-04-02 20:23:17 +0000671
Chris Lattner53e677a2004-04-02 20:23:17 +0000672
673//===----------------------------------------------------------------------===//
674// Simple SCEV method implementations
675//===----------------------------------------------------------------------===//
676
Eli Friedmanb42a6262008-08-04 23:49:06 +0000677/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000678/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000679static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000680 ScalarEvolution &SE,
681 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000682 // Handle the simplest case efficiently.
683 if (K == 1)
684 return SE.getTruncateOrZeroExtend(It, ResultTy);
685
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000686 // We are using the following formula for BC(It, K):
687 //
688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
689 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000690 // Suppose, W is the bitwidth of the return value. We must be prepared for
691 // overflow. Hence, we must assure that the result of our computation is
692 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
693 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000694 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000695 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000696 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000697 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
698 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000699 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000700 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000701 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000702 // This formula is trivially equivalent to the previous formula. However,
703 // this formula can be implemented much more efficiently. The trick is that
704 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
705 // arithmetic. To do exact division in modular arithmetic, all we have
706 // to do is multiply by the inverse. Therefore, this step can be done at
707 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000708 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000709 // The next issue is how to safely do the division by 2^T. The way this
710 // is done is by doing the multiplication step at a width of at least W + T
711 // bits. This way, the bottom W+T bits of the product are accurate. Then,
712 // when we perform the division by 2^T (which is equivalent to a right shift
713 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
714 // truncated out after the division by 2^T.
715 //
716 // In comparison to just directly using the first formula, this technique
717 // is much more efficient; using the first formula requires W * K bits,
718 // but this formula less than W + K bits. Also, the first formula requires
719 // a division step, whereas this formula only requires multiplies and shifts.
720 //
721 // It doesn't matter whether the subtraction step is done in the calculation
722 // width or the input iteration count's width; if the subtraction overflows,
723 // the result must be zero anyway. We prefer here to do it in the width of
724 // the induction variable because it helps a lot for certain cases; CodeGen
725 // isn't smart enough to ignore the overflow, which leads to much less
726 // efficient code if the width of the subtraction is wider than the native
727 // register width.
728 //
729 // (It's possible to not widen at all by pulling out factors of 2 before
730 // the multiplication; for example, K=2 can be calculated as
731 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
732 // extra arithmetic, so it's not an obvious win, and it gets
733 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000734
Eli Friedmanb42a6262008-08-04 23:49:06 +0000735 // Protection from insane SCEVs; this bound is conservative,
736 // but it probably doesn't matter.
737 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000738 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000739
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000740 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000741
Eli Friedmanb42a6262008-08-04 23:49:06 +0000742 // Calculate K! / 2^T and T; we divide out the factors of two before
743 // multiplying for calculating K! / 2^T to avoid overflow.
744 // Other overflow doesn't matter because we only care about the bottom
745 // W bits of the result.
746 APInt OddFactorial(W, 1);
747 unsigned T = 1;
748 for (unsigned i = 3; i <= K; ++i) {
749 APInt Mult(W, i);
750 unsigned TwoFactors = Mult.countTrailingZeros();
751 T += TwoFactors;
752 Mult = Mult.lshr(TwoFactors);
753 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000754 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000755
Eli Friedmanb42a6262008-08-04 23:49:06 +0000756 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000757 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000758
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000759 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000760 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
761
762 // Calculate the multiplicative inverse of K! / 2^T;
763 // this multiplication factor will perform the exact division by
764 // K! / 2^T.
765 APInt Mod = APInt::getSignedMinValue(W+1);
766 APInt MultiplyFactor = OddFactorial.zext(W+1);
767 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
768 MultiplyFactor = MultiplyFactor.trunc(W);
769
770 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000771 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
772 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000773 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000774 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000775 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000776 Dividend = SE.getMulExpr(Dividend,
777 SE.getTruncateOrZeroExtend(S, CalculationTy));
778 }
779
780 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000781 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000782
783 // Truncate the result, and divide by K! / 2^T.
784
785 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
786 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000787}
788
Chris Lattner53e677a2004-04-02 20:23:17 +0000789/// evaluateAtIteration - Return the value of this chain of recurrences at
790/// the specified iteration number. We can evaluate this recurrence by
791/// multiplying each element in the chain by the binomial coefficient
792/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
793///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000794/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000795///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000796/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000797///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000798const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000799 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000800 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000801 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000802 // The computation is correct in the face of overflow provided that the
803 // multiplication is performed _after_ the evaluation of the binomial
804 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000805 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000806 if (isa<SCEVCouldNotCompute>(Coeff))
807 return Coeff;
808
809 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 }
811 return Result;
812}
813
Chris Lattner53e677a2004-04-02 20:23:17 +0000814//===----------------------------------------------------------------------===//
815// SCEV Expression folder implementations
816//===----------------------------------------------------------------------===//
817
Dan Gohman0bba49c2009-07-07 17:06:11 +0000818const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000819 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000820 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000821 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000822 assert(isSCEVable(Ty) &&
823 "This is not a conversion to a SCEVable type!");
824 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000825
Dan Gohmanc050fd92009-07-13 20:50:19 +0000826 FoldingSetNodeID ID;
827 ID.AddInteger(scTruncate);
828 ID.AddPointer(Op);
829 ID.AddPointer(Ty);
830 void *IP = 0;
831 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
832
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000833 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000834 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000835 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000836 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
837 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000838
Dan Gohman20900ca2009-04-22 16:20:48 +0000839 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000840 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000841 return getTruncateExpr(ST->getOperand(), Ty);
842
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000843 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000844 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000845 return getTruncateOrSignExtend(SS->getOperand(), Ty);
846
847 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000848 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000849 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
850
Dan Gohman6864db62009-06-18 16:24:47 +0000851 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000852 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000853 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000855 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
856 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000857 }
858
Dan Gohmanf53462d2010-07-15 20:02:11 +0000859 // As a special case, fold trunc(undef) to undef. We don't want to
860 // know too much about SCEVUnknowns, but this special case is handy
861 // and harmless.
862 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
863 if (isa<UndefValue>(U->getValue()))
864 return getSCEV(UndefValue::get(Ty));
865
Dan Gohman420ab912010-06-25 18:47:08 +0000866 // The cast wasn't folded; create an explicit cast node. We can reuse
867 // the existing insert position since if we get here, we won't have
868 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000869 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
870 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000871 UniqueSCEVs.InsertNode(S, IP);
872 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000873}
874
Dan Gohman0bba49c2009-07-07 17:06:11 +0000875const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000876 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000877 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000878 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000879 assert(isSCEVable(Ty) &&
880 "This is not a conversion to a SCEVable type!");
881 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000882
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000883 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000884 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
885 return getConstant(
886 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
887 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000888
Dan Gohman20900ca2009-04-22 16:20:48 +0000889 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000890 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000891 return getZeroExtendExpr(SZ->getOperand(), Ty);
892
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000893 // Before doing any expensive analysis, check to see if we've already
894 // computed a SCEV for this Op and Ty.
895 FoldingSetNodeID ID;
896 ID.AddInteger(scZeroExtend);
897 ID.AddPointer(Op);
898 ID.AddPointer(Ty);
899 void *IP = 0;
900 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
901
Dan Gohman01ecca22009-04-27 20:16:15 +0000902 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000903 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000904 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000905 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000906 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000907 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000908 const SCEV *Start = AR->getStart();
909 const SCEV *Step = AR->getStepRecurrence(*this);
910 unsigned BitWidth = getTypeSizeInBits(AR->getType());
911 const Loop *L = AR->getLoop();
912
Dan Gohmaneb490a72009-07-25 01:22:26 +0000913 // If we have special knowledge that this addrec won't overflow,
914 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000915 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000916 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
917 getZeroExtendExpr(Step, Ty),
918 L);
919
Dan Gohman01ecca22009-04-27 20:16:15 +0000920 // Check whether the backedge-taken count is SCEVCouldNotCompute.
921 // Note that this serves two purposes: It filters out loops that are
922 // simply not analyzable, and it covers the case where this code is
923 // being called from within backedge-taken count analysis, such that
924 // attempting to ask for the backedge-taken count would likely result
925 // in infinite recursion. In the later case, the analysis code will
926 // cope with a conservative value, and it will take care to purge
927 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000928 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000929 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000930 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000931 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000932
933 // Check whether the backedge-taken count can be losslessly casted to
934 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000935 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000936 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000937 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000938 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
939 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000940 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000941 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000942 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000943 const SCEV *Add = getAddExpr(Start, ZMul);
944 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000945 getAddExpr(getZeroExtendExpr(Start, WideTy),
946 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
947 getZeroExtendExpr(Step, WideTy)));
948 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000949 // Return the expression with the addrec on the outside.
950 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
951 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000952 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000953
954 // Similar to above, only this time treat the step value as signed.
955 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000956 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000957 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000958 OperandExtendedAdd =
959 getAddExpr(getZeroExtendExpr(Start, WideTy),
960 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
961 getSignExtendExpr(Step, WideTy)));
962 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000963 // Return the expression with the addrec on the outside.
964 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
965 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000966 L);
967 }
968
969 // If the backedge is guarded by a comparison with the pre-inc value
970 // the addrec is safe. Also, if the entry is guarded by a comparison
971 // with the start value and the backedge is guarded by a comparison
972 // with the post-inc value, the addrec is safe.
973 if (isKnownPositive(Step)) {
974 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
975 getUnsignedRange(Step).getUnsignedMax());
976 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000977 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000978 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
979 AR->getPostIncExpr(*this), N)))
980 // Return the expression with the addrec on the outside.
981 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
982 getZeroExtendExpr(Step, Ty),
983 L);
984 } else if (isKnownNegative(Step)) {
985 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
986 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000987 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
988 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000989 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
990 AR->getPostIncExpr(*this), N)))
991 // Return the expression with the addrec on the outside.
992 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
993 getSignExtendExpr(Step, Ty),
994 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000995 }
996 }
997 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000998
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000999 // The cast wasn't folded; create an explicit cast node.
1000 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001001 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001002 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1003 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001004 UniqueSCEVs.InsertNode(S, IP);
1005 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001006}
1007
Dan Gohman0bba49c2009-07-07 17:06:11 +00001008const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001009 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001010 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001011 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001012 assert(isSCEVable(Ty) &&
1013 "This is not a conversion to a SCEVable type!");
1014 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001015
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001016 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001017 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1018 return getConstant(
1019 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1020 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001021
Dan Gohman20900ca2009-04-22 16:20:48 +00001022 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001023 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001024 return getSignExtendExpr(SS->getOperand(), Ty);
1025
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001026 // Before doing any expensive analysis, check to see if we've already
1027 // computed a SCEV for this Op and Ty.
1028 FoldingSetNodeID ID;
1029 ID.AddInteger(scSignExtend);
1030 ID.AddPointer(Op);
1031 ID.AddPointer(Ty);
1032 void *IP = 0;
1033 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1034
Dan Gohman01ecca22009-04-27 20:16:15 +00001035 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001036 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001037 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001038 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001039 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001040 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001041 const SCEV *Start = AR->getStart();
1042 const SCEV *Step = AR->getStepRecurrence(*this);
1043 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1044 const Loop *L = AR->getLoop();
1045
Dan Gohmaneb490a72009-07-25 01:22:26 +00001046 // If we have special knowledge that this addrec won't overflow,
1047 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001048 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001049 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1050 getSignExtendExpr(Step, Ty),
1051 L);
1052
Dan Gohman01ecca22009-04-27 20:16:15 +00001053 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1054 // Note that this serves two purposes: It filters out loops that are
1055 // simply not analyzable, and it covers the case where this code is
1056 // being called from within backedge-taken count analysis, such that
1057 // attempting to ask for the backedge-taken count would likely result
1058 // in infinite recursion. In the later case, the analysis code will
1059 // cope with a conservative value, and it will take care to purge
1060 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001061 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001062 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001063 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001064 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001065
1066 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001067 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001068 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001069 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001070 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001071 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1072 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001073 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001074 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001075 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001076 const SCEV *Add = getAddExpr(Start, SMul);
1077 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001078 getAddExpr(getSignExtendExpr(Start, WideTy),
1079 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1080 getSignExtendExpr(Step, WideTy)));
1081 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001082 // Return the expression with the addrec on the outside.
1083 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1084 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001085 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001086
1087 // Similar to above, only this time treat the step value as unsigned.
1088 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001089 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001090 Add = getAddExpr(Start, UMul);
1091 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001092 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001093 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1094 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001095 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001096 // Return the expression with the addrec on the outside.
1097 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1098 getZeroExtendExpr(Step, Ty),
1099 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001100 }
1101
1102 // If the backedge is guarded by a comparison with the pre-inc value
1103 // the addrec is safe. Also, if the entry is guarded by a comparison
1104 // with the start value and the backedge is guarded by a comparison
1105 // with the post-inc value, the addrec is safe.
1106 if (isKnownPositive(Step)) {
1107 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1108 getSignedRange(Step).getSignedMax());
1109 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001110 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001111 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1112 AR->getPostIncExpr(*this), N)))
1113 // Return the expression with the addrec on the outside.
1114 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1115 getSignExtendExpr(Step, Ty),
1116 L);
1117 } else if (isKnownNegative(Step)) {
1118 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1119 getSignedRange(Step).getSignedMin());
1120 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001121 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001122 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1123 AR->getPostIncExpr(*this), N)))
1124 // Return the expression with the addrec on the outside.
1125 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1126 getSignExtendExpr(Step, Ty),
1127 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001128 }
1129 }
1130 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001131
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001132 // The cast wasn't folded; create an explicit cast node.
1133 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001134 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001135 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1136 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001137 UniqueSCEVs.InsertNode(S, IP);
1138 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001139}
1140
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001141/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1142/// unspecified bits out to the given type.
1143///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001144const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001145 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001146 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1147 "This is not an extending conversion!");
1148 assert(isSCEVable(Ty) &&
1149 "This is not a conversion to a SCEVable type!");
1150 Ty = getEffectiveSCEVType(Ty);
1151
1152 // Sign-extend negative constants.
1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1154 if (SC->getValue()->getValue().isNegative())
1155 return getSignExtendExpr(Op, Ty);
1156
1157 // Peel off a truncate cast.
1158 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001159 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001160 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1161 return getAnyExtendExpr(NewOp, Ty);
1162 return getTruncateOrNoop(NewOp, Ty);
1163 }
1164
1165 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001166 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001167 if (!isa<SCEVZeroExtendExpr>(ZExt))
1168 return ZExt;
1169
1170 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001171 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001172 if (!isa<SCEVSignExtendExpr>(SExt))
1173 return SExt;
1174
Dan Gohmana10756e2010-01-21 02:09:26 +00001175 // Force the cast to be folded into the operands of an addrec.
1176 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1177 SmallVector<const SCEV *, 4> Ops;
1178 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1179 I != E; ++I)
1180 Ops.push_back(getAnyExtendExpr(*I, Ty));
1181 return getAddRecExpr(Ops, AR->getLoop());
1182 }
1183
Dan Gohmanf53462d2010-07-15 20:02:11 +00001184 // As a special case, fold anyext(undef) to undef. We don't want to
1185 // know too much about SCEVUnknowns, but this special case is handy
1186 // and harmless.
1187 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1188 if (isa<UndefValue>(U->getValue()))
1189 return getSCEV(UndefValue::get(Ty));
1190
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001191 // If the expression is obviously signed, use the sext cast value.
1192 if (isa<SCEVSMaxExpr>(Op))
1193 return SExt;
1194
1195 // Absent any other information, use the zext cast value.
1196 return ZExt;
1197}
1198
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001199/// CollectAddOperandsWithScales - Process the given Ops list, which is
1200/// a list of operands to be added under the given scale, update the given
1201/// map. This is a helper function for getAddRecExpr. As an example of
1202/// what it does, given a sequence of operands that would form an add
1203/// expression like this:
1204///
1205/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1206///
1207/// where A and B are constants, update the map with these values:
1208///
1209/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1210///
1211/// and add 13 + A*B*29 to AccumulatedConstant.
1212/// This will allow getAddRecExpr to produce this:
1213///
1214/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1215///
1216/// This form often exposes folding opportunities that are hidden in
1217/// the original operand list.
1218///
1219/// Return true iff it appears that any interesting folding opportunities
1220/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1221/// the common case where no interesting opportunities are present, and
1222/// is also used as a check to avoid infinite recursion.
1223///
1224static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001225CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1226 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001227 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001228 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001229 const APInt &Scale,
1230 ScalarEvolution &SE) {
1231 bool Interesting = false;
1232
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001233 // Iterate over the add operands. They are sorted, with constants first.
1234 unsigned i = 0;
1235 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1236 ++i;
1237 // Pull a buried constant out to the outside.
1238 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1239 Interesting = true;
1240 AccumulatedConstant += Scale * C->getValue()->getValue();
1241 }
1242
1243 // Next comes everything else. We're especially interested in multiplies
1244 // here, but they're in the middle, so just visit the rest with one loop.
1245 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001246 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1247 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1248 APInt NewScale =
1249 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1250 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1251 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001252 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001253 Interesting |=
1254 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001255 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001256 NewScale, SE);
1257 } else {
1258 // A multiplication of a constant with some other value. Update
1259 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001260 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1261 const SCEV *Key = SE.getMulExpr(MulOps);
1262 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001263 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001264 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001265 NewOps.push_back(Pair.first->first);
1266 } else {
1267 Pair.first->second += NewScale;
1268 // The map already had an entry for this value, which may indicate
1269 // a folding opportunity.
1270 Interesting = true;
1271 }
1272 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001273 } else {
1274 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001275 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001276 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001277 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001278 NewOps.push_back(Pair.first->first);
1279 } else {
1280 Pair.first->second += Scale;
1281 // The map already had an entry for this value, which may indicate
1282 // a folding opportunity.
1283 Interesting = true;
1284 }
1285 }
1286 }
1287
1288 return Interesting;
1289}
1290
1291namespace {
1292 struct APIntCompare {
1293 bool operator()(const APInt &LHS, const APInt &RHS) const {
1294 return LHS.ult(RHS);
1295 }
1296 };
1297}
1298
Dan Gohman6c0866c2009-05-24 23:45:28 +00001299/// getAddExpr - Get a canonical add expression, or something simpler if
1300/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001301const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1302 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001304 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001305#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001306 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001307 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001309 "SCEVAddExpr operand types don't match!");
1310#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001311
Dan Gohmana10756e2010-01-21 02:09:26 +00001312 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1313 if (!HasNUW && HasNSW) {
1314 bool All = true;
1315 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1316 if (!isKnownNonNegative(Ops[i])) {
1317 All = false;
1318 break;
1319 }
1320 if (All) HasNUW = true;
1321 }
1322
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001324 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001325
1326 // If there are any constants, fold them together.
1327 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001328 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001330 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001331 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001332 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001333 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1334 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001335 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001336 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001337 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 }
1339
1340 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001341 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001342 Ops.erase(Ops.begin());
1343 --Idx;
1344 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001345
Dan Gohmanbca091d2010-04-12 23:08:18 +00001346 if (Ops.size() == 1) return Ops[0];
1347 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001348
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 // Okay, check to see if the same value occurs in the operand list twice. If
1350 // so, merge them together into an multiply expression. Since we sorted the
1351 // list, these values are required to be adjacent.
1352 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001353 bool FoundMatch = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001354 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1355 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1356 // Found a match, merge the two values into a multiply, and add any
1357 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001358 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman58a85b92010-08-13 20:17:14 +00001359 const SCEV *Mul = getMulExpr(Two, Ops[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 if (Ops.size() == 2)
1361 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001362 Ops[i] = Mul;
1363 Ops.erase(Ops.begin()+i+1);
1364 --i; --e;
1365 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001366 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001367 if (FoundMatch)
1368 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001369
Dan Gohman728c7f32009-05-08 21:03:19 +00001370 // Check for truncates. If all the operands are truncated from the same
1371 // type, see if factoring out the truncate would permit the result to be
1372 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1373 // if the contents of the resulting outer trunc fold to something simple.
1374 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1375 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1376 const Type *DstType = Trunc->getType();
1377 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001378 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001379 bool Ok = true;
1380 // Check all the operands to see if they can be represented in the
1381 // source type of the truncate.
1382 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1383 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1384 if (T->getOperand()->getType() != SrcType) {
1385 Ok = false;
1386 break;
1387 }
1388 LargeOps.push_back(T->getOperand());
1389 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001390 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001391 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001392 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001393 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1394 if (const SCEVTruncateExpr *T =
1395 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1396 if (T->getOperand()->getType() != SrcType) {
1397 Ok = false;
1398 break;
1399 }
1400 LargeMulOps.push_back(T->getOperand());
1401 } else if (const SCEVConstant *C =
1402 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001403 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001404 } else {
1405 Ok = false;
1406 break;
1407 }
1408 }
1409 if (Ok)
1410 LargeOps.push_back(getMulExpr(LargeMulOps));
1411 } else {
1412 Ok = false;
1413 break;
1414 }
1415 }
1416 if (Ok) {
1417 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001418 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001419 // If it folds to something simple, use it. Otherwise, don't.
1420 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1421 return getTruncateExpr(Fold, DstType);
1422 }
1423 }
1424
1425 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001426 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1427 ++Idx;
1428
1429 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 if (Idx < Ops.size()) {
1431 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001432 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001433 // If we have an add, expand the add operands onto the end of the operands
1434 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001435 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001436 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 DeletedAdd = true;
1438 }
1439
1440 // If we deleted at least one add, we added operands to the end of the list,
1441 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001442 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001443 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001444 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001445 }
1446
1447 // Skip over the add expression until we get to a multiply.
1448 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1449 ++Idx;
1450
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001451 // Check to see if there are any folding opportunities present with
1452 // operands multiplied by constant values.
1453 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1454 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001455 DenseMap<const SCEV *, APInt> M;
1456 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001457 APInt AccumulatedConstant(BitWidth, 0);
1458 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001459 Ops.data(), Ops.size(),
1460 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001461 // Some interesting folding opportunity is present, so its worthwhile to
1462 // re-generate the operands list. Group the operands by constant scale,
1463 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001464 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1465 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001466 E = NewOps.end(); I != E; ++I)
1467 MulOpLists[M.find(*I)->second].push_back(*I);
1468 // Re-generate the operands list.
1469 Ops.clear();
1470 if (AccumulatedConstant != 0)
1471 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001472 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1473 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001474 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001475 Ops.push_back(getMulExpr(getConstant(I->first),
1476 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001477 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001478 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001479 if (Ops.size() == 1)
1480 return Ops[0];
1481 return getAddExpr(Ops);
1482 }
1483 }
1484
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 // If we are adding something to a multiply expression, make sure the
1486 // something is not already an operand of the multiply. If so, merge it into
1487 // the multiply.
1488 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001489 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001490 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001491 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001492 if (isa<SCEVConstant>(MulOpSCEV))
1493 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001495 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001497 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001498 if (Mul->getNumOperands() != 2) {
1499 // If the multiply has more than two operands, we must get the
1500 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001501 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001502 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001503 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001505 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001506 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001507 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 if (Ops.size() == 2) return OuterMul;
1509 if (AddOp < Idx) {
1510 Ops.erase(Ops.begin()+AddOp);
1511 Ops.erase(Ops.begin()+Idx-1);
1512 } else {
1513 Ops.erase(Ops.begin()+Idx);
1514 Ops.erase(Ops.begin()+AddOp-1);
1515 }
1516 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001517 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001519
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 // Check this multiply against other multiplies being added together.
Dan Gohman727356f2010-08-12 15:00:23 +00001521 bool AnyFold = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001522 for (unsigned OtherMulIdx = Idx+1;
1523 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1524 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001525 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 // If MulOp occurs in OtherMul, we can fold the two multiplies
1527 // together.
1528 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1529 OMulOp != e; ++OMulOp)
1530 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1531 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001532 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001534 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1535 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001537 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001539 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001541 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1542 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001544 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001545 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001546 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1547 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 if (Ops.size() == 2) return OuterMul;
Dan Gohman727356f2010-08-12 15:00:23 +00001549 Ops[Idx] = OuterMul;
1550 Ops.erase(Ops.begin()+OtherMulIdx);
1551 OtherMulIdx = Idx;
1552 AnyFold = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001553 }
1554 }
Dan Gohman727356f2010-08-12 15:00:23 +00001555 if (AnyFold)
1556 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 }
1558 }
1559
1560 // If there are any add recurrences in the operands list, see if any other
1561 // added values are loop invariant. If so, we can fold them into the
1562 // recurrence.
1563 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1564 ++Idx;
1565
1566 // Scan over all recurrences, trying to fold loop invariants into them.
1567 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1568 // Scan all of the other operands to this add and add them to the vector if
1569 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001570 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001571 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001572 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001573 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001574 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 LIOps.push_back(Ops[i]);
1576 Ops.erase(Ops.begin()+i);
1577 --i; --e;
1578 }
1579
1580 // If we found some loop invariants, fold them into the recurrence.
1581 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001582 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001583 LIOps.push_back(AddRec->getStart());
1584
Dan Gohman0bba49c2009-07-07 17:06:11 +00001585 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001586 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001587 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001588
Dan Gohmanb9f96512010-06-30 07:16:37 +00001589 // Build the new addrec. Propagate the NUW and NSW flags if both the
1590 // outer add and the inner addrec are guaranteed to have no overflow.
1591 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1592 HasNUW && AddRec->hasNoUnsignedWrap(),
1593 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001594
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 // If all of the other operands were loop invariant, we are done.
1596 if (Ops.size() == 1) return NewRec;
1597
1598 // Otherwise, add the folded AddRec by the non-liv parts.
1599 for (unsigned i = 0;; ++i)
1600 if (Ops[i] == AddRec) {
1601 Ops[i] = NewRec;
1602 break;
1603 }
Dan Gohman246b2562007-10-22 18:31:58 +00001604 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 }
1606
1607 // Okay, if there weren't any loop invariants to be folded, check to see if
1608 // there are multiple AddRec's with the same loop induction variable being
1609 // added together. If so, we can fold them.
1610 for (unsigned OtherIdx = Idx+1;
1611 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1612 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001613 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001614 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001616 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1617 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001618 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1619 if (i >= NewOps.size()) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001620 NewOps.append(OtherAddRec->op_begin()+i,
Chris Lattner53e677a2004-04-02 20:23:17 +00001621 OtherAddRec->op_end());
1622 break;
1623 }
Dan Gohman246b2562007-10-22 18:31:58 +00001624 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001625 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001626 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001627
1628 if (Ops.size() == 2) return NewAddRec;
1629
1630 Ops.erase(Ops.begin()+Idx);
1631 Ops.erase(Ops.begin()+OtherIdx-1);
1632 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001633 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001634 }
1635 }
1636
1637 // Otherwise couldn't fold anything into this recurrence. Move onto the
1638 // next one.
1639 }
1640
1641 // Okay, it looks like we really DO need an add expr. Check to see if we
1642 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001643 FoldingSetNodeID ID;
1644 ID.AddInteger(scAddExpr);
1645 ID.AddInteger(Ops.size());
1646 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1647 ID.AddPointer(Ops[i]);
1648 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001649 SCEVAddExpr *S =
1650 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1651 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001652 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1653 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001654 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1655 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001656 UniqueSCEVs.InsertNode(S, IP);
1657 }
Dan Gohman3645b012009-10-09 00:10:36 +00001658 if (HasNUW) S->setHasNoUnsignedWrap(true);
1659 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001660 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001661}
1662
Dan Gohman6c0866c2009-05-24 23:45:28 +00001663/// getMulExpr - Get a canonical multiply expression, or something simpler if
1664/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001665const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1666 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001667 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001668 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001669#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001670 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001671 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001672 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001673 "SCEVMulExpr operand types don't match!");
1674#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001675
Dan Gohmana10756e2010-01-21 02:09:26 +00001676 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1677 if (!HasNUW && HasNSW) {
1678 bool All = true;
1679 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1680 if (!isKnownNonNegative(Ops[i])) {
1681 All = false;
1682 break;
1683 }
1684 if (All) HasNUW = true;
1685 }
1686
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001688 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001689
1690 // If there are any constants, fold them together.
1691 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001692 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001693
1694 // C1*(C2+V) -> C1*C2 + C1*V
1695 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001696 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001697 if (Add->getNumOperands() == 2 &&
1698 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001699 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1700 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001701
Chris Lattner53e677a2004-04-02 20:23:17 +00001702 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001703 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001704 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001705 ConstantInt *Fold = ConstantInt::get(getContext(),
1706 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001707 RHSC->getValue()->getValue());
1708 Ops[0] = getConstant(Fold);
1709 Ops.erase(Ops.begin()+1); // Erase the folded element
1710 if (Ops.size() == 1) return Ops[0];
1711 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001712 }
1713
1714 // If we are left with a constant one being multiplied, strip it off.
1715 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1716 Ops.erase(Ops.begin());
1717 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001718 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001719 // If we have a multiply of zero, it will always be zero.
1720 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001721 } else if (Ops[0]->isAllOnesValue()) {
1722 // If we have a mul by -1 of an add, try distributing the -1 among the
1723 // add operands.
1724 if (Ops.size() == 2)
1725 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1726 SmallVector<const SCEV *, 4> NewOps;
1727 bool AnyFolded = false;
1728 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1729 I != E; ++I) {
1730 const SCEV *Mul = getMulExpr(Ops[0], *I);
1731 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1732 NewOps.push_back(Mul);
1733 }
1734 if (AnyFolded)
1735 return getAddExpr(NewOps);
1736 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001738
1739 if (Ops.size() == 1)
1740 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001741 }
1742
1743 // Skip over the add expression until we get to a multiply.
1744 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1745 ++Idx;
1746
Chris Lattner53e677a2004-04-02 20:23:17 +00001747 // If there are mul operands inline them all into this expression.
1748 if (Idx < Ops.size()) {
1749 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001750 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 // If we have an mul, expand the mul operands onto the end of the operands
1752 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001753 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001754 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001755 DeletedMul = true;
1756 }
1757
1758 // If we deleted at least one mul, we added operands to the end of the list,
1759 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001760 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001761 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001762 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001763 }
1764
1765 // If there are any add recurrences in the operands list, see if any other
1766 // added values are loop invariant. If so, we can fold them into the
1767 // recurrence.
1768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1769 ++Idx;
1770
1771 // Scan over all recurrences, trying to fold loop invariants into them.
1772 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1773 // Scan all of the other operands to this mul and add them to the vector if
1774 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001775 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001776 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1778 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1779 LIOps.push_back(Ops[i]);
1780 Ops.erase(Ops.begin()+i);
1781 --i; --e;
1782 }
1783
1784 // If we found some loop invariants, fold them into the recurrence.
1785 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001786 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001787 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001788 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001789 const SCEV *Scale = getMulExpr(LIOps);
1790 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1791 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001792
Dan Gohmanb9f96512010-06-30 07:16:37 +00001793 // Build the new addrec. Propagate the NUW and NSW flags if both the
1794 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00001795 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1796 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001797 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001798
1799 // If all of the other operands were loop invariant, we are done.
1800 if (Ops.size() == 1) return NewRec;
1801
1802 // Otherwise, multiply the folded AddRec by the non-liv parts.
1803 for (unsigned i = 0;; ++i)
1804 if (Ops[i] == AddRec) {
1805 Ops[i] = NewRec;
1806 break;
1807 }
Dan Gohman246b2562007-10-22 18:31:58 +00001808 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001809 }
1810
1811 // Okay, if there weren't any loop invariants to be folded, check to see if
1812 // there are multiple AddRec's with the same loop induction variable being
1813 // multiplied together. If so, we can fold them.
1814 for (unsigned OtherIdx = Idx+1;
1815 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1816 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001817 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001818 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1819 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001820 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001821 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001822 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001823 const SCEV *B = F->getStepRecurrence(*this);
1824 const SCEV *D = G->getStepRecurrence(*this);
1825 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001826 getMulExpr(G, B),
1827 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001828 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001829 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001830 if (Ops.size() == 2) return NewAddRec;
1831
1832 Ops.erase(Ops.begin()+Idx);
1833 Ops.erase(Ops.begin()+OtherIdx-1);
1834 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001835 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001836 }
1837 }
1838
1839 // Otherwise couldn't fold anything into this recurrence. Move onto the
1840 // next one.
1841 }
1842
1843 // Okay, it looks like we really DO need an mul expr. Check to see if we
1844 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001845 FoldingSetNodeID ID;
1846 ID.AddInteger(scMulExpr);
1847 ID.AddInteger(Ops.size());
1848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1849 ID.AddPointer(Ops[i]);
1850 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001851 SCEVMulExpr *S =
1852 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1853 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001854 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1855 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001856 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1857 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001858 UniqueSCEVs.InsertNode(S, IP);
1859 }
Dan Gohman3645b012009-10-09 00:10:36 +00001860 if (HasNUW) S->setHasNoUnsignedWrap(true);
1861 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001862 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001863}
1864
Andreas Bolka8a11c982009-08-07 22:55:26 +00001865/// getUDivExpr - Get a canonical unsigned division expression, or something
1866/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001867const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1868 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001869 assert(getEffectiveSCEVType(LHS->getType()) ==
1870 getEffectiveSCEVType(RHS->getType()) &&
1871 "SCEVUDivExpr operand types don't match!");
1872
Dan Gohman622ed672009-05-04 22:02:23 +00001873 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001874 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001875 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001876 // If the denominator is zero, the result of the udiv is undefined. Don't
1877 // try to analyze it, because the resolution chosen here may differ from
1878 // the resolution chosen in other parts of the compiler.
1879 if (!RHSC->getValue()->isZero()) {
1880 // Determine if the division can be folded into the operands of
1881 // its operands.
1882 // TODO: Generalize this to non-constants by using known-bits information.
1883 const Type *Ty = LHS->getType();
1884 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001885 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001886 // For non-power-of-two values, effectively round the value up to the
1887 // nearest power of two.
1888 if (!RHSC->getValue()->getValue().isPowerOf2())
1889 ++MaxShiftAmt;
1890 const IntegerType *ExtTy =
1891 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1892 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1893 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1894 if (const SCEVConstant *Step =
1895 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1896 if (!Step->getValue()->getValue()
1897 .urem(RHSC->getValue()->getValue()) &&
1898 getZeroExtendExpr(AR, ExtTy) ==
1899 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1900 getZeroExtendExpr(Step, ExtTy),
1901 AR->getLoop())) {
1902 SmallVector<const SCEV *, 4> Operands;
1903 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1904 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1905 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001906 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001907 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1908 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1909 SmallVector<const SCEV *, 4> Operands;
1910 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1911 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1912 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1913 // Find an operand that's safely divisible.
1914 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1915 const SCEV *Op = M->getOperand(i);
1916 const SCEV *Div = getUDivExpr(Op, RHSC);
1917 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1918 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1919 M->op_end());
1920 Operands[i] = Div;
1921 return getMulExpr(Operands);
1922 }
1923 }
Dan Gohman185cf032009-05-08 20:18:49 +00001924 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001925 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1926 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1927 SmallVector<const SCEV *, 4> Operands;
1928 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1929 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1930 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1931 Operands.clear();
1932 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1933 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1934 if (isa<SCEVUDivExpr>(Op) ||
1935 getMulExpr(Op, RHS) != A->getOperand(i))
1936 break;
1937 Operands.push_back(Op);
1938 }
1939 if (Operands.size() == A->getNumOperands())
1940 return getAddExpr(Operands);
1941 }
1942 }
Dan Gohman185cf032009-05-08 20:18:49 +00001943
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001944 // Fold if both operands are constant.
1945 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1946 Constant *LHSCV = LHSC->getValue();
1947 Constant *RHSCV = RHSC->getValue();
1948 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1949 RHSCV)));
1950 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001951 }
1952 }
1953
Dan Gohman1c343752009-06-27 21:21:31 +00001954 FoldingSetNodeID ID;
1955 ID.AddInteger(scUDivExpr);
1956 ID.AddPointer(LHS);
1957 ID.AddPointer(RHS);
1958 void *IP = 0;
1959 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001960 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1961 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001962 UniqueSCEVs.InsertNode(S, IP);
1963 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001964}
1965
1966
Dan Gohman6c0866c2009-05-24 23:45:28 +00001967/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1968/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001969const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001970 const SCEV *Step, const Loop *L,
1971 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001972 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001973 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001974 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001975 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001976 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001977 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001978 }
1979
1980 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001981 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001982}
1983
Dan Gohman6c0866c2009-05-24 23:45:28 +00001984/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1985/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001986const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001987ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001988 const Loop *L,
1989 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001990 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001991#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001992 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001993 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001994 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001995 "SCEVAddRecExpr operand types don't match!");
1996#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001997
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001998 if (Operands.back()->isZero()) {
1999 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00002000 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002001 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002002
Dan Gohmanbc028532010-02-19 18:49:22 +00002003 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2004 // use that information to infer NUW and NSW flags. However, computing a
2005 // BE count requires calling getAddRecExpr, so we may not yet have a
2006 // meaningful BE count at this point (and if we don't, we'd be stuck
2007 // with a SCEVCouldNotCompute as the cached BE count).
2008
Dan Gohmana10756e2010-01-21 02:09:26 +00002009 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2010 if (!HasNUW && HasNSW) {
2011 bool All = true;
2012 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2013 if (!isKnownNonNegative(Operands[i])) {
2014 All = false;
2015 break;
2016 }
2017 if (All) HasNUW = true;
2018 }
2019
Dan Gohmand9cc7492008-08-08 18:33:12 +00002020 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002021 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002022 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002023 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002024 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002025 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002026 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002027 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002028 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002029 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002030 // AddRecs require their operands be loop-invariant with respect to their
2031 // loops. Don't perform this transformation if it would break this
2032 // requirement.
2033 bool AllInvariant = true;
2034 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2035 if (!Operands[i]->isLoopInvariant(L)) {
2036 AllInvariant = false;
2037 break;
2038 }
2039 if (AllInvariant) {
2040 NestedOperands[0] = getAddRecExpr(Operands, L);
2041 AllInvariant = true;
2042 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2043 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2044 AllInvariant = false;
2045 break;
2046 }
2047 if (AllInvariant)
2048 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002049 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002050 }
2051 // Reset Operands to its original state.
2052 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002053 }
2054 }
2055
Dan Gohman67847532010-01-19 22:27:22 +00002056 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2057 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002058 FoldingSetNodeID ID;
2059 ID.AddInteger(scAddRecExpr);
2060 ID.AddInteger(Operands.size());
2061 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2062 ID.AddPointer(Operands[i]);
2063 ID.AddPointer(L);
2064 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002065 SCEVAddRecExpr *S =
2066 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2067 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002068 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2069 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002070 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2071 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002072 UniqueSCEVs.InsertNode(S, IP);
2073 }
Dan Gohman3645b012009-10-09 00:10:36 +00002074 if (HasNUW) S->setHasNoUnsignedWrap(true);
2075 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002076 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002077}
2078
Dan Gohman9311ef62009-06-24 14:49:00 +00002079const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2080 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002081 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002082 Ops.push_back(LHS);
2083 Ops.push_back(RHS);
2084 return getSMaxExpr(Ops);
2085}
2086
Dan Gohman0bba49c2009-07-07 17:06:11 +00002087const SCEV *
2088ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002089 assert(!Ops.empty() && "Cannot get empty smax!");
2090 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002091#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002092 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002093 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002094 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002095 "SCEVSMaxExpr operand types don't match!");
2096#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002097
2098 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002099 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002100
2101 // If there are any constants, fold them together.
2102 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002103 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002104 ++Idx;
2105 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002106 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002107 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002108 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002109 APIntOps::smax(LHSC->getValue()->getValue(),
2110 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002111 Ops[0] = getConstant(Fold);
2112 Ops.erase(Ops.begin()+1); // Erase the folded element
2113 if (Ops.size() == 1) return Ops[0];
2114 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002115 }
2116
Dan Gohmane5aceed2009-06-24 14:46:22 +00002117 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002118 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2119 Ops.erase(Ops.begin());
2120 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002121 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2122 // If we have an smax with a constant maximum-int, it will always be
2123 // maximum-int.
2124 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002125 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002126
Dan Gohman3ab13122010-04-13 16:49:23 +00002127 if (Ops.size() == 1) return Ops[0];
2128 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002129
2130 // Find the first SMax
2131 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2132 ++Idx;
2133
2134 // Check to see if one of the operands is an SMax. If so, expand its operands
2135 // onto our operand list, and recurse to simplify.
2136 if (Idx < Ops.size()) {
2137 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002138 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002139 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002140 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002141 DeletedSMax = true;
2142 }
2143
2144 if (DeletedSMax)
2145 return getSMaxExpr(Ops);
2146 }
2147
2148 // Okay, check to see if the same value occurs in the operand list twice. If
2149 // so, delete one. Since we sorted the list, these values are required to
2150 // be adjacent.
2151 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002152 // X smax Y smax Y --> X smax Y
2153 // X smax Y --> X, if X is always greater than Y
2154 if (Ops[i] == Ops[i+1] ||
2155 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2156 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2157 --i; --e;
2158 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002159 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2160 --i; --e;
2161 }
2162
2163 if (Ops.size() == 1) return Ops[0];
2164
2165 assert(!Ops.empty() && "Reduced smax down to nothing!");
2166
Nick Lewycky3e630762008-02-20 06:48:22 +00002167 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002168 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002169 FoldingSetNodeID ID;
2170 ID.AddInteger(scSMaxExpr);
2171 ID.AddInteger(Ops.size());
2172 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2173 ID.AddPointer(Ops[i]);
2174 void *IP = 0;
2175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002176 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2177 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002178 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2179 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002180 UniqueSCEVs.InsertNode(S, IP);
2181 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002182}
2183
Dan Gohman9311ef62009-06-24 14:49:00 +00002184const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2185 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002186 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002187 Ops.push_back(LHS);
2188 Ops.push_back(RHS);
2189 return getUMaxExpr(Ops);
2190}
2191
Dan Gohman0bba49c2009-07-07 17:06:11 +00002192const SCEV *
2193ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002194 assert(!Ops.empty() && "Cannot get empty umax!");
2195 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002196#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002197 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002198 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002199 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002200 "SCEVUMaxExpr operand types don't match!");
2201#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002202
2203 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002204 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002205
2206 // If there are any constants, fold them together.
2207 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002208 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002209 ++Idx;
2210 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002211 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002212 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002213 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002214 APIntOps::umax(LHSC->getValue()->getValue(),
2215 RHSC->getValue()->getValue()));
2216 Ops[0] = getConstant(Fold);
2217 Ops.erase(Ops.begin()+1); // Erase the folded element
2218 if (Ops.size() == 1) return Ops[0];
2219 LHSC = cast<SCEVConstant>(Ops[0]);
2220 }
2221
Dan Gohmane5aceed2009-06-24 14:46:22 +00002222 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002223 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2224 Ops.erase(Ops.begin());
2225 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002226 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2227 // If we have an umax with a constant maximum-int, it will always be
2228 // maximum-int.
2229 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002230 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002231
Dan Gohman3ab13122010-04-13 16:49:23 +00002232 if (Ops.size() == 1) return Ops[0];
2233 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002234
2235 // Find the first UMax
2236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2237 ++Idx;
2238
2239 // Check to see if one of the operands is a UMax. If so, expand its operands
2240 // onto our operand list, and recurse to simplify.
2241 if (Idx < Ops.size()) {
2242 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002243 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002244 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002245 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002246 DeletedUMax = true;
2247 }
2248
2249 if (DeletedUMax)
2250 return getUMaxExpr(Ops);
2251 }
2252
2253 // Okay, check to see if the same value occurs in the operand list twice. If
2254 // so, delete one. Since we sorted the list, these values are required to
2255 // be adjacent.
2256 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002257 // X umax Y umax Y --> X umax Y
2258 // X umax Y --> X, if X is always greater than Y
2259 if (Ops[i] == Ops[i+1] ||
2260 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2261 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2262 --i; --e;
2263 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002264 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2265 --i; --e;
2266 }
2267
2268 if (Ops.size() == 1) return Ops[0];
2269
2270 assert(!Ops.empty() && "Reduced umax down to nothing!");
2271
2272 // Okay, it looks like we really DO need a umax expr. Check to see if we
2273 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002274 FoldingSetNodeID ID;
2275 ID.AddInteger(scUMaxExpr);
2276 ID.AddInteger(Ops.size());
2277 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2278 ID.AddPointer(Ops[i]);
2279 void *IP = 0;
2280 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002281 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2282 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002283 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2284 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002285 UniqueSCEVs.InsertNode(S, IP);
2286 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002287}
2288
Dan Gohman9311ef62009-06-24 14:49:00 +00002289const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2290 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002291 // ~smax(~x, ~y) == smin(x, y).
2292 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2293}
2294
Dan Gohman9311ef62009-06-24 14:49:00 +00002295const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2296 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002297 // ~umax(~x, ~y) == umin(x, y)
2298 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2299}
2300
Dan Gohman4f8eea82010-02-01 18:27:38 +00002301const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002302 // If we have TargetData, we can bypass creating a target-independent
2303 // constant expression and then folding it back into a ConstantInt.
2304 // This is just a compile-time optimization.
2305 if (TD)
2306 return getConstant(TD->getIntPtrType(getContext()),
2307 TD->getTypeAllocSize(AllocTy));
2308
Dan Gohman4f8eea82010-02-01 18:27:38 +00002309 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2310 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002311 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2312 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002313 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2314 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2315}
2316
2317const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2318 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2319 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002320 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2321 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002322 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2323 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2324}
2325
2326const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2327 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002328 // If we have TargetData, we can bypass creating a target-independent
2329 // constant expression and then folding it back into a ConstantInt.
2330 // This is just a compile-time optimization.
2331 if (TD)
2332 return getConstant(TD->getIntPtrType(getContext()),
2333 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2334
Dan Gohman0f5efe52010-01-28 02:15:55 +00002335 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002337 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2338 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002339 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002340 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002341}
2342
Dan Gohman4f8eea82010-02-01 18:27:38 +00002343const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2344 Constant *FieldNo) {
2345 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002346 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002347 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2348 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002349 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002350 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002351}
2352
Dan Gohman0bba49c2009-07-07 17:06:11 +00002353const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002354 // Don't attempt to do anything other than create a SCEVUnknown object
2355 // here. createSCEV only calls getUnknown after checking for all other
2356 // interesting possibilities, and any other code that calls getUnknown
2357 // is doing so in order to hide a value from SCEV canonicalization.
2358
Dan Gohman1c343752009-06-27 21:21:31 +00002359 FoldingSetNodeID ID;
2360 ID.AddInteger(scUnknown);
2361 ID.AddPointer(V);
2362 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002363 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2364 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2365 "Stale SCEVUnknown in uniquing map!");
2366 return S;
2367 }
2368 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2369 FirstUnknown);
2370 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002371 UniqueSCEVs.InsertNode(S, IP);
2372 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002373}
2374
Chris Lattner53e677a2004-04-02 20:23:17 +00002375//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002376// Basic SCEV Analysis and PHI Idiom Recognition Code
2377//
2378
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002379/// isSCEVable - Test if values of the given type are analyzable within
2380/// the SCEV framework. This primarily includes integer types, and it
2381/// can optionally include pointer types if the ScalarEvolution class
2382/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002383bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002384 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002385 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002386}
2387
2388/// getTypeSizeInBits - Return the size in bits of the specified type,
2389/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002390uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002391 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2392
2393 // If we have a TargetData, use it!
2394 if (TD)
2395 return TD->getTypeSizeInBits(Ty);
2396
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002397 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002398 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002399 return Ty->getPrimitiveSizeInBits();
2400
2401 // The only other support type is pointer. Without TargetData, conservatively
2402 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002403 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002404 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002405}
2406
2407/// getEffectiveSCEVType - Return a type with the same bitwidth as
2408/// the given type and which represents how SCEV will treat the given
2409/// type, for which isSCEVable must return true. For pointer types,
2410/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002411const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002412 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2413
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002414 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002415 return Ty;
2416
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002417 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002418 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002419 if (TD) return TD->getIntPtrType(getContext());
2420
2421 // Without TargetData, conservatively assume pointers are 64-bit.
2422 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002423}
Chris Lattner53e677a2004-04-02 20:23:17 +00002424
Dan Gohman0bba49c2009-07-07 17:06:11 +00002425const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002426 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002427}
2428
Chris Lattner53e677a2004-04-02 20:23:17 +00002429/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2430/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002431const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002432 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002433
Dan Gohman0bba49c2009-07-07 17:06:11 +00002434 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002435 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002436 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002437 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002438 return S;
2439}
2440
Dan Gohman2d1be872009-04-16 03:18:22 +00002441/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2442///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002443const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002444 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002445 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002446 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002447
2448 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002449 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002450 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002451 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002452}
2453
2454/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002455const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002456 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002457 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002458 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002459
2460 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002461 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002462 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002463 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002464 return getMinusSCEV(AllOnes, V);
2465}
2466
2467/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2468///
Dan Gohman9311ef62009-06-24 14:49:00 +00002469const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2470 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002471 // Fast path: X - X --> 0.
2472 if (LHS == RHS)
2473 return getConstant(LHS->getType(), 0);
2474
Dan Gohman2d1be872009-04-16 03:18:22 +00002475 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002476 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002477}
2478
2479/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2480/// input value to the specified type. If the type must be extended, it is zero
2481/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002482const SCEV *
2483ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002484 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002485 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002486 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2487 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002488 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002489 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002490 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002491 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002492 return getTruncateExpr(V, Ty);
2493 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002494}
2495
2496/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2497/// input value to the specified type. If the type must be extended, it is sign
2498/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002499const SCEV *
2500ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002501 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002502 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002505 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002506 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002507 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002508 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002509 return getTruncateExpr(V, Ty);
2510 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002511}
2512
Dan Gohman467c4302009-05-13 03:46:30 +00002513/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2514/// input value to the specified type. If the type must be extended, it is zero
2515/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002516const SCEV *
2517ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002518 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002519 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2520 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002521 "Cannot noop or zero extend with non-integer arguments!");
2522 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2523 "getNoopOrZeroExtend cannot truncate!");
2524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2525 return V; // No conversion
2526 return getZeroExtendExpr(V, Ty);
2527}
2528
2529/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2530/// input value to the specified type. If the type must be extended, it is sign
2531/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002532const SCEV *
2533ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002534 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002535 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2536 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002537 "Cannot noop or sign extend with non-integer arguments!");
2538 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2539 "getNoopOrSignExtend cannot truncate!");
2540 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2541 return V; // No conversion
2542 return getSignExtendExpr(V, Ty);
2543}
2544
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002545/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2546/// the input value to the specified type. If the type must be extended,
2547/// it is extended with unspecified bits. The conversion must not be
2548/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002549const SCEV *
2550ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002551 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002552 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2553 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002554 "Cannot noop or any extend with non-integer arguments!");
2555 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2556 "getNoopOrAnyExtend cannot truncate!");
2557 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2558 return V; // No conversion
2559 return getAnyExtendExpr(V, Ty);
2560}
2561
Dan Gohman467c4302009-05-13 03:46:30 +00002562/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2563/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002564const SCEV *
2565ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002566 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002567 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2568 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002569 "Cannot truncate or noop with non-integer arguments!");
2570 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2571 "getTruncateOrNoop cannot extend!");
2572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2573 return V; // No conversion
2574 return getTruncateExpr(V, Ty);
2575}
2576
Dan Gohmana334aa72009-06-22 00:31:57 +00002577/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2578/// the types using zero-extension, and then perform a umax operation
2579/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002580const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2581 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002582 const SCEV *PromotedLHS = LHS;
2583 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002584
2585 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2586 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2587 else
2588 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2589
2590 return getUMaxExpr(PromotedLHS, PromotedRHS);
2591}
2592
Dan Gohmanc9759e82009-06-22 15:03:27 +00002593/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2594/// the types using zero-extension, and then perform a umin operation
2595/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002596const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2597 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002598 const SCEV *PromotedLHS = LHS;
2599 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002600
2601 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2602 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2603 else
2604 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2605
2606 return getUMinExpr(PromotedLHS, PromotedRHS);
2607}
2608
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002609/// PushDefUseChildren - Push users of the given Instruction
2610/// onto the given Worklist.
2611static void
2612PushDefUseChildren(Instruction *I,
2613 SmallVectorImpl<Instruction *> &Worklist) {
2614 // Push the def-use children onto the Worklist stack.
2615 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2616 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002617 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002618}
2619
2620/// ForgetSymbolicValue - This looks up computed SCEV values for all
2621/// instructions that depend on the given instruction and removes them from
2622/// the Scalars map if they reference SymName. This is used during PHI
2623/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002624void
Dan Gohman85669632010-02-25 06:57:05 +00002625ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002626 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002627 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002628
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002629 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002630 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002631 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002632 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002633 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002634
Dan Gohman5d984912009-12-18 01:14:11 +00002635 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002636 Scalars.find(static_cast<Value *>(I));
2637 if (It != Scalars.end()) {
2638 // Short-circuit the def-use traversal if the symbolic name
2639 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002640 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002641 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002642
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002643 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002644 // structure, it's a PHI that's in the progress of being computed
2645 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2646 // additional loop trip count information isn't going to change anything.
2647 // In the second case, createNodeForPHI will perform the necessary
2648 // updates on its own when it gets to that point. In the third, we do
2649 // want to forget the SCEVUnknown.
2650 if (!isa<PHINode>(I) ||
2651 !isa<SCEVUnknown>(It->second) ||
2652 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002653 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002654 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002655 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002656 }
2657
2658 PushDefUseChildren(I, Worklist);
2659 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002660}
Chris Lattner53e677a2004-04-02 20:23:17 +00002661
2662/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2663/// a loop header, making it a potential recurrence, or it doesn't.
2664///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002665const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002666 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2667 if (L->getHeader() == PN->getParent()) {
2668 // The loop may have multiple entrances or multiple exits; we can analyze
2669 // this phi as an addrec if it has a unique entry value and a unique
2670 // backedge value.
2671 Value *BEValueV = 0, *StartValueV = 0;
2672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2673 Value *V = PN->getIncomingValue(i);
2674 if (L->contains(PN->getIncomingBlock(i))) {
2675 if (!BEValueV) {
2676 BEValueV = V;
2677 } else if (BEValueV != V) {
2678 BEValueV = 0;
2679 break;
2680 }
2681 } else if (!StartValueV) {
2682 StartValueV = V;
2683 } else if (StartValueV != V) {
2684 StartValueV = 0;
2685 break;
2686 }
2687 }
2688 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002689 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002690 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002691 assert(Scalars.find(PN) == Scalars.end() &&
2692 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002693 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002694
2695 // Using this symbolic name for the PHI, analyze the value coming around
2696 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002697 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002698
2699 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2700 // has a special value for the first iteration of the loop.
2701
2702 // If the value coming around the backedge is an add with the symbolic
2703 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002704 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002705 // If there is a single occurrence of the symbolic value, replace it
2706 // with a recurrence.
2707 unsigned FoundIndex = Add->getNumOperands();
2708 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2709 if (Add->getOperand(i) == SymbolicName)
2710 if (FoundIndex == e) {
2711 FoundIndex = i;
2712 break;
2713 }
2714
2715 if (FoundIndex != Add->getNumOperands()) {
2716 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002717 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002718 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2719 if (i != FoundIndex)
2720 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002721 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002722
2723 // This is not a valid addrec if the step amount is varying each
2724 // loop iteration, but is not itself an addrec in this loop.
2725 if (Accum->isLoopInvariant(L) ||
2726 (isa<SCEVAddRecExpr>(Accum) &&
2727 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002728 bool HasNUW = false;
2729 bool HasNSW = false;
2730
2731 // If the increment doesn't overflow, then neither the addrec nor
2732 // the post-increment will overflow.
2733 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2734 if (OBO->hasNoUnsignedWrap())
2735 HasNUW = true;
2736 if (OBO->hasNoSignedWrap())
2737 HasNSW = true;
2738 }
2739
Dan Gohman27dead42010-04-12 07:49:36 +00002740 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002741 const SCEV *PHISCEV =
2742 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002743
Dan Gohmana10756e2010-01-21 02:09:26 +00002744 // Since the no-wrap flags are on the increment, they apply to the
2745 // post-incremented value as well.
2746 if (Accum->isLoopInvariant(L))
2747 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2748 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002749
2750 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002751 // to be symbolic. We now need to go back and purge all of the
2752 // entries for the scalars that use the symbolic expression.
2753 ForgetSymbolicName(PN, SymbolicName);
2754 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002755 return PHISCEV;
2756 }
2757 }
Dan Gohman622ed672009-05-04 22:02:23 +00002758 } else if (const SCEVAddRecExpr *AddRec =
2759 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002760 // Otherwise, this could be a loop like this:
2761 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2762 // In this case, j = {1,+,1} and BEValue is j.
2763 // Because the other in-value of i (0) fits the evolution of BEValue
2764 // i really is an addrec evolution.
2765 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002766 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002767
2768 // If StartVal = j.start - j.stride, we can use StartVal as the
2769 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002770 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002771 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002772 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002773 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002774
2775 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002776 // to be symbolic. We now need to go back and purge all of the
2777 // entries for the scalars that use the symbolic expression.
2778 ForgetSymbolicName(PN, SymbolicName);
2779 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002780 return PHISCEV;
2781 }
2782 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002783 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002784 }
Dan Gohman27dead42010-04-12 07:49:36 +00002785 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002786
Dan Gohman85669632010-02-25 06:57:05 +00002787 // If the PHI has a single incoming value, follow that value, unless the
2788 // PHI's incoming blocks are in a different loop, in which case doing so
2789 // risks breaking LCSSA form. Instcombine would normally zap these, but
2790 // it doesn't have DominatorTree information, so it may miss cases.
2791 if (Value *V = PN->hasConstantValue(DT)) {
2792 bool AllSameLoop = true;
2793 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2794 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2795 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2796 AllSameLoop = false;
2797 break;
2798 }
2799 if (AllSameLoop)
2800 return getSCEV(V);
2801 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002802
Chris Lattner53e677a2004-04-02 20:23:17 +00002803 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002804 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002805}
2806
Dan Gohman26466c02009-05-08 20:26:55 +00002807/// createNodeForGEP - Expand GEP instructions into add and multiply
2808/// operations. This allows them to be analyzed by regular SCEV code.
2809///
Dan Gohmand281ed22009-12-18 02:09:29 +00002810const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002811
Dan Gohmanb9f96512010-06-30 07:16:37 +00002812 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2813 // Add expression, because the Instruction may be guarded by control flow
2814 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002815 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002816
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002817 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002818 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002819 // Don't attempt to analyze GEPs over unsized objects.
2820 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2821 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002822 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002823 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002824 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002825 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002826 I != E; ++I) {
2827 Value *Index = *I;
2828 // Compute the (potentially symbolic) offset in bytes for this index.
2829 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2830 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002831 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002832 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2833
Dan Gohmanb9f96512010-06-30 07:16:37 +00002834 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002835 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002836 } else {
2837 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002838 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2839 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002840 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002841 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2842
Dan Gohmanb9f96512010-06-30 07:16:37 +00002843 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002844 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002845
2846 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002847 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002848 }
2849 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002850
2851 // Get the SCEV for the GEP base.
2852 const SCEV *BaseS = getSCEV(Base);
2853
Dan Gohmanb9f96512010-06-30 07:16:37 +00002854 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002855 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002856}
2857
Nick Lewycky83bb0052007-11-22 07:59:40 +00002858/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2859/// guaranteed to end in (at every loop iteration). It is, at the same time,
2860/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2861/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002862uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002863ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002864 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002865 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002866
Dan Gohman622ed672009-05-04 22:02:23 +00002867 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002868 return std::min(GetMinTrailingZeros(T->getOperand()),
2869 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002870
Dan Gohman622ed672009-05-04 22:02:23 +00002871 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002872 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2873 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2874 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002875 }
2876
Dan Gohman622ed672009-05-04 22:02:23 +00002877 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002878 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2879 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2880 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002881 }
2882
Dan Gohman622ed672009-05-04 22:02:23 +00002883 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002884 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002885 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002886 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002887 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002888 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002889 }
2890
Dan Gohman622ed672009-05-04 22:02:23 +00002891 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002892 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002893 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2894 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002895 for (unsigned i = 1, e = M->getNumOperands();
2896 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002897 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002898 BitWidth);
2899 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002900 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002901
Dan Gohman622ed672009-05-04 22:02:23 +00002902 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002903 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002904 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002905 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002906 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002907 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002908 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002909
Dan Gohman622ed672009-05-04 22:02:23 +00002910 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002911 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002912 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002913 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002914 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002915 return MinOpRes;
2916 }
2917
Dan Gohman622ed672009-05-04 22:02:23 +00002918 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002919 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002920 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002921 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002922 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002923 return MinOpRes;
2924 }
2925
Dan Gohman2c364ad2009-06-19 23:29:04 +00002926 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2927 // For a SCEVUnknown, ask ValueTracking.
2928 unsigned BitWidth = getTypeSizeInBits(U->getType());
2929 APInt Mask = APInt::getAllOnesValue(BitWidth);
2930 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2931 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2932 return Zeros.countTrailingOnes();
2933 }
2934
2935 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002936 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002937}
Chris Lattner53e677a2004-04-02 20:23:17 +00002938
Dan Gohman85b05a22009-07-13 21:35:55 +00002939/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2940///
2941ConstantRange
2942ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002943
2944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002945 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002947 unsigned BitWidth = getTypeSizeInBits(S->getType());
2948 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2949
2950 // If the value has known zeros, the maximum unsigned value will have those
2951 // known zeros as well.
2952 uint32_t TZ = GetMinTrailingZeros(S);
2953 if (TZ != 0)
2954 ConservativeResult =
2955 ConstantRange(APInt::getMinValue(BitWidth),
2956 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2957
Dan Gohman85b05a22009-07-13 21:35:55 +00002958 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2959 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2960 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2961 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002962 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002963 }
2964
2965 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2966 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2967 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2968 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002969 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002970 }
2971
2972 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2973 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2974 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2975 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002976 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002977 }
2978
2979 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2980 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2981 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2982 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002983 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002984 }
2985
2986 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2987 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2988 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002989 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002990 }
2991
2992 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002994 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002995 }
2996
2997 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2998 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002999 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003000 }
3001
3002 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3003 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003004 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003005 }
3006
Dan Gohman85b05a22009-07-13 21:35:55 +00003007 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003008 // If there's no unsigned wrap, the value will never be less than its
3009 // initial value.
3010 if (AddRec->hasNoUnsignedWrap())
3011 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003012 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003013 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003014 ConservativeResult.intersectWith(
3015 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003016
3017 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003018 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003019 const Type *Ty = AddRec->getType();
3020 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003021 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3022 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003023 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3024
3025 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003026 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003027
3028 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003029 ConstantRange StepRange = getSignedRange(Step);
3030 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3031 ConstantRange EndRange =
3032 StartRange.add(MaxBECountRange.multiply(StepRange));
3033
3034 // Check for overflow. This must be done with ConstantRange arithmetic
3035 // because we could be called from within the ScalarEvolution overflow
3036 // checking code.
3037 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3038 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3039 ConstantRange ExtMaxBECountRange =
3040 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3041 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3042 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3043 ExtEndRange)
3044 return ConservativeResult;
3045
Dan Gohman85b05a22009-07-13 21:35:55 +00003046 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3047 EndRange.getUnsignedMin());
3048 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3049 EndRange.getUnsignedMax());
3050 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003051 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003052 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00003053 }
3054 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003055
3056 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003057 }
3058
3059 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3060 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003061 APInt Mask = APInt::getAllOnesValue(BitWidth);
3062 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3063 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003064 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003065 return ConservativeResult;
3066 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003067 }
3068
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003069 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003070}
3071
Dan Gohman85b05a22009-07-13 21:35:55 +00003072/// getSignedRange - Determine the signed range for a particular SCEV.
3073///
3074ConstantRange
3075ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003076
Dan Gohman85b05a22009-07-13 21:35:55 +00003077 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3078 return ConstantRange(C->getValue()->getValue());
3079
Dan Gohman52fddd32010-01-26 04:40:18 +00003080 unsigned BitWidth = getTypeSizeInBits(S->getType());
3081 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3082
3083 // If the value has known zeros, the maximum signed value will have those
3084 // known zeros as well.
3085 uint32_t TZ = GetMinTrailingZeros(S);
3086 if (TZ != 0)
3087 ConservativeResult =
3088 ConstantRange(APInt::getSignedMinValue(BitWidth),
3089 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3090
Dan Gohman85b05a22009-07-13 21:35:55 +00003091 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3092 ConstantRange X = getSignedRange(Add->getOperand(0));
3093 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3094 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003095 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003096 }
3097
Dan Gohman85b05a22009-07-13 21:35:55 +00003098 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3099 ConstantRange X = getSignedRange(Mul->getOperand(0));
3100 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3101 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003102 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003103 }
3104
Dan Gohman85b05a22009-07-13 21:35:55 +00003105 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3106 ConstantRange X = getSignedRange(SMax->getOperand(0));
3107 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3108 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003109 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003110 }
Dan Gohman62849c02009-06-24 01:05:09 +00003111
Dan Gohman85b05a22009-07-13 21:35:55 +00003112 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3113 ConstantRange X = getSignedRange(UMax->getOperand(0));
3114 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3115 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003116 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003117 }
Dan Gohman62849c02009-06-24 01:05:09 +00003118
Dan Gohman85b05a22009-07-13 21:35:55 +00003119 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3120 ConstantRange X = getSignedRange(UDiv->getLHS());
3121 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003122 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003123 }
Dan Gohman62849c02009-06-24 01:05:09 +00003124
Dan Gohman85b05a22009-07-13 21:35:55 +00003125 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3126 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003127 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003128 }
3129
3130 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3131 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003132 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003133 }
3134
3135 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3136 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003137 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003138 }
3139
Dan Gohman85b05a22009-07-13 21:35:55 +00003140 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003141 // If there's no signed wrap, and all the operands have the same sign or
3142 // zero, the value won't ever change sign.
3143 if (AddRec->hasNoSignedWrap()) {
3144 bool AllNonNeg = true;
3145 bool AllNonPos = true;
3146 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3147 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3148 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3149 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003150 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003151 ConservativeResult = ConservativeResult.intersectWith(
3152 ConstantRange(APInt(BitWidth, 0),
3153 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003154 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003155 ConservativeResult = ConservativeResult.intersectWith(
3156 ConstantRange(APInt::getSignedMinValue(BitWidth),
3157 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003158 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003159
3160 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003161 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003162 const Type *Ty = AddRec->getType();
3163 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003164 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3165 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003166 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3167
3168 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003169 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003170
3171 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003172 ConstantRange StepRange = getSignedRange(Step);
3173 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3174 ConstantRange EndRange =
3175 StartRange.add(MaxBECountRange.multiply(StepRange));
3176
3177 // Check for overflow. This must be done with ConstantRange arithmetic
3178 // because we could be called from within the ScalarEvolution overflow
3179 // checking code.
3180 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3181 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3182 ConstantRange ExtMaxBECountRange =
3183 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3184 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3185 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3186 ExtEndRange)
3187 return ConservativeResult;
3188
Dan Gohman85b05a22009-07-13 21:35:55 +00003189 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3190 EndRange.getSignedMin());
3191 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3192 EndRange.getSignedMax());
3193 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003194 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003195 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003196 }
Dan Gohman62849c02009-06-24 01:05:09 +00003197 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003198
3199 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003200 }
3201
Dan Gohman2c364ad2009-06-19 23:29:04 +00003202 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3203 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003204 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003205 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003206 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3207 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003208 return ConservativeResult;
3209 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003210 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003211 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003212 }
3213
Dan Gohman52fddd32010-01-26 04:40:18 +00003214 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003215}
3216
Chris Lattner53e677a2004-04-02 20:23:17 +00003217/// createSCEV - We know that there is no SCEV for the specified value.
3218/// Analyze the expression.
3219///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003220const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003221 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003222 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003223
Dan Gohman6c459a22008-06-22 19:56:46 +00003224 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003225 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003226 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003227
3228 // Don't attempt to analyze instructions in blocks that aren't
3229 // reachable. Such instructions don't matter, and they aren't required
3230 // to obey basic rules for definitions dominating uses which this
3231 // analysis depends on.
3232 if (!DT->isReachableFromEntry(I->getParent()))
3233 return getUnknown(V);
3234 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003235 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003236 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3237 return getConstant(CI);
3238 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003239 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003240 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3241 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003242 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003243 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003244
Dan Gohmanca178902009-07-17 20:47:02 +00003245 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003246 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003247 case Instruction::Add: {
3248 // The simple thing to do would be to just call getSCEV on both operands
3249 // and call getAddExpr with the result. However if we're looking at a
3250 // bunch of things all added together, this can be quite inefficient,
3251 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3252 // Instead, gather up all the operands and make a single getAddExpr call.
3253 // LLVM IR canonical form means we need only traverse the left operands.
3254 SmallVector<const SCEV *, 4> AddOps;
3255 AddOps.push_back(getSCEV(U->getOperand(1)));
3256 for (Value *Op = U->getOperand(0);
3257 Op->getValueID() == Instruction::Add + Value::InstructionVal;
3258 Op = U->getOperand(0)) {
3259 U = cast<Operator>(Op);
3260 AddOps.push_back(getSCEV(U->getOperand(1)));
3261 }
3262 AddOps.push_back(getSCEV(U->getOperand(0)));
3263 return getAddExpr(AddOps);
3264 }
3265 case Instruction::Mul: {
3266 // See the Add code above.
3267 SmallVector<const SCEV *, 4> MulOps;
3268 MulOps.push_back(getSCEV(U->getOperand(1)));
3269 for (Value *Op = U->getOperand(0);
3270 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3271 Op = U->getOperand(0)) {
3272 U = cast<Operator>(Op);
3273 MulOps.push_back(getSCEV(U->getOperand(1)));
3274 }
3275 MulOps.push_back(getSCEV(U->getOperand(0)));
3276 return getMulExpr(MulOps);
3277 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003278 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003279 return getUDivExpr(getSCEV(U->getOperand(0)),
3280 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003281 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003282 return getMinusSCEV(getSCEV(U->getOperand(0)),
3283 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003284 case Instruction::And:
3285 // For an expression like x&255 that merely masks off the high bits,
3286 // use zext(trunc(x)) as the SCEV expression.
3287 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003288 if (CI->isNullValue())
3289 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003290 if (CI->isAllOnesValue())
3291 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003292 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003293
3294 // Instcombine's ShrinkDemandedConstant may strip bits out of
3295 // constants, obscuring what would otherwise be a low-bits mask.
3296 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3297 // knew about to reconstruct a low-bits mask value.
3298 unsigned LZ = A.countLeadingZeros();
3299 unsigned BitWidth = A.getBitWidth();
3300 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3301 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3302 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3303
3304 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3305
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003306 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003307 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003308 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003309 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003310 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003311 }
3312 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003313
Dan Gohman6c459a22008-06-22 19:56:46 +00003314 case Instruction::Or:
3315 // If the RHS of the Or is a constant, we may have something like:
3316 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3317 // optimizations will transparently handle this case.
3318 //
3319 // In order for this transformation to be safe, the LHS must be of the
3320 // form X*(2^n) and the Or constant must be less than 2^n.
3321 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003322 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003323 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003324 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003325 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3326 // Build a plain add SCEV.
3327 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3328 // If the LHS of the add was an addrec and it has no-wrap flags,
3329 // transfer the no-wrap flags, since an or won't introduce a wrap.
3330 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3331 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3332 if (OldAR->hasNoUnsignedWrap())
3333 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3334 if (OldAR->hasNoSignedWrap())
3335 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3336 }
3337 return S;
3338 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003339 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003340 break;
3341 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003342 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003343 // If the RHS of the xor is a signbit, then this is just an add.
3344 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003345 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003346 return getAddExpr(getSCEV(U->getOperand(0)),
3347 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003348
3349 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003350 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003351 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003352
3353 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3354 // This is a variant of the check for xor with -1, and it handles
3355 // the case where instcombine has trimmed non-demanded bits out
3356 // of an xor with -1.
3357 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3358 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3359 if (BO->getOpcode() == Instruction::And &&
3360 LCI->getValue() == CI->getValue())
3361 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003362 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003363 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003364 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003365 const Type *Z0Ty = Z0->getType();
3366 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3367
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003368 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003369 // mask off the high bits. Complement the operand and
3370 // re-apply the zext.
3371 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3372 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3373
3374 // If C is a single bit, it may be in the sign-bit position
3375 // before the zero-extend. In this case, represent the xor
3376 // using an add, which is equivalent, and re-apply the zext.
3377 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3378 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3379 Trunc.isSignBit())
3380 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3381 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003382 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003383 }
3384 break;
3385
3386 case Instruction::Shl:
3387 // Turn shift left of a constant amount into a multiply.
3388 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003389 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003390
3391 // If the shift count is not less than the bitwidth, the result of
3392 // the shift is undefined. Don't try to analyze it, because the
3393 // resolution chosen here may differ from the resolution chosen in
3394 // other parts of the compiler.
3395 if (SA->getValue().uge(BitWidth))
3396 break;
3397
Owen Andersoneed707b2009-07-24 23:12:02 +00003398 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003399 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003400 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003401 }
3402 break;
3403
Nick Lewycky01eaf802008-07-07 06:15:49 +00003404 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003405 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003406 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003407 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003408
3409 // If the shift count is not less than the bitwidth, the result of
3410 // the shift is undefined. Don't try to analyze it, because the
3411 // resolution chosen here may differ from the resolution chosen in
3412 // other parts of the compiler.
3413 if (SA->getValue().uge(BitWidth))
3414 break;
3415
Owen Andersoneed707b2009-07-24 23:12:02 +00003416 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003417 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003418 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003419 }
3420 break;
3421
Dan Gohman4ee29af2009-04-21 02:26:00 +00003422 case Instruction::AShr:
3423 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3424 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003425 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003426 if (L->getOpcode() == Instruction::Shl &&
3427 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003428 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3429
3430 // If the shift count is not less than the bitwidth, the result of
3431 // the shift is undefined. Don't try to analyze it, because the
3432 // resolution chosen here may differ from the resolution chosen in
3433 // other parts of the compiler.
3434 if (CI->getValue().uge(BitWidth))
3435 break;
3436
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003437 uint64_t Amt = BitWidth - CI->getZExtValue();
3438 if (Amt == BitWidth)
3439 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003440 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003441 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003442 IntegerType::get(getContext(),
3443 Amt)),
3444 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003445 }
3446 break;
3447
Dan Gohman6c459a22008-06-22 19:56:46 +00003448 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003449 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003450
3451 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003452 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003453
3454 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003455 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003456
3457 case Instruction::BitCast:
3458 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003459 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003460 return getSCEV(U->getOperand(0));
3461 break;
3462
Dan Gohman4f8eea82010-02-01 18:27:38 +00003463 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3464 // lead to pointer expressions which cannot safely be expanded to GEPs,
3465 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3466 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003467
Dan Gohman26466c02009-05-08 20:26:55 +00003468 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003469 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003470
Dan Gohman6c459a22008-06-22 19:56:46 +00003471 case Instruction::PHI:
3472 return createNodeForPHI(cast<PHINode>(U));
3473
3474 case Instruction::Select:
3475 // This could be a smax or umax that was lowered earlier.
3476 // Try to recover it.
3477 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3478 Value *LHS = ICI->getOperand(0);
3479 Value *RHS = ICI->getOperand(1);
3480 switch (ICI->getPredicate()) {
3481 case ICmpInst::ICMP_SLT:
3482 case ICmpInst::ICMP_SLE:
3483 std::swap(LHS, RHS);
3484 // fall through
3485 case ICmpInst::ICMP_SGT:
3486 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003487 // a >s b ? a+x : b+x -> smax(a, b)+x
3488 // a >s b ? b+x : a+x -> smin(a, b)+x
3489 if (LHS->getType() == U->getType()) {
3490 const SCEV *LS = getSCEV(LHS);
3491 const SCEV *RS = getSCEV(RHS);
3492 const SCEV *LA = getSCEV(U->getOperand(1));
3493 const SCEV *RA = getSCEV(U->getOperand(2));
3494 const SCEV *LDiff = getMinusSCEV(LA, LS);
3495 const SCEV *RDiff = getMinusSCEV(RA, RS);
3496 if (LDiff == RDiff)
3497 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3498 LDiff = getMinusSCEV(LA, RS);
3499 RDiff = getMinusSCEV(RA, LS);
3500 if (LDiff == RDiff)
3501 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3502 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003503 break;
3504 case ICmpInst::ICMP_ULT:
3505 case ICmpInst::ICMP_ULE:
3506 std::swap(LHS, RHS);
3507 // fall through
3508 case ICmpInst::ICMP_UGT:
3509 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003510 // a >u b ? a+x : b+x -> umax(a, b)+x
3511 // a >u b ? b+x : a+x -> umin(a, b)+x
3512 if (LHS->getType() == U->getType()) {
3513 const SCEV *LS = getSCEV(LHS);
3514 const SCEV *RS = getSCEV(RHS);
3515 const SCEV *LA = getSCEV(U->getOperand(1));
3516 const SCEV *RA = getSCEV(U->getOperand(2));
3517 const SCEV *LDiff = getMinusSCEV(LA, LS);
3518 const SCEV *RDiff = getMinusSCEV(RA, RS);
3519 if (LDiff == RDiff)
3520 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3521 LDiff = getMinusSCEV(LA, RS);
3522 RDiff = getMinusSCEV(RA, LS);
3523 if (LDiff == RDiff)
3524 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3525 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003526 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003527 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003528 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3529 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003530 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003531 cast<ConstantInt>(RHS)->isZero()) {
3532 const SCEV *One = getConstant(LHS->getType(), 1);
3533 const SCEV *LS = getSCEV(LHS);
3534 const SCEV *LA = getSCEV(U->getOperand(1));
3535 const SCEV *RA = getSCEV(U->getOperand(2));
3536 const SCEV *LDiff = getMinusSCEV(LA, LS);
3537 const SCEV *RDiff = getMinusSCEV(RA, One);
3538 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003539 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003540 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003541 break;
3542 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003543 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3544 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003545 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003546 cast<ConstantInt>(RHS)->isZero()) {
3547 const SCEV *One = getConstant(LHS->getType(), 1);
3548 const SCEV *LS = getSCEV(LHS);
3549 const SCEV *LA = getSCEV(U->getOperand(1));
3550 const SCEV *RA = getSCEV(U->getOperand(2));
3551 const SCEV *LDiff = getMinusSCEV(LA, One);
3552 const SCEV *RDiff = getMinusSCEV(RA, LS);
3553 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003554 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003555 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003556 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003557 default:
3558 break;
3559 }
3560 }
3561
3562 default: // We cannot analyze this expression.
3563 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003564 }
3565
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003566 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003567}
3568
3569
3570
3571//===----------------------------------------------------------------------===//
3572// Iteration Count Computation Code
3573//
3574
Dan Gohman46bdfb02009-02-24 18:55:53 +00003575/// getBackedgeTakenCount - If the specified loop has a predictable
3576/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3577/// object. The backedge-taken count is the number of times the loop header
3578/// will be branched to from within the loop. This is one less than the
3579/// trip count of the loop, since it doesn't count the first iteration,
3580/// when the header is branched to from outside the loop.
3581///
3582/// Note that it is not valid to call this method on a loop without a
3583/// loop-invariant backedge-taken count (see
3584/// hasLoopInvariantBackedgeTakenCount).
3585///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003586const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003587 return getBackedgeTakenInfo(L).Exact;
3588}
3589
3590/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3591/// return the least SCEV value that is known never to be less than the
3592/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003593const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003594 return getBackedgeTakenInfo(L).Max;
3595}
3596
Dan Gohman59ae6b92009-07-08 19:23:34 +00003597/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3598/// onto the given Worklist.
3599static void
3600PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3601 BasicBlock *Header = L->getHeader();
3602
3603 // Push all Loop-header PHIs onto the Worklist stack.
3604 for (BasicBlock::iterator I = Header->begin();
3605 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3606 Worklist.push_back(PN);
3607}
3608
Dan Gohmana1af7572009-04-30 20:47:05 +00003609const ScalarEvolution::BackedgeTakenInfo &
3610ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003611 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003612 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003613 // update the value. The temporary CouldNotCompute value tells SCEV
3614 // code elsewhere that it shouldn't attempt to request a new
3615 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003616 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003617 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3618 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003619 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3620 if (BECount.Exact != getCouldNotCompute()) {
3621 assert(BECount.Exact->isLoopInvariant(L) &&
3622 BECount.Max->isLoopInvariant(L) &&
3623 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003624 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003625
Dan Gohman01ecca22009-04-27 20:16:15 +00003626 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003627 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003628 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003629 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003630 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003631 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003632 if (isa<PHINode>(L->getHeader()->begin()))
3633 // Only count loops that have phi nodes as not being computable.
3634 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003635 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003636
3637 // Now that we know more about the trip count for this loop, forget any
3638 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003639 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003640 // information. This is similar to the code in forgetLoop, except that
3641 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003642 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003643 SmallVector<Instruction *, 16> Worklist;
3644 PushLoopPHIs(L, Worklist);
3645
3646 SmallPtrSet<Instruction *, 8> Visited;
3647 while (!Worklist.empty()) {
3648 Instruction *I = Worklist.pop_back_val();
3649 if (!Visited.insert(I)) continue;
3650
Dan Gohman5d984912009-12-18 01:14:11 +00003651 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003652 Scalars.find(static_cast<Value *>(I));
3653 if (It != Scalars.end()) {
3654 // SCEVUnknown for a PHI either means that it has an unrecognized
3655 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003656 // by createNodeForPHI. In the former case, additional loop trip
3657 // count information isn't going to change anything. In the later
3658 // case, createNodeForPHI will perform the necessary updates on its
3659 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003660 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3661 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003662 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003663 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003664 if (PHINode *PN = dyn_cast<PHINode>(I))
3665 ConstantEvolutionLoopExitValue.erase(PN);
3666 }
3667
3668 PushDefUseChildren(I, Worklist);
3669 }
3670 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003671 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003672 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003673}
3674
Dan Gohman4c7279a2009-10-31 15:04:55 +00003675/// forgetLoop - This method should be called by the client when it has
3676/// changed a loop in a way that may effect ScalarEvolution's ability to
3677/// compute a trip count, or if the loop is deleted.
3678void ScalarEvolution::forgetLoop(const Loop *L) {
3679 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003680 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003681
Dan Gohman4c7279a2009-10-31 15:04:55 +00003682 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003683 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003684 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003685
Dan Gohman59ae6b92009-07-08 19:23:34 +00003686 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003687 while (!Worklist.empty()) {
3688 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003689 if (!Visited.insert(I)) continue;
3690
Dan Gohman5d984912009-12-18 01:14:11 +00003691 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003692 Scalars.find(static_cast<Value *>(I));
3693 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003694 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003695 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003696 if (PHINode *PN = dyn_cast<PHINode>(I))
3697 ConstantEvolutionLoopExitValue.erase(PN);
3698 }
3699
3700 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003701 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003702}
3703
Eric Christophere6cbfa62010-07-29 01:25:38 +00003704/// forgetValue - This method should be called by the client when it has
3705/// changed a value in a way that may effect its value, or which may
3706/// disconnect it from a def-use chain linking it to a loop.
3707void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003708 Instruction *I = dyn_cast<Instruction>(V);
3709 if (!I) return;
3710
3711 // Drop information about expressions based on loop-header PHIs.
3712 SmallVector<Instruction *, 16> Worklist;
3713 Worklist.push_back(I);
3714
3715 SmallPtrSet<Instruction *, 8> Visited;
3716 while (!Worklist.empty()) {
3717 I = Worklist.pop_back_val();
3718 if (!Visited.insert(I)) continue;
3719
3720 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3721 Scalars.find(static_cast<Value *>(I));
3722 if (It != Scalars.end()) {
3723 ValuesAtScopes.erase(It->second);
3724 Scalars.erase(It);
3725 if (PHINode *PN = dyn_cast<PHINode>(I))
3726 ConstantEvolutionLoopExitValue.erase(PN);
3727 }
3728
3729 PushDefUseChildren(I, Worklist);
3730 }
3731}
3732
Dan Gohman46bdfb02009-02-24 18:55:53 +00003733/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3734/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003735ScalarEvolution::BackedgeTakenInfo
3736ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003737 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003738 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003739
Dan Gohmana334aa72009-06-22 00:31:57 +00003740 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003741 const SCEV *BECount = getCouldNotCompute();
3742 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003743 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003744 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3745 BackedgeTakenInfo NewBTI =
3746 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003747
Dan Gohman1c343752009-06-27 21:21:31 +00003748 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003749 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003750 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003751 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003752 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003753 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003754 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003755 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003756 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003757 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003758 }
Dan Gohman1c343752009-06-27 21:21:31 +00003759 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003760 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003761 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003762 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003763 }
3764
3765 return BackedgeTakenInfo(BECount, MaxBECount);
3766}
3767
3768/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3769/// of the specified loop will execute if it exits via the specified block.
3770ScalarEvolution::BackedgeTakenInfo
3771ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3772 BasicBlock *ExitingBlock) {
3773
3774 // Okay, we've chosen an exiting block. See what condition causes us to
3775 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003776 //
3777 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003778 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003779 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003780 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003781
Chris Lattner8b0e3602007-01-07 02:24:26 +00003782 // At this point, we know we have a conditional branch that determines whether
3783 // the loop is exited. However, we don't know if the branch is executed each
3784 // time through the loop. If not, then the execution count of the branch will
3785 // not be equal to the trip count of the loop.
3786 //
3787 // Currently we check for this by checking to see if the Exit branch goes to
3788 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003789 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003790 // loop header. This is common for un-rotated loops.
3791 //
3792 // If both of those tests fail, walk up the unique predecessor chain to the
3793 // header, stopping if there is an edge that doesn't exit the loop. If the
3794 // header is reached, the execution count of the branch will be equal to the
3795 // trip count of the loop.
3796 //
3797 // More extensive analysis could be done to handle more cases here.
3798 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003799 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003800 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003801 ExitBr->getParent() != L->getHeader()) {
3802 // The simple checks failed, try climbing the unique predecessor chain
3803 // up to the header.
3804 bool Ok = false;
3805 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3806 BasicBlock *Pred = BB->getUniquePredecessor();
3807 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003808 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003809 TerminatorInst *PredTerm = Pred->getTerminator();
3810 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3811 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3812 if (PredSucc == BB)
3813 continue;
3814 // If the predecessor has a successor that isn't BB and isn't
3815 // outside the loop, assume the worst.
3816 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003817 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003818 }
3819 if (Pred == L->getHeader()) {
3820 Ok = true;
3821 break;
3822 }
3823 BB = Pred;
3824 }
3825 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003826 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003827 }
3828
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003829 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003830 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3831 ExitBr->getSuccessor(0),
3832 ExitBr->getSuccessor(1));
3833}
3834
3835/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3836/// backedge of the specified loop will execute if its exit condition
3837/// were a conditional branch of ExitCond, TBB, and FBB.
3838ScalarEvolution::BackedgeTakenInfo
3839ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3840 Value *ExitCond,
3841 BasicBlock *TBB,
3842 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003843 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003844 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3845 if (BO->getOpcode() == Instruction::And) {
3846 // Recurse on the operands of the and.
3847 BackedgeTakenInfo BTI0 =
3848 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3849 BackedgeTakenInfo BTI1 =
3850 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003851 const SCEV *BECount = getCouldNotCompute();
3852 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003853 if (L->contains(TBB)) {
3854 // Both conditions must be true for the loop to continue executing.
3855 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003856 if (BTI0.Exact == getCouldNotCompute() ||
3857 BTI1.Exact == getCouldNotCompute())
3858 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003859 else
3860 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003861 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003862 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003863 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003864 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003865 else
3866 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003867 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003868 // Both conditions must be true at the same time for the loop to exit.
3869 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003870 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003871 if (BTI0.Max == BTI1.Max)
3872 MaxBECount = BTI0.Max;
3873 if (BTI0.Exact == BTI1.Exact)
3874 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003875 }
3876
3877 return BackedgeTakenInfo(BECount, MaxBECount);
3878 }
3879 if (BO->getOpcode() == Instruction::Or) {
3880 // Recurse on the operands of the or.
3881 BackedgeTakenInfo BTI0 =
3882 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3883 BackedgeTakenInfo BTI1 =
3884 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003885 const SCEV *BECount = getCouldNotCompute();
3886 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003887 if (L->contains(FBB)) {
3888 // Both conditions must be false for the loop to continue executing.
3889 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003890 if (BTI0.Exact == getCouldNotCompute() ||
3891 BTI1.Exact == getCouldNotCompute())
3892 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003893 else
3894 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003895 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003896 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003897 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003898 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003899 else
3900 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003901 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003902 // Both conditions must be false at the same time for the loop to exit.
3903 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003904 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003905 if (BTI0.Max == BTI1.Max)
3906 MaxBECount = BTI0.Max;
3907 if (BTI0.Exact == BTI1.Exact)
3908 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003909 }
3910
3911 return BackedgeTakenInfo(BECount, MaxBECount);
3912 }
3913 }
3914
3915 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003916 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003917 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3918 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003919
Dan Gohman00cb5b72010-02-19 18:12:07 +00003920 // Check for a constant condition. These are normally stripped out by
3921 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3922 // preserve the CFG and is temporarily leaving constant conditions
3923 // in place.
3924 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3925 if (L->contains(FBB) == !CI->getZExtValue())
3926 // The backedge is always taken.
3927 return getCouldNotCompute();
3928 else
3929 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003930 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003931 }
3932
Eli Friedman361e54d2009-05-09 12:32:42 +00003933 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003934 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3935}
3936
3937/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3938/// backedge of the specified loop will execute if its exit condition
3939/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3940ScalarEvolution::BackedgeTakenInfo
3941ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3942 ICmpInst *ExitCond,
3943 BasicBlock *TBB,
3944 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003945
Reid Spencere4d87aa2006-12-23 06:05:41 +00003946 // If the condition was exit on true, convert the condition to exit on false
3947 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003948 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003949 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003950 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003951 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003952
3953 // Handle common loops like: for (X = "string"; *X; ++X)
3954 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3955 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003956 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003957 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003958 if (ItCnt.hasAnyInfo())
3959 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003960 }
3961
Dan Gohman0bba49c2009-07-07 17:06:11 +00003962 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3963 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003964
3965 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003966 LHS = getSCEVAtScope(LHS, L);
3967 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003968
Dan Gohman64a845e2009-06-24 04:48:43 +00003969 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003970 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003971 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3972 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003973 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003975 }
3976
Dan Gohman03557dc2010-05-03 16:35:17 +00003977 // Simplify the operands before analyzing them.
3978 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3979
Chris Lattner53e677a2004-04-02 20:23:17 +00003980 // If we have a comparison of a chrec against a constant, try to use value
3981 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003982 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3983 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003984 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003985 // Form the constant range.
3986 ConstantRange CompRange(
3987 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003988
Dan Gohman0bba49c2009-07-07 17:06:11 +00003989 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003990 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003991 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003992
Chris Lattner53e677a2004-04-02 20:23:17 +00003993 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003994 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003995 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003996 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3997 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003998 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003999 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004000 case ICmpInst::ICMP_EQ: { // while (X == Y)
4001 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004002 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4003 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004004 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004005 }
4006 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004007 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4008 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004009 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004010 }
4011 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004012 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4013 getNotSCEV(RHS), L, true);
4014 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004015 break;
4016 }
4017 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004018 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4019 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004020 break;
4021 }
4022 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004023 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4024 getNotSCEV(RHS), L, false);
4025 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004026 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004027 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004028 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004029#if 0
David Greene25e0e872009-12-23 22:18:14 +00004030 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004031 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004032 dbgs() << "[unsigned] ";
4033 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004034 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004035 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004036#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004037 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004038 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004039 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004040 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004041}
4042
Chris Lattner673e02b2004-10-12 01:49:27 +00004043static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004044EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4045 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004046 const SCEV *InVal = SE.getConstant(C);
4047 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004048 assert(isa<SCEVConstant>(Val) &&
4049 "Evaluation of SCEV at constant didn't fold correctly?");
4050 return cast<SCEVConstant>(Val)->getValue();
4051}
4052
4053/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4054/// and a GEP expression (missing the pointer index) indexing into it, return
4055/// the addressed element of the initializer or null if the index expression is
4056/// invalid.
4057static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004058GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004059 const std::vector<ConstantInt*> &Indices) {
4060 Constant *Init = GV->getInitializer();
4061 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004062 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004063 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4064 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4065 Init = cast<Constant>(CS->getOperand(Idx));
4066 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4067 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4068 Init = cast<Constant>(CA->getOperand(Idx));
4069 } else if (isa<ConstantAggregateZero>(Init)) {
4070 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4071 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004072 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004073 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4074 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004075 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004076 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004077 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004078 }
4079 return 0;
4080 } else {
4081 return 0; // Unknown initializer type
4082 }
4083 }
4084 return Init;
4085}
4086
Dan Gohman46bdfb02009-02-24 18:55:53 +00004087/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4088/// 'icmp op load X, cst', try to see if we can compute the backedge
4089/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004090ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004091ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4092 LoadInst *LI,
4093 Constant *RHS,
4094 const Loop *L,
4095 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004096 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004097
4098 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004099 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004100 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004101 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004102
4103 // Make sure that it is really a constant global we are gepping, with an
4104 // initializer, and make sure the first IDX is really 0.
4105 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004106 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004107 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4108 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004109 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004110
4111 // Okay, we allow one non-constant index into the GEP instruction.
4112 Value *VarIdx = 0;
4113 std::vector<ConstantInt*> Indexes;
4114 unsigned VarIdxNum = 0;
4115 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4116 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4117 Indexes.push_back(CI);
4118 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004119 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004120 VarIdx = GEP->getOperand(i);
4121 VarIdxNum = i-2;
4122 Indexes.push_back(0);
4123 }
4124
4125 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4126 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004127 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004128 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004129
4130 // We can only recognize very limited forms of loop index expressions, in
4131 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004132 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00004133 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4134 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4135 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004136 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004137
4138 unsigned MaxSteps = MaxBruteForceIterations;
4139 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004140 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004141 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004142 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004143
4144 // Form the GEP offset.
4145 Indexes[VarIdxNum] = Val;
4146
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004147 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004148 if (Result == 0) break; // Cannot compute!
4149
4150 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004151 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004152 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004153 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004154#if 0
David Greene25e0e872009-12-23 22:18:14 +00004155 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004156 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4157 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004158#endif
4159 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004160 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004161 }
4162 }
Dan Gohman1c343752009-06-27 21:21:31 +00004163 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004164}
4165
4166
Chris Lattner3221ad02004-04-17 22:58:41 +00004167/// CanConstantFold - Return true if we can constant fold an instruction of the
4168/// specified type, assuming that all operands were constants.
4169static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004170 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004171 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4172 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004173
Chris Lattner3221ad02004-04-17 22:58:41 +00004174 if (const CallInst *CI = dyn_cast<CallInst>(I))
4175 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004176 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004177 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004178}
4179
Chris Lattner3221ad02004-04-17 22:58:41 +00004180/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4181/// in the loop that V is derived from. We allow arbitrary operations along the
4182/// way, but the operands of an operation must either be constants or a value
4183/// derived from a constant PHI. If this expression does not fit with these
4184/// constraints, return null.
4185static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4186 // If this is not an instruction, or if this is an instruction outside of the
4187 // loop, it can't be derived from a loop PHI.
4188 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004189 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004190
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004191 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004192 if (L->getHeader() == I->getParent())
4193 return PN;
4194 else
4195 // We don't currently keep track of the control flow needed to evaluate
4196 // PHIs, so we cannot handle PHIs inside of loops.
4197 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004198 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004199
4200 // If we won't be able to constant fold this expression even if the operands
4201 // are constants, return early.
4202 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004203
Chris Lattner3221ad02004-04-17 22:58:41 +00004204 // Otherwise, we can evaluate this instruction if all of its operands are
4205 // constant or derived from a PHI node themselves.
4206 PHINode *PHI = 0;
4207 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004208 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004209 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4210 if (P == 0) return 0; // Not evolving from PHI
4211 if (PHI == 0)
4212 PHI = P;
4213 else if (PHI != P)
4214 return 0; // Evolving from multiple different PHIs.
4215 }
4216
4217 // This is a expression evolving from a constant PHI!
4218 return PHI;
4219}
4220
4221/// EvaluateExpression - Given an expression that passes the
4222/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4223/// in the loop has the value PHIVal. If we can't fold this expression for some
4224/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004225static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4226 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004227 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004228 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004229 Instruction *I = cast<Instruction>(V);
4230
Dan Gohman9d4588f2010-06-22 13:15:46 +00004231 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004232
4233 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004234 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004235 if (Operands[i] == 0) return 0;
4236 }
4237
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004238 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004239 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004240 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004241 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004242 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004243}
4244
4245/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4246/// in the header of its containing loop, we know the loop executes a
4247/// constant number of times, and the PHI node is just a recurrence
4248/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004249Constant *
4250ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004251 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004252 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004253 std::map<PHINode*, Constant*>::iterator I =
4254 ConstantEvolutionLoopExitValue.find(PN);
4255 if (I != ConstantEvolutionLoopExitValue.end())
4256 return I->second;
4257
Dan Gohmane0567812010-04-08 23:03:40 +00004258 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004259 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4260
4261 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4262
4263 // Since the loop is canonicalized, the PHI node must have two entries. One
4264 // entry must be a constant (coming in from outside of the loop), and the
4265 // second must be derived from the same PHI.
4266 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4267 Constant *StartCST =
4268 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4269 if (StartCST == 0)
4270 return RetVal = 0; // Must be a constant.
4271
4272 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004273 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4274 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004275 return RetVal = 0; // Not derived from same PHI.
4276
4277 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004278 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004279 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004280
Dan Gohman46bdfb02009-02-24 18:55:53 +00004281 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004282 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004283 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4284 if (IterationNum == NumIterations)
4285 return RetVal = PHIVal; // Got exit value!
4286
4287 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004288 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004289 if (NextPHI == PHIVal)
4290 return RetVal = NextPHI; // Stopped evolving!
4291 if (NextPHI == 0)
4292 return 0; // Couldn't evaluate!
4293 PHIVal = NextPHI;
4294 }
4295}
4296
Dan Gohman07ad19b2009-07-27 16:09:48 +00004297/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004298/// constant number of times (the condition evolves only from constants),
4299/// try to evaluate a few iterations of the loop until we get the exit
4300/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004301/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004302const SCEV *
4303ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4304 Value *Cond,
4305 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004306 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004307 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004308
Dan Gohmanb92654d2010-06-19 14:17:24 +00004309 // If the loop is canonicalized, the PHI will have exactly two entries.
4310 // That's the only form we support here.
4311 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4312
4313 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004314 // second must be derived from the same PHI.
4315 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4316 Constant *StartCST =
4317 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004318 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004319
4320 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004321 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4322 !isa<Constant>(BEValue))
4323 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004324
4325 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4326 // the loop symbolically to determine when the condition gets a value of
4327 // "ExitWhen".
4328 unsigned IterationNum = 0;
4329 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4330 for (Constant *PHIVal = StartCST;
4331 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004332 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004333 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004334
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004335 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004336 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004337
Reid Spencere8019bb2007-03-01 07:25:48 +00004338 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004339 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004340 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004341 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004342
Chris Lattner3221ad02004-04-17 22:58:41 +00004343 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004344 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004345 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004346 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004347 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004348 }
4349
4350 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004351 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004352}
4353
Dan Gohmane7125f42009-09-03 15:00:26 +00004354/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004355/// at the specified scope in the program. The L value specifies a loop
4356/// nest to evaluate the expression at, where null is the top-level or a
4357/// specified loop is immediately inside of the loop.
4358///
4359/// This method can be used to compute the exit value for a variable defined
4360/// in a loop by querying what the value will hold in the parent loop.
4361///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004362/// In the case that a relevant loop exit value cannot be computed, the
4363/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004364const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004365 // Check to see if we've folded this expression at this loop before.
4366 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4367 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4368 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4369 if (!Pair.second)
4370 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004371
Dan Gohman42214892009-08-31 21:15:23 +00004372 // Otherwise compute it.
4373 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004374 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004375 return C;
4376}
4377
4378const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004379 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004380
Nick Lewycky3e630762008-02-20 06:48:22 +00004381 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004382 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004383 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004384 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004385 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004386 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4387 if (PHINode *PN = dyn_cast<PHINode>(I))
4388 if (PN->getParent() == LI->getHeader()) {
4389 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004390 // to see if the loop that contains it has a known backedge-taken
4391 // count. If so, we may be able to force computation of the exit
4392 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004393 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004394 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004395 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004396 // Okay, we know how many times the containing loop executes. If
4397 // this is a constant evolving PHI node, get the final value at
4398 // the specified iteration number.
4399 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004400 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004401 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004402 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004403 }
4404 }
4405
Reid Spencer09906f32006-12-04 21:33:23 +00004406 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004407 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004408 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004409 // result. This is particularly useful for computing loop exit values.
4410 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004411 SmallVector<Constant *, 4> Operands;
4412 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004413 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4414 Value *Op = I->getOperand(i);
4415 if (Constant *C = dyn_cast<Constant>(Op)) {
4416 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004417 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004418 }
Dan Gohman11046452010-06-29 23:43:06 +00004419
4420 // If any of the operands is non-constant and if they are
4421 // non-integer and non-pointer, don't even try to analyze them
4422 // with scev techniques.
4423 if (!isSCEVable(Op->getType()))
4424 return V;
4425
4426 const SCEV *OrigV = getSCEV(Op);
4427 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4428 MadeImprovement |= OrigV != OpV;
4429
4430 Constant *C = 0;
4431 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4432 C = SC->getValue();
4433 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4434 C = dyn_cast<Constant>(SU->getValue());
4435 if (!C) return V;
4436 if (C->getType() != Op->getType())
4437 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4438 Op->getType(),
4439 false),
4440 C, Op->getType());
4441 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004442 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004443
Dan Gohman11046452010-06-29 23:43:06 +00004444 // Check to see if getSCEVAtScope actually made an improvement.
4445 if (MadeImprovement) {
4446 Constant *C = 0;
4447 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4448 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4449 Operands[0], Operands[1], TD);
4450 else
4451 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4452 &Operands[0], Operands.size(), TD);
4453 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004454 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004455 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004456 }
4457 }
4458
4459 // This is some other type of SCEVUnknown, just return it.
4460 return V;
4461 }
4462
Dan Gohman622ed672009-05-04 22:02:23 +00004463 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004464 // Avoid performing the look-up in the common case where the specified
4465 // expression has no loop-variant portions.
4466 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004467 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004468 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004469 // Okay, at least one of these operands is loop variant but might be
4470 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004471 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4472 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004473 NewOps.push_back(OpAtScope);
4474
4475 for (++i; i != e; ++i) {
4476 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004477 NewOps.push_back(OpAtScope);
4478 }
4479 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004480 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004481 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004482 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004483 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004484 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004485 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004486 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004487 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004488 }
4489 }
4490 // If we got here, all operands are loop invariant.
4491 return Comm;
4492 }
4493
Dan Gohman622ed672009-05-04 22:02:23 +00004494 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004495 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4496 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004497 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4498 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004499 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004500 }
4501
4502 // If this is a loop recurrence for a loop that does not contain L, then we
4503 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004504 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004505 // First, attempt to evaluate each operand.
4506 // Avoid performing the look-up in the common case where the specified
4507 // expression has no loop-variant portions.
4508 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4509 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4510 if (OpAtScope == AddRec->getOperand(i))
4511 continue;
4512
4513 // Okay, at least one of these operands is loop variant but might be
4514 // foldable. Build a new instance of the folded commutative expression.
4515 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4516 AddRec->op_begin()+i);
4517 NewOps.push_back(OpAtScope);
4518 for (++i; i != e; ++i)
4519 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4520
4521 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4522 break;
4523 }
4524
4525 // If the scope is outside the addrec's loop, evaluate it by using the
4526 // loop exit value of the addrec.
4527 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004528 // To evaluate this recurrence, we need to know how many times the AddRec
4529 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004530 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004531 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004532
Eli Friedmanb42a6262008-08-04 23:49:06 +00004533 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004534 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004535 }
Dan Gohman11046452010-06-29 23:43:06 +00004536
Dan Gohmand594e6f2009-05-24 23:25:42 +00004537 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004538 }
4539
Dan Gohman622ed672009-05-04 22:02:23 +00004540 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004541 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004542 if (Op == Cast->getOperand())
4543 return Cast; // must be loop invariant
4544 return getZeroExtendExpr(Op, Cast->getType());
4545 }
4546
Dan Gohman622ed672009-05-04 22:02:23 +00004547 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004548 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004549 if (Op == Cast->getOperand())
4550 return Cast; // must be loop invariant
4551 return getSignExtendExpr(Op, Cast->getType());
4552 }
4553
Dan Gohman622ed672009-05-04 22:02:23 +00004554 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004555 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004556 if (Op == Cast->getOperand())
4557 return Cast; // must be loop invariant
4558 return getTruncateExpr(Op, Cast->getType());
4559 }
4560
Torok Edwinc23197a2009-07-14 16:55:14 +00004561 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004562 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004563}
4564
Dan Gohman66a7e852009-05-08 20:38:54 +00004565/// getSCEVAtScope - This is a convenience function which does
4566/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004567const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004568 return getSCEVAtScope(getSCEV(V), L);
4569}
4570
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004571/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4572/// following equation:
4573///
4574/// A * X = B (mod N)
4575///
4576/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4577/// A and B isn't important.
4578///
4579/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004580static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004581 ScalarEvolution &SE) {
4582 uint32_t BW = A.getBitWidth();
4583 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4584 assert(A != 0 && "A must be non-zero.");
4585
4586 // 1. D = gcd(A, N)
4587 //
4588 // The gcd of A and N may have only one prime factor: 2. The number of
4589 // trailing zeros in A is its multiplicity
4590 uint32_t Mult2 = A.countTrailingZeros();
4591 // D = 2^Mult2
4592
4593 // 2. Check if B is divisible by D.
4594 //
4595 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4596 // is not less than multiplicity of this prime factor for D.
4597 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004598 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004599
4600 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4601 // modulo (N / D).
4602 //
4603 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4604 // bit width during computations.
4605 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4606 APInt Mod(BW + 1, 0);
4607 Mod.set(BW - Mult2); // Mod = N / D
4608 APInt I = AD.multiplicativeInverse(Mod);
4609
4610 // 4. Compute the minimum unsigned root of the equation:
4611 // I * (B / D) mod (N / D)
4612 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4613
4614 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4615 // bits.
4616 return SE.getConstant(Result.trunc(BW));
4617}
Chris Lattner53e677a2004-04-02 20:23:17 +00004618
4619/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4620/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4621/// might be the same) or two SCEVCouldNotCompute objects.
4622///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004623static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004624SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004625 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004626 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4627 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4628 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004629
Chris Lattner53e677a2004-04-02 20:23:17 +00004630 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004631 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004632 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004633 return std::make_pair(CNC, CNC);
4634 }
4635
Reid Spencere8019bb2007-03-01 07:25:48 +00004636 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004637 const APInt &L = LC->getValue()->getValue();
4638 const APInt &M = MC->getValue()->getValue();
4639 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004640 APInt Two(BitWidth, 2);
4641 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004642
Dan Gohman64a845e2009-06-24 04:48:43 +00004643 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004644 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004645 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004646 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4647 // The B coefficient is M-N/2
4648 APInt B(M);
4649 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004650
Reid Spencere8019bb2007-03-01 07:25:48 +00004651 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004652 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004653
Reid Spencere8019bb2007-03-01 07:25:48 +00004654 // Compute the B^2-4ac term.
4655 APInt SqrtTerm(B);
4656 SqrtTerm *= B;
4657 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004658
Reid Spencere8019bb2007-03-01 07:25:48 +00004659 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4660 // integer value or else APInt::sqrt() will assert.
4661 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004662
Dan Gohman64a845e2009-06-24 04:48:43 +00004663 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004664 // The divisions must be performed as signed divisions.
4665 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004666 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004667 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004668 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004669 return std::make_pair(CNC, CNC);
4670 }
4671
Owen Andersone922c022009-07-22 00:24:57 +00004672 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004673
4674 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004675 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004676 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004677 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004678
Dan Gohman64a845e2009-06-24 04:48:43 +00004679 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004680 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004681 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004682}
4683
4684/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004685/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004686ScalarEvolution::BackedgeTakenInfo
4687ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004688 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004689 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004690 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004691 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004692 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004693 }
4694
Dan Gohman35738ac2009-05-04 22:30:44 +00004695 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004696 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004697 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004698
4699 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004700 // If this is an affine expression, the execution count of this branch is
4701 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004702 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004703 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004704 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004705 // equivalent to:
4706 //
4707 // Step*N = -Start (mod 2^BW)
4708 //
4709 // where BW is the common bit width of Start and Step.
4710
Chris Lattner53e677a2004-04-02 20:23:17 +00004711 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004712 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4713 L->getParentLoop());
4714 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4715 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004716
Dan Gohman622ed672009-05-04 22:02:23 +00004717 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004718 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004719
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004720 // First, handle unitary steps.
4721 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004722 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004723 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4724 return Start; // N = Start (as unsigned)
4725
4726 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004727 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004728 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004729 -StartC->getValue()->getValue(),
4730 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004731 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004732 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004733 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4734 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004735 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004736 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004737 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4738 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004739 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004740#if 0
David Greene25e0e872009-12-23 22:18:14 +00004741 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004742 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004743#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004744 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004745 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004746 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004747 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004748 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004749 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004750
Chris Lattner53e677a2004-04-02 20:23:17 +00004751 // We can only use this value if the chrec ends up with an exact zero
4752 // value at this index. When solving for "X*X != 5", for example, we
4753 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004754 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004755 if (Val->isZero())
4756 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004757 }
4758 }
4759 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004760
Dan Gohman1c343752009-06-27 21:21:31 +00004761 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004762}
4763
4764/// HowFarToNonZero - Return the number of times a backedge checking the
4765/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004766/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004767ScalarEvolution::BackedgeTakenInfo
4768ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004769 // Loops that look like: while (X == 0) are very strange indeed. We don't
4770 // handle them yet except for the trivial case. This could be expanded in the
4771 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004772
Chris Lattner53e677a2004-04-02 20:23:17 +00004773 // If the value is a constant, check to see if it is known to be non-zero
4774 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004775 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004776 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004777 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004778 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004779 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004780
Chris Lattner53e677a2004-04-02 20:23:17 +00004781 // We could implement others, but I really doubt anyone writes loops like
4782 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004783 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004784}
4785
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004786/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4787/// (which may not be an immediate predecessor) which has exactly one
4788/// successor from which BB is reachable, or null if no such block is
4789/// found.
4790///
Dan Gohman005752b2010-04-15 16:19:08 +00004791std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004792ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004793 // If the block has a unique predecessor, then there is no path from the
4794 // predecessor to the block that does not go through the direct edge
4795 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004796 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004797 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004798
4799 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004800 // If the header has a unique predecessor outside the loop, it must be
4801 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004802 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004803 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004804
Dan Gohman005752b2010-04-15 16:19:08 +00004805 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004806}
4807
Dan Gohman763bad12009-06-20 00:35:32 +00004808/// HasSameValue - SCEV structural equivalence is usually sufficient for
4809/// testing whether two expressions are equal, however for the purposes of
4810/// looking for a condition guarding a loop, it can be useful to be a little
4811/// more general, since a front-end may have replicated the controlling
4812/// expression.
4813///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004814static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004815 // Quick check to see if they are the same SCEV.
4816 if (A == B) return true;
4817
4818 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4819 // two different instructions with the same value. Check for this case.
4820 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4821 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4822 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4823 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004824 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004825 return true;
4826
4827 // Otherwise assume they may have a different value.
4828 return false;
4829}
4830
Dan Gohmane9796502010-04-24 01:28:42 +00004831/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4832/// predicate Pred. Return true iff any changes were made.
4833///
4834bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4835 const SCEV *&LHS, const SCEV *&RHS) {
4836 bool Changed = false;
4837
4838 // Canonicalize a constant to the right side.
4839 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4840 // Check for both operands constant.
4841 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4842 if (ConstantExpr::getICmp(Pred,
4843 LHSC->getValue(),
4844 RHSC->getValue())->isNullValue())
4845 goto trivially_false;
4846 else
4847 goto trivially_true;
4848 }
4849 // Otherwise swap the operands to put the constant on the right.
4850 std::swap(LHS, RHS);
4851 Pred = ICmpInst::getSwappedPredicate(Pred);
4852 Changed = true;
4853 }
4854
4855 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004856 // addrec's loop, put the addrec on the left. Also make a dominance check,
4857 // as both operands could be addrecs loop-invariant in each other's loop.
4858 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4859 const Loop *L = AR->getLoop();
4860 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004861 std::swap(LHS, RHS);
4862 Pred = ICmpInst::getSwappedPredicate(Pred);
4863 Changed = true;
4864 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004865 }
Dan Gohmane9796502010-04-24 01:28:42 +00004866
4867 // If there's a constant operand, canonicalize comparisons with boundary
4868 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4869 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4870 const APInt &RA = RC->getValue()->getValue();
4871 switch (Pred) {
4872 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4873 case ICmpInst::ICMP_EQ:
4874 case ICmpInst::ICMP_NE:
4875 break;
4876 case ICmpInst::ICMP_UGE:
4877 if ((RA - 1).isMinValue()) {
4878 Pred = ICmpInst::ICMP_NE;
4879 RHS = getConstant(RA - 1);
4880 Changed = true;
4881 break;
4882 }
4883 if (RA.isMaxValue()) {
4884 Pred = ICmpInst::ICMP_EQ;
4885 Changed = true;
4886 break;
4887 }
4888 if (RA.isMinValue()) goto trivially_true;
4889
4890 Pred = ICmpInst::ICMP_UGT;
4891 RHS = getConstant(RA - 1);
4892 Changed = true;
4893 break;
4894 case ICmpInst::ICMP_ULE:
4895 if ((RA + 1).isMaxValue()) {
4896 Pred = ICmpInst::ICMP_NE;
4897 RHS = getConstant(RA + 1);
4898 Changed = true;
4899 break;
4900 }
4901 if (RA.isMinValue()) {
4902 Pred = ICmpInst::ICMP_EQ;
4903 Changed = true;
4904 break;
4905 }
4906 if (RA.isMaxValue()) goto trivially_true;
4907
4908 Pred = ICmpInst::ICMP_ULT;
4909 RHS = getConstant(RA + 1);
4910 Changed = true;
4911 break;
4912 case ICmpInst::ICMP_SGE:
4913 if ((RA - 1).isMinSignedValue()) {
4914 Pred = ICmpInst::ICMP_NE;
4915 RHS = getConstant(RA - 1);
4916 Changed = true;
4917 break;
4918 }
4919 if (RA.isMaxSignedValue()) {
4920 Pred = ICmpInst::ICMP_EQ;
4921 Changed = true;
4922 break;
4923 }
4924 if (RA.isMinSignedValue()) goto trivially_true;
4925
4926 Pred = ICmpInst::ICMP_SGT;
4927 RHS = getConstant(RA - 1);
4928 Changed = true;
4929 break;
4930 case ICmpInst::ICMP_SLE:
4931 if ((RA + 1).isMaxSignedValue()) {
4932 Pred = ICmpInst::ICMP_NE;
4933 RHS = getConstant(RA + 1);
4934 Changed = true;
4935 break;
4936 }
4937 if (RA.isMinSignedValue()) {
4938 Pred = ICmpInst::ICMP_EQ;
4939 Changed = true;
4940 break;
4941 }
4942 if (RA.isMaxSignedValue()) goto trivially_true;
4943
4944 Pred = ICmpInst::ICMP_SLT;
4945 RHS = getConstant(RA + 1);
4946 Changed = true;
4947 break;
4948 case ICmpInst::ICMP_UGT:
4949 if (RA.isMinValue()) {
4950 Pred = ICmpInst::ICMP_NE;
4951 Changed = true;
4952 break;
4953 }
4954 if ((RA + 1).isMaxValue()) {
4955 Pred = ICmpInst::ICMP_EQ;
4956 RHS = getConstant(RA + 1);
4957 Changed = true;
4958 break;
4959 }
4960 if (RA.isMaxValue()) goto trivially_false;
4961 break;
4962 case ICmpInst::ICMP_ULT:
4963 if (RA.isMaxValue()) {
4964 Pred = ICmpInst::ICMP_NE;
4965 Changed = true;
4966 break;
4967 }
4968 if ((RA - 1).isMinValue()) {
4969 Pred = ICmpInst::ICMP_EQ;
4970 RHS = getConstant(RA - 1);
4971 Changed = true;
4972 break;
4973 }
4974 if (RA.isMinValue()) goto trivially_false;
4975 break;
4976 case ICmpInst::ICMP_SGT:
4977 if (RA.isMinSignedValue()) {
4978 Pred = ICmpInst::ICMP_NE;
4979 Changed = true;
4980 break;
4981 }
4982 if ((RA + 1).isMaxSignedValue()) {
4983 Pred = ICmpInst::ICMP_EQ;
4984 RHS = getConstant(RA + 1);
4985 Changed = true;
4986 break;
4987 }
4988 if (RA.isMaxSignedValue()) goto trivially_false;
4989 break;
4990 case ICmpInst::ICMP_SLT:
4991 if (RA.isMaxSignedValue()) {
4992 Pred = ICmpInst::ICMP_NE;
4993 Changed = true;
4994 break;
4995 }
4996 if ((RA - 1).isMinSignedValue()) {
4997 Pred = ICmpInst::ICMP_EQ;
4998 RHS = getConstant(RA - 1);
4999 Changed = true;
5000 break;
5001 }
5002 if (RA.isMinSignedValue()) goto trivially_false;
5003 break;
5004 }
5005 }
5006
5007 // Check for obvious equality.
5008 if (HasSameValue(LHS, RHS)) {
5009 if (ICmpInst::isTrueWhenEqual(Pred))
5010 goto trivially_true;
5011 if (ICmpInst::isFalseWhenEqual(Pred))
5012 goto trivially_false;
5013 }
5014
Dan Gohman03557dc2010-05-03 16:35:17 +00005015 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5016 // adding or subtracting 1 from one of the operands.
5017 switch (Pred) {
5018 case ICmpInst::ICMP_SLE:
5019 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5020 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5021 /*HasNUW=*/false, /*HasNSW=*/true);
5022 Pred = ICmpInst::ICMP_SLT;
5023 Changed = true;
5024 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005025 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005026 /*HasNUW=*/false, /*HasNSW=*/true);
5027 Pred = ICmpInst::ICMP_SLT;
5028 Changed = true;
5029 }
5030 break;
5031 case ICmpInst::ICMP_SGE:
5032 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005033 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005034 /*HasNUW=*/false, /*HasNSW=*/true);
5035 Pred = ICmpInst::ICMP_SGT;
5036 Changed = true;
5037 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5038 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5039 /*HasNUW=*/false, /*HasNSW=*/true);
5040 Pred = ICmpInst::ICMP_SGT;
5041 Changed = true;
5042 }
5043 break;
5044 case ICmpInst::ICMP_ULE:
5045 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005046 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005047 /*HasNUW=*/true, /*HasNSW=*/false);
5048 Pred = ICmpInst::ICMP_ULT;
5049 Changed = true;
5050 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005051 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005052 /*HasNUW=*/true, /*HasNSW=*/false);
5053 Pred = ICmpInst::ICMP_ULT;
5054 Changed = true;
5055 }
5056 break;
5057 case ICmpInst::ICMP_UGE:
5058 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005059 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005060 /*HasNUW=*/true, /*HasNSW=*/false);
5061 Pred = ICmpInst::ICMP_UGT;
5062 Changed = true;
5063 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005064 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005065 /*HasNUW=*/true, /*HasNSW=*/false);
5066 Pred = ICmpInst::ICMP_UGT;
5067 Changed = true;
5068 }
5069 break;
5070 default:
5071 break;
5072 }
5073
Dan Gohmane9796502010-04-24 01:28:42 +00005074 // TODO: More simplifications are possible here.
5075
5076 return Changed;
5077
5078trivially_true:
5079 // Return 0 == 0.
5080 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5081 Pred = ICmpInst::ICMP_EQ;
5082 return true;
5083
5084trivially_false:
5085 // Return 0 != 0.
5086 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5087 Pred = ICmpInst::ICMP_NE;
5088 return true;
5089}
5090
Dan Gohman85b05a22009-07-13 21:35:55 +00005091bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5092 return getSignedRange(S).getSignedMax().isNegative();
5093}
5094
5095bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5096 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5097}
5098
5099bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5100 return !getSignedRange(S).getSignedMin().isNegative();
5101}
5102
5103bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5104 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5105}
5106
5107bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5108 return isKnownNegative(S) || isKnownPositive(S);
5109}
5110
5111bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5112 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005113 // Canonicalize the inputs first.
5114 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5115
Dan Gohman53c66ea2010-04-11 22:16:48 +00005116 // If LHS or RHS is an addrec, check to see if the condition is true in
5117 // every iteration of the loop.
5118 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5119 if (isLoopEntryGuardedByCond(
5120 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5121 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005122 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005123 return true;
5124 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5125 if (isLoopEntryGuardedByCond(
5126 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5127 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005128 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005129 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005130
Dan Gohman53c66ea2010-04-11 22:16:48 +00005131 // Otherwise see what can be done with known constant ranges.
5132 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5133}
5134
5135bool
5136ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5137 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005138 if (HasSameValue(LHS, RHS))
5139 return ICmpInst::isTrueWhenEqual(Pred);
5140
Dan Gohman53c66ea2010-04-11 22:16:48 +00005141 // This code is split out from isKnownPredicate because it is called from
5142 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005143 switch (Pred) {
5144 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005145 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005146 break;
5147 case ICmpInst::ICMP_SGT:
5148 Pred = ICmpInst::ICMP_SLT;
5149 std::swap(LHS, RHS);
5150 case ICmpInst::ICMP_SLT: {
5151 ConstantRange LHSRange = getSignedRange(LHS);
5152 ConstantRange RHSRange = getSignedRange(RHS);
5153 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5154 return true;
5155 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5156 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005157 break;
5158 }
5159 case ICmpInst::ICMP_SGE:
5160 Pred = ICmpInst::ICMP_SLE;
5161 std::swap(LHS, RHS);
5162 case ICmpInst::ICMP_SLE: {
5163 ConstantRange LHSRange = getSignedRange(LHS);
5164 ConstantRange RHSRange = getSignedRange(RHS);
5165 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5166 return true;
5167 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5168 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005169 break;
5170 }
5171 case ICmpInst::ICMP_UGT:
5172 Pred = ICmpInst::ICMP_ULT;
5173 std::swap(LHS, RHS);
5174 case ICmpInst::ICMP_ULT: {
5175 ConstantRange LHSRange = getUnsignedRange(LHS);
5176 ConstantRange RHSRange = getUnsignedRange(RHS);
5177 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5178 return true;
5179 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5180 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005181 break;
5182 }
5183 case ICmpInst::ICMP_UGE:
5184 Pred = ICmpInst::ICMP_ULE;
5185 std::swap(LHS, RHS);
5186 case ICmpInst::ICMP_ULE: {
5187 ConstantRange LHSRange = getUnsignedRange(LHS);
5188 ConstantRange RHSRange = getUnsignedRange(RHS);
5189 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5190 return true;
5191 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5192 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005193 break;
5194 }
5195 case ICmpInst::ICMP_NE: {
5196 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5197 return true;
5198 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5199 return true;
5200
5201 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5202 if (isKnownNonZero(Diff))
5203 return true;
5204 break;
5205 }
5206 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005207 // The check at the top of the function catches the case where
5208 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005209 break;
5210 }
5211 return false;
5212}
5213
5214/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5215/// protected by a conditional between LHS and RHS. This is used to
5216/// to eliminate casts.
5217bool
5218ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5219 ICmpInst::Predicate Pred,
5220 const SCEV *LHS, const SCEV *RHS) {
5221 // Interpret a null as meaning no loop, where there is obviously no guard
5222 // (interprocedural conditions notwithstanding).
5223 if (!L) return true;
5224
5225 BasicBlock *Latch = L->getLoopLatch();
5226 if (!Latch)
5227 return false;
5228
5229 BranchInst *LoopContinuePredicate =
5230 dyn_cast<BranchInst>(Latch->getTerminator());
5231 if (!LoopContinuePredicate ||
5232 LoopContinuePredicate->isUnconditional())
5233 return false;
5234
Dan Gohmanaf08a362010-08-10 23:46:30 +00005235 return isImpliedCond(Pred, LHS, RHS,
5236 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005237 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005238}
5239
Dan Gohman3948d0b2010-04-11 19:27:13 +00005240/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005241/// by a conditional between LHS and RHS. This is used to help avoid max
5242/// expressions in loop trip counts, and to eliminate casts.
5243bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005244ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5245 ICmpInst::Predicate Pred,
5246 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005247 // Interpret a null as meaning no loop, where there is obviously no guard
5248 // (interprocedural conditions notwithstanding).
5249 if (!L) return false;
5250
Dan Gohman859b4822009-05-18 15:36:09 +00005251 // Starting at the loop predecessor, climb up the predecessor chain, as long
5252 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005253 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005254 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005255 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005256 Pair.first;
5257 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005258
5259 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005260 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005261 if (!LoopEntryPredicate ||
5262 LoopEntryPredicate->isUnconditional())
5263 continue;
5264
Dan Gohmanaf08a362010-08-10 23:46:30 +00005265 if (isImpliedCond(Pred, LHS, RHS,
5266 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005267 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005268 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005269 }
5270
Dan Gohman38372182008-08-12 20:17:31 +00005271 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005272}
5273
Dan Gohman0f4b2852009-07-21 23:03:19 +00005274/// isImpliedCond - Test whether the condition described by Pred, LHS,
5275/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005276bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005277 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005278 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005279 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005280 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005282 if (BO->getOpcode() == Instruction::And) {
5283 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005284 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5285 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005286 } else if (BO->getOpcode() == Instruction::Or) {
5287 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005288 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5289 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005290 }
5291 }
5292
Dan Gohmanaf08a362010-08-10 23:46:30 +00005293 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005294 if (!ICI) return false;
5295
Dan Gohman85b05a22009-07-13 21:35:55 +00005296 // Bail if the ICmp's operands' types are wider than the needed type
5297 // before attempting to call getSCEV on them. This avoids infinite
5298 // recursion, since the analysis of widening casts can require loop
5299 // exit condition information for overflow checking, which would
5300 // lead back here.
5301 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005302 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005303 return false;
5304
Dan Gohman0f4b2852009-07-21 23:03:19 +00005305 // Now that we found a conditional branch that dominates the loop, check to
5306 // see if it is the comparison we are looking for.
5307 ICmpInst::Predicate FoundPred;
5308 if (Inverse)
5309 FoundPred = ICI->getInversePredicate();
5310 else
5311 FoundPred = ICI->getPredicate();
5312
5313 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5314 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005315
5316 // Balance the types. The case where FoundLHS' type is wider than
5317 // LHS' type is checked for above.
5318 if (getTypeSizeInBits(LHS->getType()) >
5319 getTypeSizeInBits(FoundLHS->getType())) {
5320 if (CmpInst::isSigned(Pred)) {
5321 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5322 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5323 } else {
5324 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5325 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5326 }
5327 }
5328
Dan Gohman0f4b2852009-07-21 23:03:19 +00005329 // Canonicalize the query to match the way instcombine will have
5330 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005331 if (SimplifyICmpOperands(Pred, LHS, RHS))
5332 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005333 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005334 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5335 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005336 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005337
5338 // Check to see if we can make the LHS or RHS match.
5339 if (LHS == FoundRHS || RHS == FoundLHS) {
5340 if (isa<SCEVConstant>(RHS)) {
5341 std::swap(FoundLHS, FoundRHS);
5342 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5343 } else {
5344 std::swap(LHS, RHS);
5345 Pred = ICmpInst::getSwappedPredicate(Pred);
5346 }
5347 }
5348
5349 // Check whether the found predicate is the same as the desired predicate.
5350 if (FoundPred == Pred)
5351 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5352
5353 // Check whether swapping the found predicate makes it the same as the
5354 // desired predicate.
5355 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5356 if (isa<SCEVConstant>(RHS))
5357 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5358 else
5359 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5360 RHS, LHS, FoundLHS, FoundRHS);
5361 }
5362
5363 // Check whether the actual condition is beyond sufficient.
5364 if (FoundPred == ICmpInst::ICMP_EQ)
5365 if (ICmpInst::isTrueWhenEqual(Pred))
5366 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5367 return true;
5368 if (Pred == ICmpInst::ICMP_NE)
5369 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5370 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5371 return true;
5372
5373 // Otherwise assume the worst.
5374 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005375}
5376
Dan Gohman0f4b2852009-07-21 23:03:19 +00005377/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005378/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005379/// and FoundRHS is true.
5380bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5381 const SCEV *LHS, const SCEV *RHS,
5382 const SCEV *FoundLHS,
5383 const SCEV *FoundRHS) {
5384 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5385 FoundLHS, FoundRHS) ||
5386 // ~x < ~y --> x > y
5387 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5388 getNotSCEV(FoundRHS),
5389 getNotSCEV(FoundLHS));
5390}
5391
5392/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005393/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005394/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005395bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005396ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5397 const SCEV *LHS, const SCEV *RHS,
5398 const SCEV *FoundLHS,
5399 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005400 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005401 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5402 case ICmpInst::ICMP_EQ:
5403 case ICmpInst::ICMP_NE:
5404 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5405 return true;
5406 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005407 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005408 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005409 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5410 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005411 return true;
5412 break;
5413 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005414 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005415 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5416 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005417 return true;
5418 break;
5419 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005420 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005421 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5422 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005423 return true;
5424 break;
5425 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005426 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005427 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5428 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005429 return true;
5430 break;
5431 }
5432
5433 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005434}
5435
Dan Gohman51f53b72009-06-21 23:46:38 +00005436/// getBECount - Subtract the end and start values and divide by the step,
5437/// rounding up, to get the number of times the backedge is executed. Return
5438/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005439const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005440 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005441 const SCEV *Step,
5442 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005443 assert(!isKnownNegative(Step) &&
5444 "This code doesn't handle negative strides yet!");
5445
Dan Gohman51f53b72009-06-21 23:46:38 +00005446 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005447 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005448 const SCEV *Diff = getMinusSCEV(End, Start);
5449 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005450
5451 // Add an adjustment to the difference between End and Start so that
5452 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005453 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005454
Dan Gohman1f96e672009-09-17 18:05:20 +00005455 if (!NoWrap) {
5456 // Check Add for unsigned overflow.
5457 // TODO: More sophisticated things could be done here.
5458 const Type *WideTy = IntegerType::get(getContext(),
5459 getTypeSizeInBits(Ty) + 1);
5460 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5461 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5462 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5463 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5464 return getCouldNotCompute();
5465 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005466
5467 return getUDivExpr(Add, Step);
5468}
5469
Chris Lattnerdb25de42005-08-15 23:33:51 +00005470/// HowManyLessThans - Return the number of times a backedge containing the
5471/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005472/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005473ScalarEvolution::BackedgeTakenInfo
5474ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5475 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005476 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005477 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005478
Dan Gohman35738ac2009-05-04 22:30:44 +00005479 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005480 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005481 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005482
Dan Gohman1f96e672009-09-17 18:05:20 +00005483 // Check to see if we have a flag which makes analysis easy.
5484 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5485 AddRec->hasNoUnsignedWrap();
5486
Chris Lattnerdb25de42005-08-15 23:33:51 +00005487 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005488 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005489 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005490
Dan Gohman52fddd32010-01-26 04:40:18 +00005491 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005492 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005493 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005494 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005495 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005496 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005497 // value and past the maximum value for its type in a single step.
5498 // Note that it's not sufficient to check NoWrap here, because even
5499 // though the value after a wrap is undefined, it's not undefined
5500 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005501 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005502 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005503 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005504 if (isSigned) {
5505 APInt Max = APInt::getSignedMaxValue(BitWidth);
5506 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5507 .slt(getSignedRange(RHS).getSignedMax()))
5508 return getCouldNotCompute();
5509 } else {
5510 APInt Max = APInt::getMaxValue(BitWidth);
5511 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5512 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5513 return getCouldNotCompute();
5514 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005515 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005516 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005517 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005518
Dan Gohmana1af7572009-04-30 20:47:05 +00005519 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5520 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5521 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005522 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005523
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005524 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005525 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005526
Dan Gohmana1af7572009-04-30 20:47:05 +00005527 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005528 const SCEV *MinStart = getConstant(isSigned ?
5529 getSignedRange(Start).getSignedMin() :
5530 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005531
Dan Gohmana1af7572009-04-30 20:47:05 +00005532 // If we know that the condition is true in order to enter the loop,
5533 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005534 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5535 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005536 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005537 if (!isLoopEntryGuardedByCond(L,
5538 isSigned ? ICmpInst::ICMP_SLT :
5539 ICmpInst::ICMP_ULT,
5540 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005541 End = isSigned ? getSMaxExpr(RHS, Start)
5542 : getUMaxExpr(RHS, Start);
5543
5544 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005545 const SCEV *MaxEnd = getConstant(isSigned ?
5546 getSignedRange(End).getSignedMax() :
5547 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005548
Dan Gohman52fddd32010-01-26 04:40:18 +00005549 // If MaxEnd is within a step of the maximum integer value in its type,
5550 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005551 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005552 // compute the correct value.
5553 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005554 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005555 MaxEnd = isSigned ?
5556 getSMinExpr(MaxEnd,
5557 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5558 StepMinusOne)) :
5559 getUMinExpr(MaxEnd,
5560 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5561 StepMinusOne));
5562
Dan Gohmana1af7572009-04-30 20:47:05 +00005563 // Finally, we subtract these two values and divide, rounding up, to get
5564 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005565 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005566
5567 // The maximum backedge count is similar, except using the minimum start
5568 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005569 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005570
5571 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005572 }
5573
Dan Gohman1c343752009-06-27 21:21:31 +00005574 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005575}
5576
Chris Lattner53e677a2004-04-02 20:23:17 +00005577/// getNumIterationsInRange - Return the number of iterations of this loop that
5578/// produce values in the specified constant range. Another way of looking at
5579/// this is that it returns the first iteration number where the value is not in
5580/// the condition, thus computing the exit count. If the iteration count can't
5581/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005582const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005583 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005584 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005585 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005586
5587 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005588 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005589 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005590 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005591 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005592 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005593 if (const SCEVAddRecExpr *ShiftedAddRec =
5594 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005595 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005596 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005597 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005598 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005599 }
5600
5601 // The only time we can solve this is when we have all constant indices.
5602 // Otherwise, we cannot determine the overflow conditions.
5603 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5604 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005605 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005606
5607
5608 // Okay at this point we know that all elements of the chrec are constants and
5609 // that the start element is zero.
5610
5611 // First check to see if the range contains zero. If not, the first
5612 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005613 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005614 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005615 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005616
Chris Lattner53e677a2004-04-02 20:23:17 +00005617 if (isAffine()) {
5618 // If this is an affine expression then we have this situation:
5619 // Solve {0,+,A} in Range === Ax in Range
5620
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005621 // We know that zero is in the range. If A is positive then we know that
5622 // the upper value of the range must be the first possible exit value.
5623 // If A is negative then the lower of the range is the last possible loop
5624 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005625 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005626 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5627 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005628
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005629 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005630 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005631 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005632
5633 // Evaluate at the exit value. If we really did fall out of the valid
5634 // range, then we computed our trip count, otherwise wrap around or other
5635 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005636 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005637 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005638 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005639
5640 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005641 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005642 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005643 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005644 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005645 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005646 } else if (isQuadratic()) {
5647 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5648 // quadratic equation to solve it. To do this, we must frame our problem in
5649 // terms of figuring out when zero is crossed, instead of when
5650 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005651 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005652 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005653 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005654
5655 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005656 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005657 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005658 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5659 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005660 if (R1) {
5661 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005662 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005663 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005664 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005665 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005666 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005667
Chris Lattner53e677a2004-04-02 20:23:17 +00005668 // Make sure the root is not off by one. The returned iteration should
5669 // not be in the range, but the previous one should be. When solving
5670 // for "X*X < 5", for example, we should not return a root of 2.
5671 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005672 R1->getValue(),
5673 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005674 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005675 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005676 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005677 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005678
Dan Gohman246b2562007-10-22 18:31:58 +00005679 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005680 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005681 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005682 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005683 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005684
Chris Lattner53e677a2004-04-02 20:23:17 +00005685 // If R1 was not in the range, then it is a good return value. Make
5686 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005687 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005688 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005689 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005690 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005691 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005692 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005693 }
5694 }
5695 }
5696
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005697 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005698}
5699
5700
5701
5702//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005703// SCEVCallbackVH Class Implementation
5704//===----------------------------------------------------------------------===//
5705
Dan Gohman1959b752009-05-19 19:22:47 +00005706void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005707 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005708 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5709 SE->ConstantEvolutionLoopExitValue.erase(PN);
5710 SE->Scalars.erase(getValPtr());
5711 // this now dangles!
5712}
5713
Dan Gohman81f91212010-07-28 01:09:07 +00005714void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005715 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005716
Dan Gohman35738ac2009-05-04 22:30:44 +00005717 // Forget all the expressions associated with users of the old value,
5718 // so that future queries will recompute the expressions using the new
5719 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005720 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005721 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005722 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005723 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5724 UI != UE; ++UI)
5725 Worklist.push_back(*UI);
5726 while (!Worklist.empty()) {
5727 User *U = Worklist.pop_back_val();
5728 // Deleting the Old value will cause this to dangle. Postpone
5729 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005730 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005731 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005732 if (!Visited.insert(U))
5733 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005734 if (PHINode *PN = dyn_cast<PHINode>(U))
5735 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005736 SE->Scalars.erase(U);
5737 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5738 UI != UE; ++UI)
5739 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005740 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005741 // Delete the Old value.
5742 if (PHINode *PN = dyn_cast<PHINode>(Old))
5743 SE->ConstantEvolutionLoopExitValue.erase(PN);
5744 SE->Scalars.erase(Old);
5745 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005746}
5747
Dan Gohman1959b752009-05-19 19:22:47 +00005748ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005749 : CallbackVH(V), SE(se) {}
5750
5751//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005752// ScalarEvolution Class Implementation
5753//===----------------------------------------------------------------------===//
5754
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005755ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005756 : FunctionPass(ID), FirstUnknown(0) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005757}
5758
Chris Lattner53e677a2004-04-02 20:23:17 +00005759bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005760 this->F = &F;
5761 LI = &getAnalysis<LoopInfo>();
5762 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005763 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005764 return false;
5765}
5766
5767void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005768 // Iterate through all the SCEVUnknown instances and call their
5769 // destructors, so that they release their references to their values.
5770 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5771 U->~SCEVUnknown();
5772 FirstUnknown = 0;
5773
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005774 Scalars.clear();
5775 BackedgeTakenCounts.clear();
5776 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005777 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005778 UniqueSCEVs.clear();
5779 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005780}
5781
5782void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5783 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005784 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005785 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005786}
5787
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005788bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005789 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005790}
5791
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005792static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005793 const Loop *L) {
5794 // Print all inner loops first
5795 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5796 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005797
Dan Gohman30733292010-01-09 18:17:45 +00005798 OS << "Loop ";
5799 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5800 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005801
Dan Gohman5d984912009-12-18 01:14:11 +00005802 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005803 L->getExitBlocks(ExitBlocks);
5804 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005805 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005806
Dan Gohman46bdfb02009-02-24 18:55:53 +00005807 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5808 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005809 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005810 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005811 }
5812
Dan Gohman30733292010-01-09 18:17:45 +00005813 OS << "\n"
5814 "Loop ";
5815 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5816 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005817
5818 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5819 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5820 } else {
5821 OS << "Unpredictable max backedge-taken count. ";
5822 }
5823
5824 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005825}
5826
Dan Gohman5d984912009-12-18 01:14:11 +00005827void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005828 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005829 // out SCEV values of all instructions that are interesting. Doing
5830 // this potentially causes it to create new SCEV objects though,
5831 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005832 // observable from outside the class though, so casting away the
5833 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005834 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005835
Dan Gohman30733292010-01-09 18:17:45 +00005836 OS << "Classifying expressions for: ";
5837 WriteAsOperand(OS, F, /*PrintType=*/false);
5838 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005839 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005840 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005841 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005842 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005843 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005844 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005845
Dan Gohman0c689c52009-06-19 17:49:54 +00005846 const Loop *L = LI->getLoopFor((*I).getParent());
5847
Dan Gohman0bba49c2009-07-07 17:06:11 +00005848 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005849 if (AtUse != SV) {
5850 OS << " --> ";
5851 AtUse->print(OS);
5852 }
5853
5854 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005855 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005856 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005857 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005858 OS << "<<Unknown>>";
5859 } else {
5860 OS << *ExitValue;
5861 }
5862 }
5863
Chris Lattner53e677a2004-04-02 20:23:17 +00005864 OS << "\n";
5865 }
5866
Dan Gohman30733292010-01-09 18:17:45 +00005867 OS << "Determining loop execution counts for: ";
5868 WriteAsOperand(OS, F, /*PrintType=*/false);
5869 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005870 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5871 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005872}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005873