blob: 20b886e4aa02b5177fd4831867c933c24c8929e1 [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 {
Dan Gohmanbb854092010-08-16 16:16:11 +0000261 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
262 if (!(*I)->dominates(BB, DT))
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000263 return false;
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
Dan Gohmanbb854092010-08-16 16:16:11 +0000268 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
269 if (!(*I)->properlyDominates(BB, DT))
Dan Gohman6e70e312009-09-27 15:26:03 +0000270 return false;
Dan Gohman6e70e312009-09-27 15:26:03 +0000271 return true;
272}
273
Dan Gohman2f199f92010-08-16 16:21:27 +0000274bool SCEVNAryExpr::isLoopInvariant(const Loop *L) const {
275 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
276 if (!(*I)->isLoopInvariant(L))
277 return false;
278 return true;
279}
280
281// hasComputableLoopEvolution - N-ary expressions have computable loop
282// evolutions iff they have at least one operand that varies with the loop,
283// but that all varying operands are computable.
284bool SCEVNAryExpr::hasComputableLoopEvolution(const Loop *L) const {
285 bool HasVarying = false;
286 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
287 const SCEV *S = *I;
288 if (!S->isLoopInvariant(L)) {
289 if (S->hasComputableLoopEvolution(L))
290 HasVarying = true;
291 else
292 return false;
293 }
294 }
295 return HasVarying;
296}
297
298bool SCEVNAryExpr::hasOperand(const SCEV *O) const {
299 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
300 const SCEV *S = *I;
301 if (O == S || S->hasOperand(O))
302 return true;
303 }
304 return false;
305}
306
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000307bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
308 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
309}
310
Dan Gohman6e70e312009-09-27 15:26:03 +0000311bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
312 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
313}
314
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000315void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000316 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000319const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000320 // In most cases the types of LHS and RHS will be the same, but in some
321 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
322 // depend on the type for correctness, but handling types carefully can
323 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
324 // a pointer type than the RHS, so use the RHS' type here.
325 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000326}
327
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000328bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000329 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000330 if (!QueryLoop)
331 return false;
332
333 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000334 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000335 return false;
336
Dan Gohman71c41442010-08-13 20:11:39 +0000337 // This recurrence is invariant w.r.t. QueryLoop if L contains QueryLoop.
338 if (L->contains(QueryLoop))
339 return true;
340
Dan Gohmane890eea2009-06-26 22:17:21 +0000341 // This recurrence is variant w.r.t. QueryLoop if any of its operands
342 // are variant.
343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
344 if (!getOperand(i)->isLoopInvariant(QueryLoop))
345 return false;
346
347 // Otherwise it's loop-invariant.
348 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000349}
350
Dan Gohman39125d82010-02-13 00:19:39 +0000351bool
352SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
353 return DT->dominates(L->getHeader(), BB) &&
354 SCEVNAryExpr::dominates(BB, DT);
355}
356
357bool
358SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
359 // This uses a "dominates" query instead of "properly dominates" query because
360 // the instruction which produces the addrec's value is a PHI, and a PHI
361 // effectively properly dominates its entire containing block.
362 return DT->dominates(L->getHeader(), BB) &&
363 SCEVNAryExpr::properlyDominates(BB, DT);
364}
365
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000366void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000367 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000368 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000369 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000370 OS << "}<";
371 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
372 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000373}
Chris Lattner53e677a2004-04-02 20:23:17 +0000374
Dan Gohmanab37f502010-08-02 23:49:30 +0000375void SCEVUnknown::deleted() {
376 // Clear this SCEVUnknown from ValuesAtScopes.
377 SE->ValuesAtScopes.erase(this);
378
379 // Remove this SCEVUnknown from the uniquing map.
380 SE->UniqueSCEVs.RemoveNode(this);
381
382 // Release the value.
383 setValPtr(0);
384}
385
386void SCEVUnknown::allUsesReplacedWith(Value *New) {
387 // Clear this SCEVUnknown from ValuesAtScopes.
388 SE->ValuesAtScopes.erase(this);
389
390 // Remove this SCEVUnknown from the uniquing map.
391 SE->UniqueSCEVs.RemoveNode(this);
392
393 // Update this SCEVUnknown to point to the new value. This is needed
394 // because there may still be outstanding SCEVs which still point to
395 // this SCEVUnknown.
396 setValPtr(New);
397}
398
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000399bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
400 // All non-instruction values are loop invariant. All instructions are loop
401 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000402 // Instructions are never considered invariant in the function body
403 // (null loop) because they are defined within the "loop".
Dan Gohmanab37f502010-08-02 23:49:30 +0000404 if (Instruction *I = dyn_cast<Instruction>(getValue()))
Dan Gohman92329c72009-12-18 01:24:09 +0000405 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000406 return true;
407}
Chris Lattner53e677a2004-04-02 20:23:17 +0000408
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000409bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
410 if (Instruction *I = dyn_cast<Instruction>(getValue()))
411 return DT->dominates(I->getParent(), BB);
412 return true;
413}
414
Dan Gohman6e70e312009-09-27 15:26:03 +0000415bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
416 if (Instruction *I = dyn_cast<Instruction>(getValue()))
417 return DT->properlyDominates(I->getParent(), BB);
418 return true;
419}
420
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000421const Type *SCEVUnknown::getType() const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000422 return getValue()->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000423}
Chris Lattner53e677a2004-04-02 20:23:17 +0000424
Dan Gohman0f5efe52010-01-28 02:15:55 +0000425bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000426 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000427 if (VCE->getOpcode() == Instruction::PtrToInt)
428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000429 if (CE->getOpcode() == Instruction::GetElementPtr &&
430 CE->getOperand(0)->isNullValue() &&
431 CE->getNumOperands() == 2)
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
433 if (CI->isOne()) {
434 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
435 ->getElementType();
436 return true;
437 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000438
439 return false;
440}
441
442bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000443 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000444 if (VCE->getOpcode() == Instruction::PtrToInt)
445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000446 if (CE->getOpcode() == Instruction::GetElementPtr &&
447 CE->getOperand(0)->isNullValue()) {
448 const Type *Ty =
449 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
450 if (const StructType *STy = dyn_cast<StructType>(Ty))
451 if (!STy->isPacked() &&
452 CE->getNumOperands() == 3 &&
453 CE->getOperand(1)->isNullValue()) {
454 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
455 if (CI->isOne() &&
456 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000457 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000458 AllocTy = STy->getElementType(1);
459 return true;
460 }
461 }
462 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000463
464 return false;
465}
466
Dan Gohman4f8eea82010-02-01 18:27:38 +0000467bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000468 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000469 if (VCE->getOpcode() == Instruction::PtrToInt)
470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
471 if (CE->getOpcode() == Instruction::GetElementPtr &&
472 CE->getNumOperands() == 3 &&
473 CE->getOperand(0)->isNullValue() &&
474 CE->getOperand(1)->isNullValue()) {
475 const Type *Ty =
476 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
477 // Ignore vector types here so that ScalarEvolutionExpander doesn't
478 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000479 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000480 CTy = Ty;
481 FieldNo = CE->getOperand(2);
482 return true;
483 }
484 }
485
486 return false;
487}
488
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000489void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000490 const Type *AllocTy;
491 if (isSizeOf(AllocTy)) {
492 OS << "sizeof(" << *AllocTy << ")";
493 return;
494 }
495 if (isAlignOf(AllocTy)) {
496 OS << "alignof(" << *AllocTy << ")";
497 return;
498 }
499
Dan Gohman4f8eea82010-02-01 18:27:38 +0000500 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000501 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000502 if (isOffsetOf(CTy, FieldNo)) {
503 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000504 WriteAsOperand(OS, FieldNo, false);
505 OS << ")";
506 return;
507 }
508
509 // Otherwise just print it normally.
Dan Gohmanab37f502010-08-02 23:49:30 +0000510 WriteAsOperand(OS, getValue(), false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000511}
512
Chris Lattner8d741b82004-06-20 06:23:15 +0000513//===----------------------------------------------------------------------===//
514// SCEV Utilities
515//===----------------------------------------------------------------------===//
516
517namespace {
518 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
519 /// than the complexity of the RHS. This comparator is used to canonicalize
520 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000521 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000522 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000523 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000524 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000525
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000526 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000527 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
528 if (LHS == RHS)
529 return false;
530
Dan Gohman72861302009-05-07 14:39:04 +0000531 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000532 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
533 if (LType != RType)
534 return LType < RType;
Dan Gohman72861302009-05-07 14:39:04 +0000535
Dan Gohman3bf63762010-06-18 19:54:20 +0000536 // Aside from the getSCEVType() ordering, the particular ordering
537 // isn't very important except that it's beneficial to be consistent,
538 // so that (a + b) and (b + a) don't end up as different expressions.
539
540 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
541 // not as complete as it could be.
542 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
543 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000544 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000545
546 // Order pointer values after integer values. This helps SCEVExpander
547 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000548 bool LIsPointer = LV->getType()->isPointerTy(),
549 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000550 if (LIsPointer != RIsPointer)
551 return RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000552
553 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000554 unsigned LID = LV->getValueID(),
555 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000556 if (LID != RID)
557 return LID < RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000558
559 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000560 if (const Argument *LA = dyn_cast<Argument>(LV)) {
561 const Argument *RA = cast<Argument>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000562 return LA->getArgNo() < RA->getArgNo();
563 }
564
565 // For instructions, compare their loop depth, and their opcode.
566 // This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000567 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
568 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000569
570 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000571 const BasicBlock *LParent = LInst->getParent(),
572 *RParent = RInst->getParent();
573 if (LParent != RParent) {
574 unsigned LDepth = LI->getLoopDepth(LParent),
575 RDepth = LI->getLoopDepth(RParent);
576 if (LDepth != RDepth)
577 return LDepth < RDepth;
578 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000579
580 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000581 unsigned LNumOps = LInst->getNumOperands(),
582 RNumOps = RInst->getNumOperands();
Dan Gohman304a7a62010-07-23 21:20:52 +0000583 if (LNumOps != RNumOps)
584 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000585 }
586
587 return false;
588 }
589
590 // Compare constant values.
591 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
592 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohmane28d7922010-08-16 16:25:35 +0000593 const APInt &LA = LC->getValue()->getValue();
594 const APInt &RA = RC->getValue()->getValue();
595 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman304a7a62010-07-23 21:20:52 +0000596 if (LBitWidth != RBitWidth)
597 return LBitWidth < RBitWidth;
Dan Gohmane28d7922010-08-16 16:25:35 +0000598 return LA.ult(RA);
Dan Gohman3bf63762010-06-18 19:54:20 +0000599 }
600
601 // Compare addrec loop depths.
602 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
603 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000604 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
605 if (LLoop != RLoop) {
606 unsigned LDepth = LLoop->getLoopDepth(),
607 RDepth = RLoop->getLoopDepth();
608 if (LDepth != RDepth)
609 return LDepth < RDepth;
610 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000611 }
612
613 // Lexicographically compare n-ary expressions.
614 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
615 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000616 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
617 for (unsigned i = 0; i != LNumOps; ++i) {
618 if (i >= RNumOps)
Dan Gohman3bf63762010-06-18 19:54:20 +0000619 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000620 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
621 if (operator()(LOp, ROp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000622 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000623 if (operator()(ROp, LOp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000624 return false;
625 }
Dan Gohman304a7a62010-07-23 21:20:52 +0000626 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000627 }
628
629 // Lexicographically compare udiv expressions.
630 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
631 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000632 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
633 *RL = RC->getLHS(), *RR = RC->getRHS();
634 if (operator()(LL, RL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000635 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000636 if (operator()(RL, LL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000637 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000638 if (operator()(LR, RR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000639 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000640 if (operator()(RR, LR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000641 return false;
642 return false;
643 }
644
645 // Compare cast expressions by operand.
646 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
647 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
648 return operator()(LC->getOperand(), RC->getOperand());
649 }
650
651 llvm_unreachable("Unknown SCEV kind!");
652 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000653 }
654 };
655}
656
657/// GroupByComplexity - Given a list of SCEV objects, order them by their
658/// complexity, and group objects of the same complexity together by value.
659/// When this routine is finished, we know that any duplicates in the vector are
660/// consecutive and that complexity is monotonically increasing.
661///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000662/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000663/// results from this routine. In other words, we don't want the results of
664/// this to depend on where the addresses of various SCEV objects happened to
665/// land in memory.
666///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000667static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000668 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000669 if (Ops.size() < 2) return; // Noop
670 if (Ops.size() == 2) {
671 // This is the common case, which also happens to be trivially simple.
672 // Special case it.
Dan Gohman3bf63762010-06-18 19:54:20 +0000673 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000674 std::swap(Ops[0], Ops[1]);
675 return;
676 }
677
Dan Gohman3bf63762010-06-18 19:54:20 +0000678 // Do the rough sort by complexity.
679 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
680
681 // Now that we are sorted by complexity, group elements of the same
682 // complexity. Note that this is, at worst, N^2, but the vector is likely to
683 // be extremely short in practice. Note that we take this approach because we
684 // do not want to depend on the addresses of the objects we are grouping.
685 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
686 const SCEV *S = Ops[i];
687 unsigned Complexity = S->getSCEVType();
688
689 // If there are any objects of the same complexity and same value as this
690 // one, group them.
691 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
692 if (Ops[j] == S) { // Found a duplicate.
693 // Move it to immediately after i'th element.
694 std::swap(Ops[i+1], Ops[j]);
695 ++i; // no need to rescan it.
696 if (i == e-2) return; // Done!
697 }
698 }
699 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000700}
701
Chris Lattner53e677a2004-04-02 20:23:17 +0000702
Chris Lattner53e677a2004-04-02 20:23:17 +0000703
704//===----------------------------------------------------------------------===//
705// Simple SCEV method implementations
706//===----------------------------------------------------------------------===//
707
Eli Friedmanb42a6262008-08-04 23:49:06 +0000708/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000709/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000710static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000711 ScalarEvolution &SE,
712 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000713 // Handle the simplest case efficiently.
714 if (K == 1)
715 return SE.getTruncateOrZeroExtend(It, ResultTy);
716
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000717 // We are using the following formula for BC(It, K):
718 //
719 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
720 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000721 // Suppose, W is the bitwidth of the return value. We must be prepared for
722 // overflow. Hence, we must assure that the result of our computation is
723 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
724 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000725 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000726 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000727 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000728 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
729 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000730 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000731 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000732 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000733 // This formula is trivially equivalent to the previous formula. However,
734 // this formula can be implemented much more efficiently. The trick is that
735 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
736 // arithmetic. To do exact division in modular arithmetic, all we have
737 // to do is multiply by the inverse. Therefore, this step can be done at
738 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000739 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000740 // The next issue is how to safely do the division by 2^T. The way this
741 // is done is by doing the multiplication step at a width of at least W + T
742 // bits. This way, the bottom W+T bits of the product are accurate. Then,
743 // when we perform the division by 2^T (which is equivalent to a right shift
744 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
745 // truncated out after the division by 2^T.
746 //
747 // In comparison to just directly using the first formula, this technique
748 // is much more efficient; using the first formula requires W * K bits,
749 // but this formula less than W + K bits. Also, the first formula requires
750 // a division step, whereas this formula only requires multiplies and shifts.
751 //
752 // It doesn't matter whether the subtraction step is done in the calculation
753 // width or the input iteration count's width; if the subtraction overflows,
754 // the result must be zero anyway. We prefer here to do it in the width of
755 // the induction variable because it helps a lot for certain cases; CodeGen
756 // isn't smart enough to ignore the overflow, which leads to much less
757 // efficient code if the width of the subtraction is wider than the native
758 // register width.
759 //
760 // (It's possible to not widen at all by pulling out factors of 2 before
761 // the multiplication; for example, K=2 can be calculated as
762 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
763 // extra arithmetic, so it's not an obvious win, and it gets
764 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000765
Eli Friedmanb42a6262008-08-04 23:49:06 +0000766 // Protection from insane SCEVs; this bound is conservative,
767 // but it probably doesn't matter.
768 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000769 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000770
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000771 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000772
Eli Friedmanb42a6262008-08-04 23:49:06 +0000773 // Calculate K! / 2^T and T; we divide out the factors of two before
774 // multiplying for calculating K! / 2^T to avoid overflow.
775 // Other overflow doesn't matter because we only care about the bottom
776 // W bits of the result.
777 APInt OddFactorial(W, 1);
778 unsigned T = 1;
779 for (unsigned i = 3; i <= K; ++i) {
780 APInt Mult(W, i);
781 unsigned TwoFactors = Mult.countTrailingZeros();
782 T += TwoFactors;
783 Mult = Mult.lshr(TwoFactors);
784 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000785 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000786
Eli Friedmanb42a6262008-08-04 23:49:06 +0000787 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000788 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000789
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000790 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000791 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
792
793 // Calculate the multiplicative inverse of K! / 2^T;
794 // this multiplication factor will perform the exact division by
795 // K! / 2^T.
796 APInt Mod = APInt::getSignedMinValue(W+1);
797 APInt MultiplyFactor = OddFactorial.zext(W+1);
798 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
799 MultiplyFactor = MultiplyFactor.trunc(W);
800
801 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000802 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
803 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000804 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000805 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000806 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000807 Dividend = SE.getMulExpr(Dividend,
808 SE.getTruncateOrZeroExtend(S, CalculationTy));
809 }
810
811 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000812 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000813
814 // Truncate the result, and divide by K! / 2^T.
815
816 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
817 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000818}
819
Chris Lattner53e677a2004-04-02 20:23:17 +0000820/// evaluateAtIteration - Return the value of this chain of recurrences at
821/// the specified iteration number. We can evaluate this recurrence by
822/// multiplying each element in the chain by the binomial coefficient
823/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
824///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000825/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000826///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000827/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000828///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000829const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000830 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000831 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000832 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000833 // The computation is correct in the face of overflow provided that the
834 // multiplication is performed _after_ the evaluation of the binomial
835 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000836 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000837 if (isa<SCEVCouldNotCompute>(Coeff))
838 return Coeff;
839
840 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000841 }
842 return Result;
843}
844
Chris Lattner53e677a2004-04-02 20:23:17 +0000845//===----------------------------------------------------------------------===//
846// SCEV Expression folder implementations
847//===----------------------------------------------------------------------===//
848
Dan Gohman0bba49c2009-07-07 17:06:11 +0000849const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000850 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000851 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000852 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000853 assert(isSCEVable(Ty) &&
854 "This is not a conversion to a SCEVable type!");
855 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000856
Dan Gohmanc050fd92009-07-13 20:50:19 +0000857 FoldingSetNodeID ID;
858 ID.AddInteger(scTruncate);
859 ID.AddPointer(Op);
860 ID.AddPointer(Ty);
861 void *IP = 0;
862 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
863
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000864 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000865 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000866 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000867 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
868 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000869
Dan Gohman20900ca2009-04-22 16:20:48 +0000870 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000871 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000872 return getTruncateExpr(ST->getOperand(), Ty);
873
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000874 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000875 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000876 return getTruncateOrSignExtend(SS->getOperand(), Ty);
877
878 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000879 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000880 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
881
Dan Gohman6864db62009-06-18 16:24:47 +0000882 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000883 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000884 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000885 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000886 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
887 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000888 }
889
Dan Gohmanf53462d2010-07-15 20:02:11 +0000890 // As a special case, fold trunc(undef) to undef. We don't want to
891 // know too much about SCEVUnknowns, but this special case is handy
892 // and harmless.
893 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
894 if (isa<UndefValue>(U->getValue()))
895 return getSCEV(UndefValue::get(Ty));
896
Dan Gohman420ab912010-06-25 18:47:08 +0000897 // The cast wasn't folded; create an explicit cast node. We can reuse
898 // the existing insert position since if we get here, we won't have
899 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000900 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
901 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000902 UniqueSCEVs.InsertNode(S, IP);
903 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000904}
905
Dan Gohman0bba49c2009-07-07 17:06:11 +0000906const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000907 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000908 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000909 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000910 assert(isSCEVable(Ty) &&
911 "This is not a conversion to a SCEVable type!");
912 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000913
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000914 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000915 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
916 return getConstant(
917 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
918 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000919
Dan Gohman20900ca2009-04-22 16:20:48 +0000920 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000921 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000922 return getZeroExtendExpr(SZ->getOperand(), Ty);
923
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000924 // Before doing any expensive analysis, check to see if we've already
925 // computed a SCEV for this Op and Ty.
926 FoldingSetNodeID ID;
927 ID.AddInteger(scZeroExtend);
928 ID.AddPointer(Op);
929 ID.AddPointer(Ty);
930 void *IP = 0;
931 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
932
Dan Gohman01ecca22009-04-27 20:16:15 +0000933 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000934 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000935 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000936 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000937 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000938 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000939 const SCEV *Start = AR->getStart();
940 const SCEV *Step = AR->getStepRecurrence(*this);
941 unsigned BitWidth = getTypeSizeInBits(AR->getType());
942 const Loop *L = AR->getLoop();
943
Dan Gohmaneb490a72009-07-25 01:22:26 +0000944 // If we have special knowledge that this addrec won't overflow,
945 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000946 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000947 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
948 getZeroExtendExpr(Step, Ty),
949 L);
950
Dan Gohman01ecca22009-04-27 20:16:15 +0000951 // Check whether the backedge-taken count is SCEVCouldNotCompute.
952 // Note that this serves two purposes: It filters out loops that are
953 // simply not analyzable, and it covers the case where this code is
954 // being called from within backedge-taken count analysis, such that
955 // attempting to ask for the backedge-taken count would likely result
956 // in infinite recursion. In the later case, the analysis code will
957 // cope with a conservative value, and it will take care to purge
958 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000959 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000960 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000961 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000962 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000963
964 // Check whether the backedge-taken count can be losslessly casted to
965 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000966 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000967 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000968 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000969 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
970 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000971 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000972 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000973 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000974 const SCEV *Add = getAddExpr(Start, ZMul);
975 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000976 getAddExpr(getZeroExtendExpr(Start, WideTy),
977 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
978 getZeroExtendExpr(Step, WideTy)));
979 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000980 // Return the expression with the addrec on the outside.
981 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
982 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000983 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000984
985 // Similar to above, only this time treat the step value as signed.
986 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000987 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000988 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000989 OperandExtendedAdd =
990 getAddExpr(getZeroExtendExpr(Start, WideTy),
991 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
992 getSignExtendExpr(Step, WideTy)));
993 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000994 // Return the expression with the addrec on the outside.
995 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
996 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000997 L);
998 }
999
1000 // If the backedge is guarded by a comparison with the pre-inc value
1001 // the addrec is safe. Also, if the entry is guarded by a comparison
1002 // with the start value and the backedge is guarded by a comparison
1003 // with the post-inc value, the addrec is safe.
1004 if (isKnownPositive(Step)) {
1005 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1006 getUnsignedRange(Step).getUnsignedMax());
1007 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001008 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001009 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1010 AR->getPostIncExpr(*this), N)))
1011 // Return the expression with the addrec on the outside.
1012 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1013 getZeroExtendExpr(Step, Ty),
1014 L);
1015 } else if (isKnownNegative(Step)) {
1016 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1017 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +00001018 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1019 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001020 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1021 AR->getPostIncExpr(*this), N)))
1022 // Return the expression with the addrec on the outside.
1023 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1024 getSignExtendExpr(Step, Ty),
1025 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001026 }
1027 }
1028 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001029
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001030 // The cast wasn't folded; create an explicit cast node.
1031 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001032 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001033 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1034 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001035 UniqueSCEVs.InsertNode(S, IP);
1036 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001037}
1038
Dan Gohman0bba49c2009-07-07 17:06:11 +00001039const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001040 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001041 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001042 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001043 assert(isSCEVable(Ty) &&
1044 "This is not a conversion to a SCEVable type!");
1045 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001046
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001047 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001048 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1049 return getConstant(
1050 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1051 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001052
Dan Gohman20900ca2009-04-22 16:20:48 +00001053 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001054 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001055 return getSignExtendExpr(SS->getOperand(), Ty);
1056
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001057 // Before doing any expensive analysis, check to see if we've already
1058 // computed a SCEV for this Op and Ty.
1059 FoldingSetNodeID ID;
1060 ID.AddInteger(scSignExtend);
1061 ID.AddPointer(Op);
1062 ID.AddPointer(Ty);
1063 void *IP = 0;
1064 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1065
Dan Gohman01ecca22009-04-27 20:16:15 +00001066 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001067 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001068 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001069 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001070 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001071 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001072 const SCEV *Start = AR->getStart();
1073 const SCEV *Step = AR->getStepRecurrence(*this);
1074 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1075 const Loop *L = AR->getLoop();
1076
Dan Gohmaneb490a72009-07-25 01:22:26 +00001077 // If we have special knowledge that this addrec won't overflow,
1078 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001079 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001080 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1081 getSignExtendExpr(Step, Ty),
1082 L);
1083
Dan Gohman01ecca22009-04-27 20:16:15 +00001084 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1085 // Note that this serves two purposes: It filters out loops that are
1086 // simply not analyzable, and it covers the case where this code is
1087 // being called from within backedge-taken count analysis, such that
1088 // attempting to ask for the backedge-taken count would likely result
1089 // in infinite recursion. In the later case, the analysis code will
1090 // cope with a conservative value, and it will take care to purge
1091 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001092 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001093 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001094 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001095 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001096
1097 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001098 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001099 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001100 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001101 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001102 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1103 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001104 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001105 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001106 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001107 const SCEV *Add = getAddExpr(Start, SMul);
1108 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001109 getAddExpr(getSignExtendExpr(Start, WideTy),
1110 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1111 getSignExtendExpr(Step, WideTy)));
1112 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001113 // Return the expression with the addrec on the outside.
1114 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1115 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001116 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001117
1118 // Similar to above, only this time treat the step value as unsigned.
1119 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001120 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001121 Add = getAddExpr(Start, UMul);
1122 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001123 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001124 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1125 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001126 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001127 // Return the expression with the addrec on the outside.
1128 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1129 getZeroExtendExpr(Step, Ty),
1130 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001131 }
1132
1133 // If the backedge is guarded by a comparison with the pre-inc value
1134 // the addrec is safe. Also, if the entry is guarded by a comparison
1135 // with the start value and the backedge is guarded by a comparison
1136 // with the post-inc value, the addrec is safe.
1137 if (isKnownPositive(Step)) {
1138 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1139 getSignedRange(Step).getSignedMax());
1140 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001141 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001142 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1143 AR->getPostIncExpr(*this), N)))
1144 // Return the expression with the addrec on the outside.
1145 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1146 getSignExtendExpr(Step, Ty),
1147 L);
1148 } else if (isKnownNegative(Step)) {
1149 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1150 getSignedRange(Step).getSignedMin());
1151 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001152 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001153 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1154 AR->getPostIncExpr(*this), N)))
1155 // Return the expression with the addrec on the outside.
1156 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1157 getSignExtendExpr(Step, Ty),
1158 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001159 }
1160 }
1161 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001162
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001163 // The cast wasn't folded; create an explicit cast node.
1164 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001165 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001166 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1167 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001168 UniqueSCEVs.InsertNode(S, IP);
1169 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001170}
1171
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001172/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1173/// unspecified bits out to the given type.
1174///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001175const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001176 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001177 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1178 "This is not an extending conversion!");
1179 assert(isSCEVable(Ty) &&
1180 "This is not a conversion to a SCEVable type!");
1181 Ty = getEffectiveSCEVType(Ty);
1182
1183 // Sign-extend negative constants.
1184 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1185 if (SC->getValue()->getValue().isNegative())
1186 return getSignExtendExpr(Op, Ty);
1187
1188 // Peel off a truncate cast.
1189 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001190 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001191 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1192 return getAnyExtendExpr(NewOp, Ty);
1193 return getTruncateOrNoop(NewOp, Ty);
1194 }
1195
1196 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001197 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001198 if (!isa<SCEVZeroExtendExpr>(ZExt))
1199 return ZExt;
1200
1201 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001202 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001203 if (!isa<SCEVSignExtendExpr>(SExt))
1204 return SExt;
1205
Dan Gohmana10756e2010-01-21 02:09:26 +00001206 // Force the cast to be folded into the operands of an addrec.
1207 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1208 SmallVector<const SCEV *, 4> Ops;
1209 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1210 I != E; ++I)
1211 Ops.push_back(getAnyExtendExpr(*I, Ty));
1212 return getAddRecExpr(Ops, AR->getLoop());
1213 }
1214
Dan Gohmanf53462d2010-07-15 20:02:11 +00001215 // As a special case, fold anyext(undef) to undef. We don't want to
1216 // know too much about SCEVUnknowns, but this special case is handy
1217 // and harmless.
1218 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1219 if (isa<UndefValue>(U->getValue()))
1220 return getSCEV(UndefValue::get(Ty));
1221
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001222 // If the expression is obviously signed, use the sext cast value.
1223 if (isa<SCEVSMaxExpr>(Op))
1224 return SExt;
1225
1226 // Absent any other information, use the zext cast value.
1227 return ZExt;
1228}
1229
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001230/// CollectAddOperandsWithScales - Process the given Ops list, which is
1231/// a list of operands to be added under the given scale, update the given
1232/// map. This is a helper function for getAddRecExpr. As an example of
1233/// what it does, given a sequence of operands that would form an add
1234/// expression like this:
1235///
1236/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1237///
1238/// where A and B are constants, update the map with these values:
1239///
1240/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1241///
1242/// and add 13 + A*B*29 to AccumulatedConstant.
1243/// This will allow getAddRecExpr to produce this:
1244///
1245/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1246///
1247/// This form often exposes folding opportunities that are hidden in
1248/// the original operand list.
1249///
1250/// Return true iff it appears that any interesting folding opportunities
1251/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1252/// the common case where no interesting opportunities are present, and
1253/// is also used as a check to avoid infinite recursion.
1254///
1255static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001256CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1257 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001258 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001259 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001260 const APInt &Scale,
1261 ScalarEvolution &SE) {
1262 bool Interesting = false;
1263
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001264 // Iterate over the add operands. They are sorted, with constants first.
1265 unsigned i = 0;
1266 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1267 ++i;
1268 // Pull a buried constant out to the outside.
1269 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1270 Interesting = true;
1271 AccumulatedConstant += Scale * C->getValue()->getValue();
1272 }
1273
1274 // Next comes everything else. We're especially interested in multiplies
1275 // here, but they're in the middle, so just visit the rest with one loop.
1276 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001277 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1278 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1279 APInt NewScale =
1280 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1281 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1282 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001283 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001284 Interesting |=
1285 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001286 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001287 NewScale, SE);
1288 } else {
1289 // A multiplication of a constant with some other value. Update
1290 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001291 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1292 const SCEV *Key = SE.getMulExpr(MulOps);
1293 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001294 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001295 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001296 NewOps.push_back(Pair.first->first);
1297 } else {
1298 Pair.first->second += NewScale;
1299 // The map already had an entry for this value, which may indicate
1300 // a folding opportunity.
1301 Interesting = true;
1302 }
1303 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001304 } else {
1305 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001306 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001307 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001308 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001309 NewOps.push_back(Pair.first->first);
1310 } else {
1311 Pair.first->second += Scale;
1312 // The map already had an entry for this value, which may indicate
1313 // a folding opportunity.
1314 Interesting = true;
1315 }
1316 }
1317 }
1318
1319 return Interesting;
1320}
1321
1322namespace {
1323 struct APIntCompare {
1324 bool operator()(const APInt &LHS, const APInt &RHS) const {
1325 return LHS.ult(RHS);
1326 }
1327 };
1328}
1329
Dan Gohman6c0866c2009-05-24 23:45:28 +00001330/// getAddExpr - Get a canonical add expression, or something simpler if
1331/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001332const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1333 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001334 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001335 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001336#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001337 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001338 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001339 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001340 "SCEVAddExpr operand types don't match!");
1341#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001342
Dan Gohmana10756e2010-01-21 02:09:26 +00001343 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1344 if (!HasNUW && HasNSW) {
1345 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001346 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1347 E = Ops.end(); I != E; ++I)
1348 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001349 All = false;
1350 break;
1351 }
1352 if (All) HasNUW = true;
1353 }
1354
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001356 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001357
1358 // If there are any constants, fold them together.
1359 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001360 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001361 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001362 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001363 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001365 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1366 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001367 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001368 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001369 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001370 }
1371
1372 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001373 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001374 Ops.erase(Ops.begin());
1375 --Idx;
1376 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001377
Dan Gohmanbca091d2010-04-12 23:08:18 +00001378 if (Ops.size() == 1) return Ops[0];
1379 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001380
Chris Lattner53e677a2004-04-02 20:23:17 +00001381 // Okay, check to see if the same value occurs in the operand list twice. If
1382 // so, merge them together into an multiply expression. Since we sorted the
1383 // list, these values are required to be adjacent.
1384 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001385 bool FoundMatch = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1387 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1388 // Found a match, merge the two values into a multiply, and add any
1389 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001390 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman58a85b92010-08-13 20:17:14 +00001391 const SCEV *Mul = getMulExpr(Two, Ops[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001392 if (Ops.size() == 2)
1393 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001394 Ops[i] = Mul;
1395 Ops.erase(Ops.begin()+i+1);
1396 --i; --e;
1397 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001398 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001399 if (FoundMatch)
1400 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001401
Dan Gohman728c7f32009-05-08 21:03:19 +00001402 // Check for truncates. If all the operands are truncated from the same
1403 // type, see if factoring out the truncate would permit the result to be
1404 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1405 // if the contents of the resulting outer trunc fold to something simple.
1406 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1407 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1408 const Type *DstType = Trunc->getType();
1409 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001410 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001411 bool Ok = true;
1412 // Check all the operands to see if they can be represented in the
1413 // source type of the truncate.
1414 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1415 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1416 if (T->getOperand()->getType() != SrcType) {
1417 Ok = false;
1418 break;
1419 }
1420 LargeOps.push_back(T->getOperand());
1421 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001422 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001423 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001424 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001425 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1426 if (const SCEVTruncateExpr *T =
1427 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1428 if (T->getOperand()->getType() != SrcType) {
1429 Ok = false;
1430 break;
1431 }
1432 LargeMulOps.push_back(T->getOperand());
1433 } else if (const SCEVConstant *C =
1434 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001435 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001436 } else {
1437 Ok = false;
1438 break;
1439 }
1440 }
1441 if (Ok)
1442 LargeOps.push_back(getMulExpr(LargeMulOps));
1443 } else {
1444 Ok = false;
1445 break;
1446 }
1447 }
1448 if (Ok) {
1449 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001450 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001451 // If it folds to something simple, use it. Otherwise, don't.
1452 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1453 return getTruncateExpr(Fold, DstType);
1454 }
1455 }
1456
1457 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001458 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1459 ++Idx;
1460
1461 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 if (Idx < Ops.size()) {
1463 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001464 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 // If we have an add, expand the add operands onto the end of the operands
1466 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001468 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 DeletedAdd = true;
1470 }
1471
1472 // If we deleted at least one add, we added operands to the end of the list,
1473 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001474 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001475 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001476 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 }
1478
1479 // Skip over the add expression until we get to a multiply.
1480 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1481 ++Idx;
1482
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001483 // Check to see if there are any folding opportunities present with
1484 // operands multiplied by constant values.
1485 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1486 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001487 DenseMap<const SCEV *, APInt> M;
1488 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001489 APInt AccumulatedConstant(BitWidth, 0);
1490 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001491 Ops.data(), Ops.size(),
1492 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001493 // Some interesting folding opportunity is present, so its worthwhile to
1494 // re-generate the operands list. Group the operands by constant scale,
1495 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001496 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001497 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001498 E = NewOps.end(); I != E; ++I)
1499 MulOpLists[M.find(*I)->second].push_back(*I);
1500 // Re-generate the operands list.
1501 Ops.clear();
1502 if (AccumulatedConstant != 0)
1503 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001504 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1505 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001506 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001507 Ops.push_back(getMulExpr(getConstant(I->first),
1508 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001509 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001510 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001511 if (Ops.size() == 1)
1512 return Ops[0];
1513 return getAddExpr(Ops);
1514 }
1515 }
1516
Chris Lattner53e677a2004-04-02 20:23:17 +00001517 // If we are adding something to a multiply expression, make sure the
1518 // something is not already an operand of the multiply. If so, merge it into
1519 // the multiply.
1520 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001521 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001522 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001523 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001524 if (isa<SCEVConstant>(MulOpSCEV))
1525 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001527 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001528 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001529 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001530 if (Mul->getNumOperands() != 2) {
1531 // If the multiply has more than two operands, we must get the
1532 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001533 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001534 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001535 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001537 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001538 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001539 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 if (Ops.size() == 2) return OuterMul;
1541 if (AddOp < Idx) {
1542 Ops.erase(Ops.begin()+AddOp);
1543 Ops.erase(Ops.begin()+Idx-1);
1544 } else {
1545 Ops.erase(Ops.begin()+Idx);
1546 Ops.erase(Ops.begin()+AddOp-1);
1547 }
1548 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001549 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001551
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 // Check this multiply against other multiplies being added together.
Dan Gohman727356f2010-08-12 15:00:23 +00001553 bool AnyFold = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 for (unsigned OtherMulIdx = Idx+1;
1555 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1556 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001557 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 // If MulOp occurs in OtherMul, we can fold the two multiplies
1559 // together.
1560 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1561 OMulOp != e; ++OMulOp)
1562 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1563 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001564 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001566 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1567 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001569 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001570 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001571 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001573 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1574 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001576 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001577 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001578 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1579 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 if (Ops.size() == 2) return OuterMul;
Dan Gohman727356f2010-08-12 15:00:23 +00001581 Ops[Idx] = OuterMul;
1582 Ops.erase(Ops.begin()+OtherMulIdx);
1583 OtherMulIdx = Idx;
1584 AnyFold = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001585 }
1586 }
Dan Gohman727356f2010-08-12 15:00:23 +00001587 if (AnyFold)
1588 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 }
1590 }
1591
1592 // If there are any add recurrences in the operands list, see if any other
1593 // added values are loop invariant. If so, we can fold them into the
1594 // recurrence.
1595 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1596 ++Idx;
1597
1598 // Scan over all recurrences, trying to fold loop invariants into them.
1599 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1600 // Scan all of the other operands to this add and add them to the vector if
1601 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001602 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001603 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001604 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001606 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001607 LIOps.push_back(Ops[i]);
1608 Ops.erase(Ops.begin()+i);
1609 --i; --e;
1610 }
1611
1612 // If we found some loop invariants, fold them into the recurrence.
1613 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001614 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 LIOps.push_back(AddRec->getStart());
1616
Dan Gohman0bba49c2009-07-07 17:06:11 +00001617 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001618 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001619 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001620
Dan Gohmanb9f96512010-06-30 07:16:37 +00001621 // Build the new addrec. Propagate the NUW and NSW flags if both the
1622 // outer add and the inner addrec are guaranteed to have no overflow.
1623 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1624 HasNUW && AddRec->hasNoUnsignedWrap(),
1625 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001626
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 // If all of the other operands were loop invariant, we are done.
1628 if (Ops.size() == 1) return NewRec;
1629
1630 // Otherwise, add the folded AddRec by the non-liv parts.
1631 for (unsigned i = 0;; ++i)
1632 if (Ops[i] == AddRec) {
1633 Ops[i] = NewRec;
1634 break;
1635 }
Dan Gohman246b2562007-10-22 18:31:58 +00001636 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001637 }
1638
1639 // Okay, if there weren't any loop invariants to be folded, check to see if
1640 // there are multiple AddRec's with the same loop induction variable being
1641 // added together. If so, we can fold them.
1642 for (unsigned OtherIdx = Idx+1;
1643 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1644 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001645 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001646 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001647 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001648 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1649 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1651 if (i >= NewOps.size()) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001652 NewOps.append(OtherAddRec->op_begin()+i,
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 OtherAddRec->op_end());
1654 break;
1655 }
Dan Gohman246b2562007-10-22 18:31:58 +00001656 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001657 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001658 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001659
1660 if (Ops.size() == 2) return NewAddRec;
1661
1662 Ops.erase(Ops.begin()+Idx);
1663 Ops.erase(Ops.begin()+OtherIdx-1);
1664 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001665 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001666 }
1667 }
1668
1669 // Otherwise couldn't fold anything into this recurrence. Move onto the
1670 // next one.
1671 }
1672
1673 // Okay, it looks like we really DO need an add expr. Check to see if we
1674 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001675 FoldingSetNodeID ID;
1676 ID.AddInteger(scAddExpr);
1677 ID.AddInteger(Ops.size());
1678 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1679 ID.AddPointer(Ops[i]);
1680 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001681 SCEVAddExpr *S =
1682 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1683 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001684 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1685 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001686 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1687 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001688 UniqueSCEVs.InsertNode(S, IP);
1689 }
Dan Gohman3645b012009-10-09 00:10:36 +00001690 if (HasNUW) S->setHasNoUnsignedWrap(true);
1691 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001692 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001693}
1694
Dan Gohman6c0866c2009-05-24 23:45:28 +00001695/// getMulExpr - Get a canonical multiply expression, or something simpler if
1696/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001697const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1698 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001699 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001700 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001701#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001702 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001703 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001704 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001705 "SCEVMulExpr operand types don't match!");
1706#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001707
Dan Gohmana10756e2010-01-21 02:09:26 +00001708 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1709 if (!HasNUW && HasNSW) {
1710 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001711 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1712 E = Ops.end(); I != E; ++I)
1713 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001714 All = false;
1715 break;
1716 }
1717 if (All) HasNUW = true;
1718 }
1719
Chris Lattner53e677a2004-04-02 20:23:17 +00001720 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001721 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001722
1723 // If there are any constants, fold them together.
1724 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001725 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001726
1727 // C1*(C2+V) -> C1*C2 + C1*V
1728 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001729 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001730 if (Add->getNumOperands() == 2 &&
1731 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001732 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1733 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001734
Chris Lattner53e677a2004-04-02 20:23:17 +00001735 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001736 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001738 ConstantInt *Fold = ConstantInt::get(getContext(),
1739 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001740 RHSC->getValue()->getValue());
1741 Ops[0] = getConstant(Fold);
1742 Ops.erase(Ops.begin()+1); // Erase the folded element
1743 if (Ops.size() == 1) return Ops[0];
1744 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 }
1746
1747 // If we are left with a constant one being multiplied, strip it off.
1748 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1749 Ops.erase(Ops.begin());
1750 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001751 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001752 // If we have a multiply of zero, it will always be zero.
1753 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001754 } else if (Ops[0]->isAllOnesValue()) {
1755 // If we have a mul by -1 of an add, try distributing the -1 among the
1756 // add operands.
1757 if (Ops.size() == 2)
1758 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1759 SmallVector<const SCEV *, 4> NewOps;
1760 bool AnyFolded = false;
1761 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1762 I != E; ++I) {
1763 const SCEV *Mul = getMulExpr(Ops[0], *I);
1764 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1765 NewOps.push_back(Mul);
1766 }
1767 if (AnyFolded)
1768 return getAddExpr(NewOps);
1769 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001770 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001771
1772 if (Ops.size() == 1)
1773 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001774 }
1775
1776 // Skip over the add expression until we get to a multiply.
1777 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1778 ++Idx;
1779
Chris Lattner53e677a2004-04-02 20:23:17 +00001780 // If there are mul operands inline them all into this expression.
1781 if (Idx < Ops.size()) {
1782 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001783 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001784 // If we have an mul, expand the mul operands onto the end of the operands
1785 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001787 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001788 DeletedMul = true;
1789 }
1790
1791 // If we deleted at least one mul, we added operands to the end of the list,
1792 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001793 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001794 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001795 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001796 }
1797
1798 // If there are any add recurrences in the operands list, see if any other
1799 // added values are loop invariant. If so, we can fold them into the
1800 // recurrence.
1801 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1802 ++Idx;
1803
1804 // Scan over all recurrences, trying to fold loop invariants into them.
1805 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1806 // Scan all of the other operands to this mul and add them to the vector if
1807 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001808 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001809 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001810 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1811 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1812 LIOps.push_back(Ops[i]);
1813 Ops.erase(Ops.begin()+i);
1814 --i; --e;
1815 }
1816
1817 // If we found some loop invariants, fold them into the recurrence.
1818 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001819 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001820 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001821 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001822 const SCEV *Scale = getMulExpr(LIOps);
1823 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1824 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001825
Dan Gohmanb9f96512010-06-30 07:16:37 +00001826 // Build the new addrec. Propagate the NUW and NSW flags if both the
1827 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00001828 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1829 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001830 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001831
1832 // If all of the other operands were loop invariant, we are done.
1833 if (Ops.size() == 1) return NewRec;
1834
1835 // Otherwise, multiply the folded AddRec by the non-liv parts.
1836 for (unsigned i = 0;; ++i)
1837 if (Ops[i] == AddRec) {
1838 Ops[i] = NewRec;
1839 break;
1840 }
Dan Gohman246b2562007-10-22 18:31:58 +00001841 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001842 }
1843
1844 // Okay, if there weren't any loop invariants to be folded, check to see if
1845 // there are multiple AddRec's with the same loop induction variable being
1846 // multiplied together. If so, we can fold them.
1847 for (unsigned OtherIdx = Idx+1;
1848 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1849 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001850 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001851 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1852 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001853 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001854 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001855 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001856 const SCEV *B = F->getStepRecurrence(*this);
1857 const SCEV *D = G->getStepRecurrence(*this);
1858 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001859 getMulExpr(G, B),
1860 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001861 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001862 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001863 if (Ops.size() == 2) return NewAddRec;
1864
1865 Ops.erase(Ops.begin()+Idx);
1866 Ops.erase(Ops.begin()+OtherIdx-1);
1867 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001868 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001869 }
1870 }
1871
1872 // Otherwise couldn't fold anything into this recurrence. Move onto the
1873 // next one.
1874 }
1875
1876 // Okay, it looks like we really DO need an mul expr. Check to see if we
1877 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001878 FoldingSetNodeID ID;
1879 ID.AddInteger(scMulExpr);
1880 ID.AddInteger(Ops.size());
1881 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1882 ID.AddPointer(Ops[i]);
1883 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001884 SCEVMulExpr *S =
1885 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1886 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001887 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1888 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001889 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1890 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001891 UniqueSCEVs.InsertNode(S, IP);
1892 }
Dan Gohman3645b012009-10-09 00:10:36 +00001893 if (HasNUW) S->setHasNoUnsignedWrap(true);
1894 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001895 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001896}
1897
Andreas Bolka8a11c982009-08-07 22:55:26 +00001898/// getUDivExpr - Get a canonical unsigned division expression, or something
1899/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001900const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1901 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001902 assert(getEffectiveSCEVType(LHS->getType()) ==
1903 getEffectiveSCEVType(RHS->getType()) &&
1904 "SCEVUDivExpr operand types don't match!");
1905
Dan Gohman622ed672009-05-04 22:02:23 +00001906 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001907 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001908 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001909 // If the denominator is zero, the result of the udiv is undefined. Don't
1910 // try to analyze it, because the resolution chosen here may differ from
1911 // the resolution chosen in other parts of the compiler.
1912 if (!RHSC->getValue()->isZero()) {
1913 // Determine if the division can be folded into the operands of
1914 // its operands.
1915 // TODO: Generalize this to non-constants by using known-bits information.
1916 const Type *Ty = LHS->getType();
1917 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001918 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001919 // For non-power-of-two values, effectively round the value up to the
1920 // nearest power of two.
1921 if (!RHSC->getValue()->getValue().isPowerOf2())
1922 ++MaxShiftAmt;
1923 const IntegerType *ExtTy =
1924 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1925 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1926 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1927 if (const SCEVConstant *Step =
1928 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1929 if (!Step->getValue()->getValue()
1930 .urem(RHSC->getValue()->getValue()) &&
1931 getZeroExtendExpr(AR, ExtTy) ==
1932 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1933 getZeroExtendExpr(Step, ExtTy),
1934 AR->getLoop())) {
1935 SmallVector<const SCEV *, 4> Operands;
1936 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1937 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1938 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001939 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001940 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1941 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1942 SmallVector<const SCEV *, 4> Operands;
1943 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1944 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1945 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1946 // Find an operand that's safely divisible.
1947 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1948 const SCEV *Op = M->getOperand(i);
1949 const SCEV *Div = getUDivExpr(Op, RHSC);
1950 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1951 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1952 M->op_end());
1953 Operands[i] = Div;
1954 return getMulExpr(Operands);
1955 }
1956 }
Dan Gohman185cf032009-05-08 20:18:49 +00001957 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001958 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1959 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1960 SmallVector<const SCEV *, 4> Operands;
1961 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1962 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1963 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1964 Operands.clear();
1965 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1966 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1967 if (isa<SCEVUDivExpr>(Op) ||
1968 getMulExpr(Op, RHS) != A->getOperand(i))
1969 break;
1970 Operands.push_back(Op);
1971 }
1972 if (Operands.size() == A->getNumOperands())
1973 return getAddExpr(Operands);
1974 }
1975 }
Dan Gohman185cf032009-05-08 20:18:49 +00001976
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001977 // Fold if both operands are constant.
1978 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1979 Constant *LHSCV = LHSC->getValue();
1980 Constant *RHSCV = RHSC->getValue();
1981 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1982 RHSCV)));
1983 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001984 }
1985 }
1986
Dan Gohman1c343752009-06-27 21:21:31 +00001987 FoldingSetNodeID ID;
1988 ID.AddInteger(scUDivExpr);
1989 ID.AddPointer(LHS);
1990 ID.AddPointer(RHS);
1991 void *IP = 0;
1992 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001993 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1994 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001995 UniqueSCEVs.InsertNode(S, IP);
1996 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001997}
1998
1999
Dan Gohman6c0866c2009-05-24 23:45:28 +00002000/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2001/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002002const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00002003 const SCEV *Step, const Loop *L,
2004 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002005 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002006 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002007 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002008 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002009 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002010 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002011 }
2012
2013 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00002014 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002015}
2016
Dan Gohman6c0866c2009-05-24 23:45:28 +00002017/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2018/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002019const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002020ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00002021 const Loop *L,
2022 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002023 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002024#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002025 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002026 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002027 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002028 "SCEVAddRecExpr operand types don't match!");
2029#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002030
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002031 if (Operands.back()->isZero()) {
2032 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00002033 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002034 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002035
Dan Gohmanbc028532010-02-19 18:49:22 +00002036 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2037 // use that information to infer NUW and NSW flags. However, computing a
2038 // BE count requires calling getAddRecExpr, so we may not yet have a
2039 // meaningful BE count at this point (and if we don't, we'd be stuck
2040 // with a SCEVCouldNotCompute as the cached BE count).
2041
Dan Gohmana10756e2010-01-21 02:09:26 +00002042 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2043 if (!HasNUW && HasNSW) {
2044 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00002045 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2046 E = Operands.end(); I != E; ++I)
2047 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002048 All = false;
2049 break;
2050 }
2051 if (All) HasNUW = true;
2052 }
2053
Dan Gohmand9cc7492008-08-08 18:33:12 +00002054 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002055 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002056 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002057 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002058 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002059 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002060 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002061 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002062 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002063 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002064 // AddRecs require their operands be loop-invariant with respect to their
2065 // loops. Don't perform this transformation if it would break this
2066 // requirement.
2067 bool AllInvariant = true;
2068 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2069 if (!Operands[i]->isLoopInvariant(L)) {
2070 AllInvariant = false;
2071 break;
2072 }
2073 if (AllInvariant) {
2074 NestedOperands[0] = getAddRecExpr(Operands, L);
2075 AllInvariant = true;
2076 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2077 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2078 AllInvariant = false;
2079 break;
2080 }
2081 if (AllInvariant)
2082 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002083 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002084 }
2085 // Reset Operands to its original state.
2086 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002087 }
2088 }
2089
Dan Gohman67847532010-01-19 22:27:22 +00002090 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2091 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002092 FoldingSetNodeID ID;
2093 ID.AddInteger(scAddRecExpr);
2094 ID.AddInteger(Operands.size());
2095 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2096 ID.AddPointer(Operands[i]);
2097 ID.AddPointer(L);
2098 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002099 SCEVAddRecExpr *S =
2100 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2101 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002102 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2103 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002104 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2105 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002106 UniqueSCEVs.InsertNode(S, IP);
2107 }
Dan Gohman3645b012009-10-09 00:10:36 +00002108 if (HasNUW) S->setHasNoUnsignedWrap(true);
2109 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002110 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002111}
2112
Dan Gohman9311ef62009-06-24 14:49:00 +00002113const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2114 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002115 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002116 Ops.push_back(LHS);
2117 Ops.push_back(RHS);
2118 return getSMaxExpr(Ops);
2119}
2120
Dan Gohman0bba49c2009-07-07 17:06:11 +00002121const SCEV *
2122ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002123 assert(!Ops.empty() && "Cannot get empty smax!");
2124 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002125#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002126 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002127 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002128 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002129 "SCEVSMaxExpr operand types don't match!");
2130#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002131
2132 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002133 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002134
2135 // If there are any constants, fold them together.
2136 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002137 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002138 ++Idx;
2139 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002140 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002141 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002142 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002143 APIntOps::smax(LHSC->getValue()->getValue(),
2144 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002145 Ops[0] = getConstant(Fold);
2146 Ops.erase(Ops.begin()+1); // Erase the folded element
2147 if (Ops.size() == 1) return Ops[0];
2148 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002149 }
2150
Dan Gohmane5aceed2009-06-24 14:46:22 +00002151 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002152 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2153 Ops.erase(Ops.begin());
2154 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002155 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2156 // If we have an smax with a constant maximum-int, it will always be
2157 // maximum-int.
2158 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002159 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002160
Dan Gohman3ab13122010-04-13 16:49:23 +00002161 if (Ops.size() == 1) return Ops[0];
2162 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002163
2164 // Find the first SMax
2165 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2166 ++Idx;
2167
2168 // Check to see if one of the operands is an SMax. If so, expand its operands
2169 // onto our operand list, and recurse to simplify.
2170 if (Idx < Ops.size()) {
2171 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002172 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002173 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002174 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002175 DeletedSMax = true;
2176 }
2177
2178 if (DeletedSMax)
2179 return getSMaxExpr(Ops);
2180 }
2181
2182 // Okay, check to see if the same value occurs in the operand list twice. If
2183 // so, delete one. Since we sorted the list, these values are required to
2184 // be adjacent.
2185 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002186 // X smax Y smax Y --> X smax Y
2187 // X smax Y --> X, if X is always greater than Y
2188 if (Ops[i] == Ops[i+1] ||
2189 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2190 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2191 --i; --e;
2192 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002193 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2194 --i; --e;
2195 }
2196
2197 if (Ops.size() == 1) return Ops[0];
2198
2199 assert(!Ops.empty() && "Reduced smax down to nothing!");
2200
Nick Lewycky3e630762008-02-20 06:48:22 +00002201 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002202 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002203 FoldingSetNodeID ID;
2204 ID.AddInteger(scSMaxExpr);
2205 ID.AddInteger(Ops.size());
2206 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2207 ID.AddPointer(Ops[i]);
2208 void *IP = 0;
2209 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002210 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2211 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002212 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2213 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002214 UniqueSCEVs.InsertNode(S, IP);
2215 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002216}
2217
Dan Gohman9311ef62009-06-24 14:49:00 +00002218const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2219 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002220 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002221 Ops.push_back(LHS);
2222 Ops.push_back(RHS);
2223 return getUMaxExpr(Ops);
2224}
2225
Dan Gohman0bba49c2009-07-07 17:06:11 +00002226const SCEV *
2227ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002228 assert(!Ops.empty() && "Cannot get empty umax!");
2229 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002230#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002231 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002232 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002233 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002234 "SCEVUMaxExpr operand types don't match!");
2235#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002236
2237 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002238 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002239
2240 // If there are any constants, fold them together.
2241 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002242 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002243 ++Idx;
2244 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002245 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002246 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002247 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002248 APIntOps::umax(LHSC->getValue()->getValue(),
2249 RHSC->getValue()->getValue()));
2250 Ops[0] = getConstant(Fold);
2251 Ops.erase(Ops.begin()+1); // Erase the folded element
2252 if (Ops.size() == 1) return Ops[0];
2253 LHSC = cast<SCEVConstant>(Ops[0]);
2254 }
2255
Dan Gohmane5aceed2009-06-24 14:46:22 +00002256 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002257 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2258 Ops.erase(Ops.begin());
2259 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002260 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2261 // If we have an umax with a constant maximum-int, it will always be
2262 // maximum-int.
2263 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002264 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002265
Dan Gohman3ab13122010-04-13 16:49:23 +00002266 if (Ops.size() == 1) return Ops[0];
2267 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002268
2269 // Find the first UMax
2270 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2271 ++Idx;
2272
2273 // Check to see if one of the operands is a UMax. If so, expand its operands
2274 // onto our operand list, and recurse to simplify.
2275 if (Idx < Ops.size()) {
2276 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002277 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002278 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002279 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002280 DeletedUMax = true;
2281 }
2282
2283 if (DeletedUMax)
2284 return getUMaxExpr(Ops);
2285 }
2286
2287 // Okay, check to see if the same value occurs in the operand list twice. If
2288 // so, delete one. Since we sorted the list, these values are required to
2289 // be adjacent.
2290 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002291 // X umax Y umax Y --> X umax Y
2292 // X umax Y --> X, if X is always greater than Y
2293 if (Ops[i] == Ops[i+1] ||
2294 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2295 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2296 --i; --e;
2297 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002298 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2299 --i; --e;
2300 }
2301
2302 if (Ops.size() == 1) return Ops[0];
2303
2304 assert(!Ops.empty() && "Reduced umax down to nothing!");
2305
2306 // Okay, it looks like we really DO need a umax expr. Check to see if we
2307 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002308 FoldingSetNodeID ID;
2309 ID.AddInteger(scUMaxExpr);
2310 ID.AddInteger(Ops.size());
2311 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2312 ID.AddPointer(Ops[i]);
2313 void *IP = 0;
2314 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002315 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2316 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002317 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2318 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002319 UniqueSCEVs.InsertNode(S, IP);
2320 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002321}
2322
Dan Gohman9311ef62009-06-24 14:49:00 +00002323const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2324 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002325 // ~smax(~x, ~y) == smin(x, y).
2326 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2327}
2328
Dan Gohman9311ef62009-06-24 14:49:00 +00002329const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2330 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002331 // ~umax(~x, ~y) == umin(x, y)
2332 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2333}
2334
Dan Gohman4f8eea82010-02-01 18:27:38 +00002335const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002336 // If we have TargetData, we can bypass creating a target-independent
2337 // constant expression and then folding it back into a ConstantInt.
2338 // This is just a compile-time optimization.
2339 if (TD)
2340 return getConstant(TD->getIntPtrType(getContext()),
2341 TD->getTypeAllocSize(AllocTy));
2342
Dan Gohman4f8eea82010-02-01 18:27:38 +00002343 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2344 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002345 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2346 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002347 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2348 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2349}
2350
2351const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2352 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2353 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002354 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2355 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002356 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2357 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2358}
2359
2360const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2361 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002362 // If we have TargetData, we can bypass creating a target-independent
2363 // constant expression and then folding it back into a ConstantInt.
2364 // This is just a compile-time optimization.
2365 if (TD)
2366 return getConstant(TD->getIntPtrType(getContext()),
2367 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2368
Dan Gohman0f5efe52010-01-28 02:15:55 +00002369 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002371 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2372 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002373 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002374 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002375}
2376
Dan Gohman4f8eea82010-02-01 18:27:38 +00002377const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2378 Constant *FieldNo) {
2379 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002380 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002381 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2382 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002383 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002384 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002385}
2386
Dan Gohman0bba49c2009-07-07 17:06:11 +00002387const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002388 // Don't attempt to do anything other than create a SCEVUnknown object
2389 // here. createSCEV only calls getUnknown after checking for all other
2390 // interesting possibilities, and any other code that calls getUnknown
2391 // is doing so in order to hide a value from SCEV canonicalization.
2392
Dan Gohman1c343752009-06-27 21:21:31 +00002393 FoldingSetNodeID ID;
2394 ID.AddInteger(scUnknown);
2395 ID.AddPointer(V);
2396 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002397 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2398 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2399 "Stale SCEVUnknown in uniquing map!");
2400 return S;
2401 }
2402 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2403 FirstUnknown);
2404 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002405 UniqueSCEVs.InsertNode(S, IP);
2406 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002407}
2408
Chris Lattner53e677a2004-04-02 20:23:17 +00002409//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002410// Basic SCEV Analysis and PHI Idiom Recognition Code
2411//
2412
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002413/// isSCEVable - Test if values of the given type are analyzable within
2414/// the SCEV framework. This primarily includes integer types, and it
2415/// can optionally include pointer types if the ScalarEvolution class
2416/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002417bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002418 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002419 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002420}
2421
2422/// getTypeSizeInBits - Return the size in bits of the specified type,
2423/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002424uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002425 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2426
2427 // If we have a TargetData, use it!
2428 if (TD)
2429 return TD->getTypeSizeInBits(Ty);
2430
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002431 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002432 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002433 return Ty->getPrimitiveSizeInBits();
2434
2435 // The only other support type is pointer. Without TargetData, conservatively
2436 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002437 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002438 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002439}
2440
2441/// getEffectiveSCEVType - Return a type with the same bitwidth as
2442/// the given type and which represents how SCEV will treat the given
2443/// type, for which isSCEVable must return true. For pointer types,
2444/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002445const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002446 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2447
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002448 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002449 return Ty;
2450
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002451 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002452 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002453 if (TD) return TD->getIntPtrType(getContext());
2454
2455 // Without TargetData, conservatively assume pointers are 64-bit.
2456 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002457}
Chris Lattner53e677a2004-04-02 20:23:17 +00002458
Dan Gohman0bba49c2009-07-07 17:06:11 +00002459const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002460 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002461}
2462
Chris Lattner53e677a2004-04-02 20:23:17 +00002463/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2464/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002465const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002466 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002467
Dan Gohman8d9c7a62010-08-16 16:30:01 +00002468 std::map<SCEVCallbackVH, const SCEV *>::const_iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002469 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002470 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002471 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002472 return S;
2473}
2474
Dan Gohman2d1be872009-04-16 03:18:22 +00002475/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2476///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002477const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002478 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002479 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002480 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002481
2482 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002483 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002484 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002485 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002486}
2487
2488/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002489const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002490 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002491 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002492 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002493
2494 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002495 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002496 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002497 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002498 return getMinusSCEV(AllOnes, V);
2499}
2500
2501/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2502///
Dan Gohman9311ef62009-06-24 14:49:00 +00002503const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2504 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002505 // Fast path: X - X --> 0.
2506 if (LHS == RHS)
2507 return getConstant(LHS->getType(), 0);
2508
Dan Gohman2d1be872009-04-16 03:18:22 +00002509 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002510 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002511}
2512
2513/// getTruncateOrZeroExtend - 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.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002516const SCEV *
2517ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002518 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002519 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002520 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2521 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002522 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002523 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002524 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002525 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002526 return getTruncateExpr(V, Ty);
2527 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002528}
2529
2530/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2531/// input value to the specified type. If the type must be extended, it is sign
2532/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002533const SCEV *
2534ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002535 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002536 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002537 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2538 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002539 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002540 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002541 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002542 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002543 return getTruncateExpr(V, Ty);
2544 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002545}
2546
Dan Gohman467c4302009-05-13 03:46:30 +00002547/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2548/// input value to the specified type. If the type must be extended, it is zero
2549/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002550const SCEV *
2551ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002552 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002553 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2554 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002555 "Cannot noop or zero extend with non-integer arguments!");
2556 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2557 "getNoopOrZeroExtend cannot truncate!");
2558 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2559 return V; // No conversion
2560 return getZeroExtendExpr(V, Ty);
2561}
2562
2563/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2564/// input value to the specified type. If the type must be extended, it is sign
2565/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002566const SCEV *
2567ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002568 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002569 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2570 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002571 "Cannot noop or sign extend with non-integer arguments!");
2572 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2573 "getNoopOrSignExtend cannot truncate!");
2574 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2575 return V; // No conversion
2576 return getSignExtendExpr(V, Ty);
2577}
2578
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002579/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2580/// the input value to the specified type. If the type must be extended,
2581/// it is extended with unspecified bits. The conversion must not be
2582/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002583const SCEV *
2584ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002585 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002586 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2587 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002588 "Cannot noop or any extend with non-integer arguments!");
2589 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2590 "getNoopOrAnyExtend cannot truncate!");
2591 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2592 return V; // No conversion
2593 return getAnyExtendExpr(V, Ty);
2594}
2595
Dan Gohman467c4302009-05-13 03:46:30 +00002596/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2597/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002598const SCEV *
2599ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002600 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002601 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2602 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002603 "Cannot truncate or noop with non-integer arguments!");
2604 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2605 "getTruncateOrNoop cannot extend!");
2606 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2607 return V; // No conversion
2608 return getTruncateExpr(V, Ty);
2609}
2610
Dan Gohmana334aa72009-06-22 00:31:57 +00002611/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2612/// the types using zero-extension, and then perform a umax operation
2613/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002614const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2615 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002616 const SCEV *PromotedLHS = LHS;
2617 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002618
2619 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2620 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2621 else
2622 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2623
2624 return getUMaxExpr(PromotedLHS, PromotedRHS);
2625}
2626
Dan Gohmanc9759e82009-06-22 15:03:27 +00002627/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2628/// the types using zero-extension, and then perform a umin operation
2629/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002630const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2631 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002632 const SCEV *PromotedLHS = LHS;
2633 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002634
2635 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2636 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2637 else
2638 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2639
2640 return getUMinExpr(PromotedLHS, PromotedRHS);
2641}
2642
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002643/// PushDefUseChildren - Push users of the given Instruction
2644/// onto the given Worklist.
2645static void
2646PushDefUseChildren(Instruction *I,
2647 SmallVectorImpl<Instruction *> &Worklist) {
2648 // Push the def-use children onto the Worklist stack.
2649 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2650 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002651 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002652}
2653
2654/// ForgetSymbolicValue - This looks up computed SCEV values for all
2655/// instructions that depend on the given instruction and removes them from
2656/// the Scalars map if they reference SymName. This is used during PHI
2657/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002658void
Dan Gohman85669632010-02-25 06:57:05 +00002659ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002660 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002661 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002662
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002663 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002664 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002665 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002666 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002667 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002668
Dan Gohman5d984912009-12-18 01:14:11 +00002669 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002670 Scalars.find(static_cast<Value *>(I));
2671 if (It != Scalars.end()) {
2672 // Short-circuit the def-use traversal if the symbolic name
2673 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002674 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002675 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002676
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002677 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002678 // structure, it's a PHI that's in the progress of being computed
2679 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2680 // additional loop trip count information isn't going to change anything.
2681 // In the second case, createNodeForPHI will perform the necessary
2682 // updates on its own when it gets to that point. In the third, we do
2683 // want to forget the SCEVUnknown.
2684 if (!isa<PHINode>(I) ||
2685 !isa<SCEVUnknown>(It->second) ||
2686 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002687 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002688 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002689 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002690 }
2691
2692 PushDefUseChildren(I, Worklist);
2693 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002694}
Chris Lattner53e677a2004-04-02 20:23:17 +00002695
2696/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2697/// a loop header, making it a potential recurrence, or it doesn't.
2698///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002699const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002700 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2701 if (L->getHeader() == PN->getParent()) {
2702 // The loop may have multiple entrances or multiple exits; we can analyze
2703 // this phi as an addrec if it has a unique entry value and a unique
2704 // backedge value.
2705 Value *BEValueV = 0, *StartValueV = 0;
2706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2707 Value *V = PN->getIncomingValue(i);
2708 if (L->contains(PN->getIncomingBlock(i))) {
2709 if (!BEValueV) {
2710 BEValueV = V;
2711 } else if (BEValueV != V) {
2712 BEValueV = 0;
2713 break;
2714 }
2715 } else if (!StartValueV) {
2716 StartValueV = V;
2717 } else if (StartValueV != V) {
2718 StartValueV = 0;
2719 break;
2720 }
2721 }
2722 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002723 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002724 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002725 assert(Scalars.find(PN) == Scalars.end() &&
2726 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002727 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002728
2729 // Using this symbolic name for the PHI, analyze the value coming around
2730 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002731 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002732
2733 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2734 // has a special value for the first iteration of the loop.
2735
2736 // If the value coming around the backedge is an add with the symbolic
2737 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002738 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002739 // If there is a single occurrence of the symbolic value, replace it
2740 // with a recurrence.
2741 unsigned FoundIndex = Add->getNumOperands();
2742 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2743 if (Add->getOperand(i) == SymbolicName)
2744 if (FoundIndex == e) {
2745 FoundIndex = i;
2746 break;
2747 }
2748
2749 if (FoundIndex != Add->getNumOperands()) {
2750 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002751 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002752 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2753 if (i != FoundIndex)
2754 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002755 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002756
2757 // This is not a valid addrec if the step amount is varying each
2758 // loop iteration, but is not itself an addrec in this loop.
2759 if (Accum->isLoopInvariant(L) ||
2760 (isa<SCEVAddRecExpr>(Accum) &&
2761 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002762 bool HasNUW = false;
2763 bool HasNSW = false;
2764
2765 // If the increment doesn't overflow, then neither the addrec nor
2766 // the post-increment will overflow.
2767 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2768 if (OBO->hasNoUnsignedWrap())
2769 HasNUW = true;
2770 if (OBO->hasNoSignedWrap())
2771 HasNSW = true;
2772 }
2773
Dan Gohman27dead42010-04-12 07:49:36 +00002774 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002775 const SCEV *PHISCEV =
2776 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002777
Dan Gohmana10756e2010-01-21 02:09:26 +00002778 // Since the no-wrap flags are on the increment, they apply to the
2779 // post-incremented value as well.
2780 if (Accum->isLoopInvariant(L))
2781 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2782 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002783
2784 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002785 // to be symbolic. We now need to go back and purge all of the
2786 // entries for the scalars that use the symbolic expression.
2787 ForgetSymbolicName(PN, SymbolicName);
2788 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002789 return PHISCEV;
2790 }
2791 }
Dan Gohman622ed672009-05-04 22:02:23 +00002792 } else if (const SCEVAddRecExpr *AddRec =
2793 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002794 // Otherwise, this could be a loop like this:
2795 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2796 // In this case, j = {1,+,1} and BEValue is j.
2797 // Because the other in-value of i (0) fits the evolution of BEValue
2798 // i really is an addrec evolution.
2799 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002800 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002801
2802 // If StartVal = j.start - j.stride, we can use StartVal as the
2803 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002804 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002805 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002806 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002807 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002808
2809 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002810 // to be symbolic. We now need to go back and purge all of the
2811 // entries for the scalars that use the symbolic expression.
2812 ForgetSymbolicName(PN, SymbolicName);
2813 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002814 return PHISCEV;
2815 }
2816 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002817 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002818 }
Dan Gohman27dead42010-04-12 07:49:36 +00002819 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002820
Dan Gohman85669632010-02-25 06:57:05 +00002821 // If the PHI has a single incoming value, follow that value, unless the
2822 // PHI's incoming blocks are in a different loop, in which case doing so
2823 // risks breaking LCSSA form. Instcombine would normally zap these, but
2824 // it doesn't have DominatorTree information, so it may miss cases.
2825 if (Value *V = PN->hasConstantValue(DT)) {
2826 bool AllSameLoop = true;
2827 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2828 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2829 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2830 AllSameLoop = false;
2831 break;
2832 }
2833 if (AllSameLoop)
2834 return getSCEV(V);
2835 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002836
Chris Lattner53e677a2004-04-02 20:23:17 +00002837 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002838 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002839}
2840
Dan Gohman26466c02009-05-08 20:26:55 +00002841/// createNodeForGEP - Expand GEP instructions into add and multiply
2842/// operations. This allows them to be analyzed by regular SCEV code.
2843///
Dan Gohmand281ed22009-12-18 02:09:29 +00002844const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002845
Dan Gohmanb9f96512010-06-30 07:16:37 +00002846 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2847 // Add expression, because the Instruction may be guarded by control flow
2848 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002849 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002850
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002851 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002852 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002853 // Don't attempt to analyze GEPs over unsized objects.
2854 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2855 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002856 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002857 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002858 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002859 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002860 I != E; ++I) {
2861 Value *Index = *I;
2862 // Compute the (potentially symbolic) offset in bytes for this index.
2863 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2864 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002865 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002866 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2867
Dan Gohmanb9f96512010-06-30 07:16:37 +00002868 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002869 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002870 } else {
2871 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002872 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2873 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002874 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002875 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2876
Dan Gohmanb9f96512010-06-30 07:16:37 +00002877 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002878 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002879
2880 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002881 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002882 }
2883 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002884
2885 // Get the SCEV for the GEP base.
2886 const SCEV *BaseS = getSCEV(Base);
2887
Dan Gohmanb9f96512010-06-30 07:16:37 +00002888 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002889 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002890}
2891
Nick Lewycky83bb0052007-11-22 07:59:40 +00002892/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2893/// guaranteed to end in (at every loop iteration). It is, at the same time,
2894/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2895/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002896uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002897ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002898 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002899 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002900
Dan Gohman622ed672009-05-04 22:02:23 +00002901 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002902 return std::min(GetMinTrailingZeros(T->getOperand()),
2903 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002904
Dan Gohman622ed672009-05-04 22:02:23 +00002905 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002906 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2907 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2908 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002909 }
2910
Dan Gohman622ed672009-05-04 22:02:23 +00002911 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002912 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2913 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2914 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002915 }
2916
Dan Gohman622ed672009-05-04 22:02:23 +00002917 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002918 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002919 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002920 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002921 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002922 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002923 }
2924
Dan Gohman622ed672009-05-04 22:02:23 +00002925 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002926 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002927 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2928 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002929 for (unsigned i = 1, e = M->getNumOperands();
2930 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002931 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002932 BitWidth);
2933 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002934 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002935
Dan Gohman622ed672009-05-04 22:02:23 +00002936 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002937 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002938 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002939 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002940 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002941 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002942 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002943
Dan Gohman622ed672009-05-04 22:02:23 +00002944 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002945 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002947 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002948 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002949 return MinOpRes;
2950 }
2951
Dan Gohman622ed672009-05-04 22:02:23 +00002952 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002953 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002954 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002955 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002956 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002957 return MinOpRes;
2958 }
2959
Dan Gohman2c364ad2009-06-19 23:29:04 +00002960 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2961 // For a SCEVUnknown, ask ValueTracking.
2962 unsigned BitWidth = getTypeSizeInBits(U->getType());
2963 APInt Mask = APInt::getAllOnesValue(BitWidth);
2964 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2965 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2966 return Zeros.countTrailingOnes();
2967 }
2968
2969 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002970 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002971}
Chris Lattner53e677a2004-04-02 20:23:17 +00002972
Dan Gohman85b05a22009-07-13 21:35:55 +00002973/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2974///
2975ConstantRange
2976ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002977
2978 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002979 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002980
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002981 unsigned BitWidth = getTypeSizeInBits(S->getType());
2982 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2983
2984 // If the value has known zeros, the maximum unsigned value will have those
2985 // known zeros as well.
2986 uint32_t TZ = GetMinTrailingZeros(S);
2987 if (TZ != 0)
2988 ConservativeResult =
2989 ConstantRange(APInt::getMinValue(BitWidth),
2990 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2991
Dan Gohman85b05a22009-07-13 21:35:55 +00002992 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2994 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2995 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002996 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002997 }
2998
2999 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3000 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3001 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3002 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003003 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003004 }
3005
3006 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3007 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3008 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3009 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003010 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003011 }
3012
3013 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3014 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3015 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3016 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003017 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003018 }
3019
3020 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3021 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3022 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003023 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003024 }
3025
3026 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3027 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003028 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003029 }
3030
3031 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3032 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003033 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003034 }
3035
3036 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3037 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003038 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003039 }
3040
Dan Gohman85b05a22009-07-13 21:35:55 +00003041 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003042 // If there's no unsigned wrap, the value will never be less than its
3043 // initial value.
3044 if (AddRec->hasNoUnsignedWrap())
3045 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003046 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003047 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003048 ConservativeResult.intersectWith(
3049 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003050
3051 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003052 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003053 const Type *Ty = AddRec->getType();
3054 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003055 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3056 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003057 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3058
3059 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003060 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003061
3062 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003063 ConstantRange StepRange = getSignedRange(Step);
3064 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3065 ConstantRange EndRange =
3066 StartRange.add(MaxBECountRange.multiply(StepRange));
3067
3068 // Check for overflow. This must be done with ConstantRange arithmetic
3069 // because we could be called from within the ScalarEvolution overflow
3070 // checking code.
3071 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3072 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3073 ConstantRange ExtMaxBECountRange =
3074 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3075 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3076 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3077 ExtEndRange)
3078 return ConservativeResult;
3079
Dan Gohman85b05a22009-07-13 21:35:55 +00003080 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3081 EndRange.getUnsignedMin());
3082 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3083 EndRange.getUnsignedMax());
3084 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003085 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003086 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00003087 }
3088 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003089
3090 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003091 }
3092
3093 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3094 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003095 APInt Mask = APInt::getAllOnesValue(BitWidth);
3096 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3097 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003098 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003099 return ConservativeResult;
3100 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003101 }
3102
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003103 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003104}
3105
Dan Gohman85b05a22009-07-13 21:35:55 +00003106/// getSignedRange - Determine the signed range for a particular SCEV.
3107///
3108ConstantRange
3109ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003110
Dan Gohman85b05a22009-07-13 21:35:55 +00003111 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3112 return ConstantRange(C->getValue()->getValue());
3113
Dan Gohman52fddd32010-01-26 04:40:18 +00003114 unsigned BitWidth = getTypeSizeInBits(S->getType());
3115 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3116
3117 // If the value has known zeros, the maximum signed value will have those
3118 // known zeros as well.
3119 uint32_t TZ = GetMinTrailingZeros(S);
3120 if (TZ != 0)
3121 ConservativeResult =
3122 ConstantRange(APInt::getSignedMinValue(BitWidth),
3123 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3124
Dan Gohman85b05a22009-07-13 21:35:55 +00003125 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3126 ConstantRange X = getSignedRange(Add->getOperand(0));
3127 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3128 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003129 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003130 }
3131
Dan Gohman85b05a22009-07-13 21:35:55 +00003132 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3133 ConstantRange X = getSignedRange(Mul->getOperand(0));
3134 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3135 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003136 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003137 }
3138
Dan Gohman85b05a22009-07-13 21:35:55 +00003139 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3140 ConstantRange X = getSignedRange(SMax->getOperand(0));
3141 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3142 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003143 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003144 }
Dan Gohman62849c02009-06-24 01:05:09 +00003145
Dan Gohman85b05a22009-07-13 21:35:55 +00003146 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3147 ConstantRange X = getSignedRange(UMax->getOperand(0));
3148 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3149 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003150 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003151 }
Dan Gohman62849c02009-06-24 01:05:09 +00003152
Dan Gohman85b05a22009-07-13 21:35:55 +00003153 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3154 ConstantRange X = getSignedRange(UDiv->getLHS());
3155 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003156 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003157 }
Dan Gohman62849c02009-06-24 01:05:09 +00003158
Dan Gohman85b05a22009-07-13 21:35:55 +00003159 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3160 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003161 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003162 }
3163
3164 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3165 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003166 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003167 }
3168
3169 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3170 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003171 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003172 }
3173
Dan Gohman85b05a22009-07-13 21:35:55 +00003174 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003175 // If there's no signed wrap, and all the operands have the same sign or
3176 // zero, the value won't ever change sign.
3177 if (AddRec->hasNoSignedWrap()) {
3178 bool AllNonNeg = true;
3179 bool AllNonPos = true;
3180 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3181 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3182 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3183 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003184 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003185 ConservativeResult = ConservativeResult.intersectWith(
3186 ConstantRange(APInt(BitWidth, 0),
3187 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003188 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003189 ConservativeResult = ConservativeResult.intersectWith(
3190 ConstantRange(APInt::getSignedMinValue(BitWidth),
3191 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003192 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003193
3194 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003195 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003196 const Type *Ty = AddRec->getType();
3197 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003198 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3199 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003200 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3201
3202 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003203 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003204
3205 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003206 ConstantRange StepRange = getSignedRange(Step);
3207 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3208 ConstantRange EndRange =
3209 StartRange.add(MaxBECountRange.multiply(StepRange));
3210
3211 // Check for overflow. This must be done with ConstantRange arithmetic
3212 // because we could be called from within the ScalarEvolution overflow
3213 // checking code.
3214 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3215 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3216 ConstantRange ExtMaxBECountRange =
3217 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3218 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3219 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3220 ExtEndRange)
3221 return ConservativeResult;
3222
Dan Gohman85b05a22009-07-13 21:35:55 +00003223 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3224 EndRange.getSignedMin());
3225 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3226 EndRange.getSignedMax());
3227 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003228 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003229 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003230 }
Dan Gohman62849c02009-06-24 01:05:09 +00003231 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003232
3233 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003234 }
3235
Dan Gohman2c364ad2009-06-19 23:29:04 +00003236 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3237 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003238 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003239 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003240 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3241 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003242 return ConservativeResult;
3243 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003244 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003245 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003246 }
3247
Dan Gohman52fddd32010-01-26 04:40:18 +00003248 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003249}
3250
Chris Lattner53e677a2004-04-02 20:23:17 +00003251/// createSCEV - We know that there is no SCEV for the specified value.
3252/// Analyze the expression.
3253///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003254const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003255 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003256 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003257
Dan Gohman6c459a22008-06-22 19:56:46 +00003258 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003259 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003260 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003261
3262 // Don't attempt to analyze instructions in blocks that aren't
3263 // reachable. Such instructions don't matter, and they aren't required
3264 // to obey basic rules for definitions dominating uses which this
3265 // analysis depends on.
3266 if (!DT->isReachableFromEntry(I->getParent()))
3267 return getUnknown(V);
3268 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003269 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003270 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3271 return getConstant(CI);
3272 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003273 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003274 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3275 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003276 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003277 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003278
Dan Gohmanca178902009-07-17 20:47:02 +00003279 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003280 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003281 case Instruction::Add: {
3282 // The simple thing to do would be to just call getSCEV on both operands
3283 // and call getAddExpr with the result. However if we're looking at a
3284 // bunch of things all added together, this can be quite inefficient,
3285 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3286 // Instead, gather up all the operands and make a single getAddExpr call.
3287 // LLVM IR canonical form means we need only traverse the left operands.
3288 SmallVector<const SCEV *, 4> AddOps;
3289 AddOps.push_back(getSCEV(U->getOperand(1)));
3290 for (Value *Op = U->getOperand(0);
3291 Op->getValueID() == Instruction::Add + Value::InstructionVal;
3292 Op = U->getOperand(0)) {
3293 U = cast<Operator>(Op);
3294 AddOps.push_back(getSCEV(U->getOperand(1)));
3295 }
3296 AddOps.push_back(getSCEV(U->getOperand(0)));
3297 return getAddExpr(AddOps);
3298 }
3299 case Instruction::Mul: {
3300 // See the Add code above.
3301 SmallVector<const SCEV *, 4> MulOps;
3302 MulOps.push_back(getSCEV(U->getOperand(1)));
3303 for (Value *Op = U->getOperand(0);
3304 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3305 Op = U->getOperand(0)) {
3306 U = cast<Operator>(Op);
3307 MulOps.push_back(getSCEV(U->getOperand(1)));
3308 }
3309 MulOps.push_back(getSCEV(U->getOperand(0)));
3310 return getMulExpr(MulOps);
3311 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003312 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003313 return getUDivExpr(getSCEV(U->getOperand(0)),
3314 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003315 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003316 return getMinusSCEV(getSCEV(U->getOperand(0)),
3317 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003318 case Instruction::And:
3319 // For an expression like x&255 that merely masks off the high bits,
3320 // use zext(trunc(x)) as the SCEV expression.
3321 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003322 if (CI->isNullValue())
3323 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003324 if (CI->isAllOnesValue())
3325 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003326 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003327
3328 // Instcombine's ShrinkDemandedConstant may strip bits out of
3329 // constants, obscuring what would otherwise be a low-bits mask.
3330 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3331 // knew about to reconstruct a low-bits mask value.
3332 unsigned LZ = A.countLeadingZeros();
3333 unsigned BitWidth = A.getBitWidth();
3334 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3335 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3336 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3337
3338 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3339
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003340 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003341 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003342 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003343 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003344 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003345 }
3346 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003347
Dan Gohman6c459a22008-06-22 19:56:46 +00003348 case Instruction::Or:
3349 // If the RHS of the Or is a constant, we may have something like:
3350 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3351 // optimizations will transparently handle this case.
3352 //
3353 // In order for this transformation to be safe, the LHS must be of the
3354 // form X*(2^n) and the Or constant must be less than 2^n.
3355 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003356 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003357 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003358 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003359 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3360 // Build a plain add SCEV.
3361 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3362 // If the LHS of the add was an addrec and it has no-wrap flags,
3363 // transfer the no-wrap flags, since an or won't introduce a wrap.
3364 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3365 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3366 if (OldAR->hasNoUnsignedWrap())
3367 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3368 if (OldAR->hasNoSignedWrap())
3369 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3370 }
3371 return S;
3372 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003373 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003374 break;
3375 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003376 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003377 // If the RHS of the xor is a signbit, then this is just an add.
3378 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003379 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003380 return getAddExpr(getSCEV(U->getOperand(0)),
3381 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003382
3383 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003384 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003385 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003386
3387 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3388 // This is a variant of the check for xor with -1, and it handles
3389 // the case where instcombine has trimmed non-demanded bits out
3390 // of an xor with -1.
3391 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3392 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3393 if (BO->getOpcode() == Instruction::And &&
3394 LCI->getValue() == CI->getValue())
3395 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003396 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003397 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003398 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003399 const Type *Z0Ty = Z0->getType();
3400 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3401
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003402 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003403 // mask off the high bits. Complement the operand and
3404 // re-apply the zext.
3405 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3406 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3407
3408 // If C is a single bit, it may be in the sign-bit position
3409 // before the zero-extend. In this case, represent the xor
3410 // using an add, which is equivalent, and re-apply the zext.
3411 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3412 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3413 Trunc.isSignBit())
3414 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3415 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003416 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003417 }
3418 break;
3419
3420 case Instruction::Shl:
3421 // Turn shift left of a constant amount into a multiply.
3422 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003423 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003424
3425 // If the shift count is not less than the bitwidth, the result of
3426 // the shift is undefined. Don't try to analyze it, because the
3427 // resolution chosen here may differ from the resolution chosen in
3428 // other parts of the compiler.
3429 if (SA->getValue().uge(BitWidth))
3430 break;
3431
Owen Andersoneed707b2009-07-24 23:12:02 +00003432 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003433 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003434 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003435 }
3436 break;
3437
Nick Lewycky01eaf802008-07-07 06:15:49 +00003438 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003439 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003440 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003441 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003442
3443 // If the shift count is not less than the bitwidth, the result of
3444 // the shift is undefined. Don't try to analyze it, because the
3445 // resolution chosen here may differ from the resolution chosen in
3446 // other parts of the compiler.
3447 if (SA->getValue().uge(BitWidth))
3448 break;
3449
Owen Andersoneed707b2009-07-24 23:12:02 +00003450 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003451 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003452 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003453 }
3454 break;
3455
Dan Gohman4ee29af2009-04-21 02:26:00 +00003456 case Instruction::AShr:
3457 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3458 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003459 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003460 if (L->getOpcode() == Instruction::Shl &&
3461 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003462 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3463
3464 // If the shift count is not less than the bitwidth, the result of
3465 // the shift is undefined. Don't try to analyze it, because the
3466 // resolution chosen here may differ from the resolution chosen in
3467 // other parts of the compiler.
3468 if (CI->getValue().uge(BitWidth))
3469 break;
3470
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003471 uint64_t Amt = BitWidth - CI->getZExtValue();
3472 if (Amt == BitWidth)
3473 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003474 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003475 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003476 IntegerType::get(getContext(),
3477 Amt)),
3478 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003479 }
3480 break;
3481
Dan Gohman6c459a22008-06-22 19:56:46 +00003482 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003483 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003484
3485 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003486 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003487
3488 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003489 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003490
3491 case Instruction::BitCast:
3492 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003493 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003494 return getSCEV(U->getOperand(0));
3495 break;
3496
Dan Gohman4f8eea82010-02-01 18:27:38 +00003497 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3498 // lead to pointer expressions which cannot safely be expanded to GEPs,
3499 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3500 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003501
Dan Gohman26466c02009-05-08 20:26:55 +00003502 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003503 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003504
Dan Gohman6c459a22008-06-22 19:56:46 +00003505 case Instruction::PHI:
3506 return createNodeForPHI(cast<PHINode>(U));
3507
3508 case Instruction::Select:
3509 // This could be a smax or umax that was lowered earlier.
3510 // Try to recover it.
3511 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3512 Value *LHS = ICI->getOperand(0);
3513 Value *RHS = ICI->getOperand(1);
3514 switch (ICI->getPredicate()) {
3515 case ICmpInst::ICMP_SLT:
3516 case ICmpInst::ICMP_SLE:
3517 std::swap(LHS, RHS);
3518 // fall through
3519 case ICmpInst::ICMP_SGT:
3520 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003521 // a >s b ? a+x : b+x -> smax(a, b)+x
3522 // a >s b ? b+x : a+x -> smin(a, b)+x
3523 if (LHS->getType() == U->getType()) {
3524 const SCEV *LS = getSCEV(LHS);
3525 const SCEV *RS = getSCEV(RHS);
3526 const SCEV *LA = getSCEV(U->getOperand(1));
3527 const SCEV *RA = getSCEV(U->getOperand(2));
3528 const SCEV *LDiff = getMinusSCEV(LA, LS);
3529 const SCEV *RDiff = getMinusSCEV(RA, RS);
3530 if (LDiff == RDiff)
3531 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3532 LDiff = getMinusSCEV(LA, RS);
3533 RDiff = getMinusSCEV(RA, LS);
3534 if (LDiff == RDiff)
3535 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3536 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003537 break;
3538 case ICmpInst::ICMP_ULT:
3539 case ICmpInst::ICMP_ULE:
3540 std::swap(LHS, RHS);
3541 // fall through
3542 case ICmpInst::ICMP_UGT:
3543 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003544 // a >u b ? a+x : b+x -> umax(a, b)+x
3545 // a >u b ? b+x : a+x -> umin(a, b)+x
3546 if (LHS->getType() == U->getType()) {
3547 const SCEV *LS = getSCEV(LHS);
3548 const SCEV *RS = getSCEV(RHS);
3549 const SCEV *LA = getSCEV(U->getOperand(1));
3550 const SCEV *RA = getSCEV(U->getOperand(2));
3551 const SCEV *LDiff = getMinusSCEV(LA, LS);
3552 const SCEV *RDiff = getMinusSCEV(RA, RS);
3553 if (LDiff == RDiff)
3554 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3555 LDiff = getMinusSCEV(LA, RS);
3556 RDiff = getMinusSCEV(RA, LS);
3557 if (LDiff == RDiff)
3558 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3559 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003560 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003561 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003562 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3563 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003564 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003565 cast<ConstantInt>(RHS)->isZero()) {
3566 const SCEV *One = getConstant(LHS->getType(), 1);
3567 const SCEV *LS = getSCEV(LHS);
3568 const SCEV *LA = getSCEV(U->getOperand(1));
3569 const SCEV *RA = getSCEV(U->getOperand(2));
3570 const SCEV *LDiff = getMinusSCEV(LA, LS);
3571 const SCEV *RDiff = getMinusSCEV(RA, One);
3572 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003573 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003574 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003575 break;
3576 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003577 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3578 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003579 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003580 cast<ConstantInt>(RHS)->isZero()) {
3581 const SCEV *One = getConstant(LHS->getType(), 1);
3582 const SCEV *LS = getSCEV(LHS);
3583 const SCEV *LA = getSCEV(U->getOperand(1));
3584 const SCEV *RA = getSCEV(U->getOperand(2));
3585 const SCEV *LDiff = getMinusSCEV(LA, One);
3586 const SCEV *RDiff = getMinusSCEV(RA, LS);
3587 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003588 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003589 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003590 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003591 default:
3592 break;
3593 }
3594 }
3595
3596 default: // We cannot analyze this expression.
3597 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003598 }
3599
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003600 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003601}
3602
3603
3604
3605//===----------------------------------------------------------------------===//
3606// Iteration Count Computation Code
3607//
3608
Dan Gohman46bdfb02009-02-24 18:55:53 +00003609/// getBackedgeTakenCount - If the specified loop has a predictable
3610/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3611/// object. The backedge-taken count is the number of times the loop header
3612/// will be branched to from within the loop. This is one less than the
3613/// trip count of the loop, since it doesn't count the first iteration,
3614/// when the header is branched to from outside the loop.
3615///
3616/// Note that it is not valid to call this method on a loop without a
3617/// loop-invariant backedge-taken count (see
3618/// hasLoopInvariantBackedgeTakenCount).
3619///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003620const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003621 return getBackedgeTakenInfo(L).Exact;
3622}
3623
3624/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3625/// return the least SCEV value that is known never to be less than the
3626/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003627const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003628 return getBackedgeTakenInfo(L).Max;
3629}
3630
Dan Gohman59ae6b92009-07-08 19:23:34 +00003631/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3632/// onto the given Worklist.
3633static void
3634PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3635 BasicBlock *Header = L->getHeader();
3636
3637 // Push all Loop-header PHIs onto the Worklist stack.
3638 for (BasicBlock::iterator I = Header->begin();
3639 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3640 Worklist.push_back(PN);
3641}
3642
Dan Gohmana1af7572009-04-30 20:47:05 +00003643const ScalarEvolution::BackedgeTakenInfo &
3644ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003645 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003646 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003647 // update the value. The temporary CouldNotCompute value tells SCEV
3648 // code elsewhere that it shouldn't attempt to request a new
3649 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003650 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003651 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3652 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003653 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3654 if (BECount.Exact != getCouldNotCompute()) {
3655 assert(BECount.Exact->isLoopInvariant(L) &&
3656 BECount.Max->isLoopInvariant(L) &&
3657 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003658 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003659
Dan Gohman01ecca22009-04-27 20:16:15 +00003660 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003661 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003662 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003663 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003664 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003665 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003666 if (isa<PHINode>(L->getHeader()->begin()))
3667 // Only count loops that have phi nodes as not being computable.
3668 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003669 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003670
3671 // Now that we know more about the trip count for this loop, forget any
3672 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003673 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003674 // information. This is similar to the code in forgetLoop, except that
3675 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003676 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003677 SmallVector<Instruction *, 16> Worklist;
3678 PushLoopPHIs(L, Worklist);
3679
3680 SmallPtrSet<Instruction *, 8> Visited;
3681 while (!Worklist.empty()) {
3682 Instruction *I = Worklist.pop_back_val();
3683 if (!Visited.insert(I)) continue;
3684
Dan Gohman5d984912009-12-18 01:14:11 +00003685 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003686 Scalars.find(static_cast<Value *>(I));
3687 if (It != Scalars.end()) {
3688 // SCEVUnknown for a PHI either means that it has an unrecognized
3689 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003690 // by createNodeForPHI. In the former case, additional loop trip
3691 // count information isn't going to change anything. In the later
3692 // case, createNodeForPHI will perform the necessary updates on its
3693 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003694 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3695 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003696 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003697 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003698 if (PHINode *PN = dyn_cast<PHINode>(I))
3699 ConstantEvolutionLoopExitValue.erase(PN);
3700 }
3701
3702 PushDefUseChildren(I, Worklist);
3703 }
3704 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003705 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003706 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003707}
3708
Dan Gohman4c7279a2009-10-31 15:04:55 +00003709/// forgetLoop - This method should be called by the client when it has
3710/// changed a loop in a way that may effect ScalarEvolution's ability to
3711/// compute a trip count, or if the loop is deleted.
3712void ScalarEvolution::forgetLoop(const Loop *L) {
3713 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003714 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003715
Dan Gohman4c7279a2009-10-31 15:04:55 +00003716 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003717 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003718 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003719
Dan Gohman59ae6b92009-07-08 19:23:34 +00003720 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003721 while (!Worklist.empty()) {
3722 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003723 if (!Visited.insert(I)) continue;
3724
Dan Gohman5d984912009-12-18 01:14:11 +00003725 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003726 Scalars.find(static_cast<Value *>(I));
3727 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003728 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003729 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003730 if (PHINode *PN = dyn_cast<PHINode>(I))
3731 ConstantEvolutionLoopExitValue.erase(PN);
3732 }
3733
3734 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003735 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003736}
3737
Eric Christophere6cbfa62010-07-29 01:25:38 +00003738/// forgetValue - This method should be called by the client when it has
3739/// changed a value in a way that may effect its value, or which may
3740/// disconnect it from a def-use chain linking it to a loop.
3741void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003742 Instruction *I = dyn_cast<Instruction>(V);
3743 if (!I) return;
3744
3745 // Drop information about expressions based on loop-header PHIs.
3746 SmallVector<Instruction *, 16> Worklist;
3747 Worklist.push_back(I);
3748
3749 SmallPtrSet<Instruction *, 8> Visited;
3750 while (!Worklist.empty()) {
3751 I = Worklist.pop_back_val();
3752 if (!Visited.insert(I)) continue;
3753
3754 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3755 Scalars.find(static_cast<Value *>(I));
3756 if (It != Scalars.end()) {
3757 ValuesAtScopes.erase(It->second);
3758 Scalars.erase(It);
3759 if (PHINode *PN = dyn_cast<PHINode>(I))
3760 ConstantEvolutionLoopExitValue.erase(PN);
3761 }
3762
3763 PushDefUseChildren(I, Worklist);
3764 }
3765}
3766
Dan Gohman46bdfb02009-02-24 18:55:53 +00003767/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3768/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003769ScalarEvolution::BackedgeTakenInfo
3770ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003771 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003772 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003773
Dan Gohmana334aa72009-06-22 00:31:57 +00003774 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003775 const SCEV *BECount = getCouldNotCompute();
3776 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003777 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003778 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3779 BackedgeTakenInfo NewBTI =
3780 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003781
Dan Gohman1c343752009-06-27 21:21:31 +00003782 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003783 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003784 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003785 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003786 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003787 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003788 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003789 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003790 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003791 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003792 }
Dan Gohman1c343752009-06-27 21:21:31 +00003793 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003794 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003795 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003796 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003797 }
3798
3799 return BackedgeTakenInfo(BECount, MaxBECount);
3800}
3801
3802/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3803/// of the specified loop will execute if it exits via the specified block.
3804ScalarEvolution::BackedgeTakenInfo
3805ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3806 BasicBlock *ExitingBlock) {
3807
3808 // Okay, we've chosen an exiting block. See what condition causes us to
3809 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003810 //
3811 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003812 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003813 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003814 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003815
Chris Lattner8b0e3602007-01-07 02:24:26 +00003816 // At this point, we know we have a conditional branch that determines whether
3817 // the loop is exited. However, we don't know if the branch is executed each
3818 // time through the loop. If not, then the execution count of the branch will
3819 // not be equal to the trip count of the loop.
3820 //
3821 // Currently we check for this by checking to see if the Exit branch goes to
3822 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003823 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003824 // loop header. This is common for un-rotated loops.
3825 //
3826 // If both of those tests fail, walk up the unique predecessor chain to the
3827 // header, stopping if there is an edge that doesn't exit the loop. If the
3828 // header is reached, the execution count of the branch will be equal to the
3829 // trip count of the loop.
3830 //
3831 // More extensive analysis could be done to handle more cases here.
3832 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003833 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003834 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003835 ExitBr->getParent() != L->getHeader()) {
3836 // The simple checks failed, try climbing the unique predecessor chain
3837 // up to the header.
3838 bool Ok = false;
3839 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3840 BasicBlock *Pred = BB->getUniquePredecessor();
3841 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003842 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003843 TerminatorInst *PredTerm = Pred->getTerminator();
3844 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3845 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3846 if (PredSucc == BB)
3847 continue;
3848 // If the predecessor has a successor that isn't BB and isn't
3849 // outside the loop, assume the worst.
3850 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003851 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003852 }
3853 if (Pred == L->getHeader()) {
3854 Ok = true;
3855 break;
3856 }
3857 BB = Pred;
3858 }
3859 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003860 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003861 }
3862
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003863 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003864 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3865 ExitBr->getSuccessor(0),
3866 ExitBr->getSuccessor(1));
3867}
3868
3869/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3870/// backedge of the specified loop will execute if its exit condition
3871/// were a conditional branch of ExitCond, TBB, and FBB.
3872ScalarEvolution::BackedgeTakenInfo
3873ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3874 Value *ExitCond,
3875 BasicBlock *TBB,
3876 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003877 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003878 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3879 if (BO->getOpcode() == Instruction::And) {
3880 // Recurse on the operands of the and.
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(TBB)) {
3888 // Both conditions must be true 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 true 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(FBB) && "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 if (BO->getOpcode() == Instruction::Or) {
3914 // Recurse on the operands of the or.
3915 BackedgeTakenInfo BTI0 =
3916 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3917 BackedgeTakenInfo BTI1 =
3918 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003919 const SCEV *BECount = getCouldNotCompute();
3920 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003921 if (L->contains(FBB)) {
3922 // Both conditions must be false for the loop to continue executing.
3923 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003924 if (BTI0.Exact == getCouldNotCompute() ||
3925 BTI1.Exact == getCouldNotCompute())
3926 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003927 else
3928 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003929 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003930 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003931 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003932 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003933 else
3934 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003935 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003936 // Both conditions must be false at the same time for the loop to exit.
3937 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003938 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003939 if (BTI0.Max == BTI1.Max)
3940 MaxBECount = BTI0.Max;
3941 if (BTI0.Exact == BTI1.Exact)
3942 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003943 }
3944
3945 return BackedgeTakenInfo(BECount, MaxBECount);
3946 }
3947 }
3948
3949 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003950 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003951 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3952 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003953
Dan Gohman00cb5b72010-02-19 18:12:07 +00003954 // Check for a constant condition. These are normally stripped out by
3955 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3956 // preserve the CFG and is temporarily leaving constant conditions
3957 // in place.
3958 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3959 if (L->contains(FBB) == !CI->getZExtValue())
3960 // The backedge is always taken.
3961 return getCouldNotCompute();
3962 else
3963 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003964 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003965 }
3966
Eli Friedman361e54d2009-05-09 12:32:42 +00003967 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003968 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3969}
3970
3971/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3972/// backedge of the specified loop will execute if its exit condition
3973/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3974ScalarEvolution::BackedgeTakenInfo
3975ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3976 ICmpInst *ExitCond,
3977 BasicBlock *TBB,
3978 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003979
Reid Spencere4d87aa2006-12-23 06:05:41 +00003980 // If the condition was exit on true, convert the condition to exit on false
3981 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003982 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003983 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003984 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003986
3987 // Handle common loops like: for (X = "string"; *X; ++X)
3988 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3989 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003990 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003991 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003992 if (ItCnt.hasAnyInfo())
3993 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003994 }
3995
Dan Gohman0bba49c2009-07-07 17:06:11 +00003996 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3997 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003998
3999 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00004000 LHS = getSCEVAtScope(LHS, L);
4001 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004002
Dan Gohman64a845e2009-06-24 04:48:43 +00004003 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004004 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004005 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
4006 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004007 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004008 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004009 }
4010
Dan Gohman03557dc2010-05-03 16:35:17 +00004011 // Simplify the operands before analyzing them.
4012 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4013
Chris Lattner53e677a2004-04-02 20:23:17 +00004014 // If we have a comparison of a chrec against a constant, try to use value
4015 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004016 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4017 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004018 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004019 // Form the constant range.
4020 ConstantRange CompRange(
4021 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004022
Dan Gohman0bba49c2009-07-07 17:06:11 +00004023 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004024 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004025 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004026
Chris Lattner53e677a2004-04-02 20:23:17 +00004027 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004028 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004029 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004030 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4031 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004032 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004033 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004034 case ICmpInst::ICMP_EQ: { // while (X == Y)
4035 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004036 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4037 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004038 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004039 }
4040 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004041 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4042 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004043 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004044 }
4045 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004046 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4047 getNotSCEV(RHS), L, true);
4048 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004049 break;
4050 }
4051 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004052 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4053 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004054 break;
4055 }
4056 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004057 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4058 getNotSCEV(RHS), L, false);
4059 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004060 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004061 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004062 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004063#if 0
David Greene25e0e872009-12-23 22:18:14 +00004064 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004065 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004066 dbgs() << "[unsigned] ";
4067 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004068 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004069 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004070#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004071 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004072 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004073 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004074 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004075}
4076
Chris Lattner673e02b2004-10-12 01:49:27 +00004077static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004078EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4079 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004080 const SCEV *InVal = SE.getConstant(C);
4081 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004082 assert(isa<SCEVConstant>(Val) &&
4083 "Evaluation of SCEV at constant didn't fold correctly?");
4084 return cast<SCEVConstant>(Val)->getValue();
4085}
4086
4087/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4088/// and a GEP expression (missing the pointer index) indexing into it, return
4089/// the addressed element of the initializer or null if the index expression is
4090/// invalid.
4091static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004092GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004093 const std::vector<ConstantInt*> &Indices) {
4094 Constant *Init = GV->getInitializer();
4095 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004096 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004097 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4098 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4099 Init = cast<Constant>(CS->getOperand(Idx));
4100 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4101 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4102 Init = cast<Constant>(CA->getOperand(Idx));
4103 } else if (isa<ConstantAggregateZero>(Init)) {
4104 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4105 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004106 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004107 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4108 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004109 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004110 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004111 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004112 }
4113 return 0;
4114 } else {
4115 return 0; // Unknown initializer type
4116 }
4117 }
4118 return Init;
4119}
4120
Dan Gohman46bdfb02009-02-24 18:55:53 +00004121/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4122/// 'icmp op load X, cst', try to see if we can compute the backedge
4123/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004124ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004125ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4126 LoadInst *LI,
4127 Constant *RHS,
4128 const Loop *L,
4129 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004130 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004131
4132 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004133 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004134 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004135 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004136
4137 // Make sure that it is really a constant global we are gepping, with an
4138 // initializer, and make sure the first IDX is really 0.
4139 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004140 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004141 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4142 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004143 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004144
4145 // Okay, we allow one non-constant index into the GEP instruction.
4146 Value *VarIdx = 0;
4147 std::vector<ConstantInt*> Indexes;
4148 unsigned VarIdxNum = 0;
4149 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4150 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4151 Indexes.push_back(CI);
4152 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004153 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004154 VarIdx = GEP->getOperand(i);
4155 VarIdxNum = i-2;
4156 Indexes.push_back(0);
4157 }
4158
4159 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4160 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004161 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004162 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004163
4164 // We can only recognize very limited forms of loop index expressions, in
4165 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004166 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00004167 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4168 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4169 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004170 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004171
4172 unsigned MaxSteps = MaxBruteForceIterations;
4173 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004174 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004175 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004176 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004177
4178 // Form the GEP offset.
4179 Indexes[VarIdxNum] = Val;
4180
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004181 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004182 if (Result == 0) break; // Cannot compute!
4183
4184 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004185 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004186 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004187 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004188#if 0
David Greene25e0e872009-12-23 22:18:14 +00004189 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004190 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4191 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004192#endif
4193 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004194 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004195 }
4196 }
Dan Gohman1c343752009-06-27 21:21:31 +00004197 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004198}
4199
4200
Chris Lattner3221ad02004-04-17 22:58:41 +00004201/// CanConstantFold - Return true if we can constant fold an instruction of the
4202/// specified type, assuming that all operands were constants.
4203static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004204 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004205 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4206 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004207
Chris Lattner3221ad02004-04-17 22:58:41 +00004208 if (const CallInst *CI = dyn_cast<CallInst>(I))
4209 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004210 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004211 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004212}
4213
Chris Lattner3221ad02004-04-17 22:58:41 +00004214/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4215/// in the loop that V is derived from. We allow arbitrary operations along the
4216/// way, but the operands of an operation must either be constants or a value
4217/// derived from a constant PHI. If this expression does not fit with these
4218/// constraints, return null.
4219static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4220 // If this is not an instruction, or if this is an instruction outside of the
4221 // loop, it can't be derived from a loop PHI.
4222 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004223 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004224
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004225 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004226 if (L->getHeader() == I->getParent())
4227 return PN;
4228 else
4229 // We don't currently keep track of the control flow needed to evaluate
4230 // PHIs, so we cannot handle PHIs inside of loops.
4231 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004232 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004233
4234 // If we won't be able to constant fold this expression even if the operands
4235 // are constants, return early.
4236 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004237
Chris Lattner3221ad02004-04-17 22:58:41 +00004238 // Otherwise, we can evaluate this instruction if all of its operands are
4239 // constant or derived from a PHI node themselves.
4240 PHINode *PHI = 0;
4241 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004242 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004243 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4244 if (P == 0) return 0; // Not evolving from PHI
4245 if (PHI == 0)
4246 PHI = P;
4247 else if (PHI != P)
4248 return 0; // Evolving from multiple different PHIs.
4249 }
4250
4251 // This is a expression evolving from a constant PHI!
4252 return PHI;
4253}
4254
4255/// EvaluateExpression - Given an expression that passes the
4256/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4257/// in the loop has the value PHIVal. If we can't fold this expression for some
4258/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004259static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4260 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004261 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004262 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004263 Instruction *I = cast<Instruction>(V);
4264
Dan Gohman9d4588f2010-06-22 13:15:46 +00004265 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004266
4267 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004268 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004269 if (Operands[i] == 0) return 0;
4270 }
4271
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004272 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004273 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004274 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004275 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004276 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004277}
4278
4279/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4280/// in the header of its containing loop, we know the loop executes a
4281/// constant number of times, and the PHI node is just a recurrence
4282/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004283Constant *
4284ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004285 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004286 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004287 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004288 ConstantEvolutionLoopExitValue.find(PN);
4289 if (I != ConstantEvolutionLoopExitValue.end())
4290 return I->second;
4291
Dan Gohmane0567812010-04-08 23:03:40 +00004292 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004293 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4294
4295 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4296
4297 // Since the loop is canonicalized, the PHI node must have two entries. One
4298 // entry must be a constant (coming in from outside of the loop), and the
4299 // second must be derived from the same PHI.
4300 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4301 Constant *StartCST =
4302 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4303 if (StartCST == 0)
4304 return RetVal = 0; // Must be a constant.
4305
4306 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004307 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4308 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004309 return RetVal = 0; // Not derived from same PHI.
4310
4311 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004312 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004313 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004314
Dan Gohman46bdfb02009-02-24 18:55:53 +00004315 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004316 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004317 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4318 if (IterationNum == NumIterations)
4319 return RetVal = PHIVal; // Got exit value!
4320
4321 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004322 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004323 if (NextPHI == PHIVal)
4324 return RetVal = NextPHI; // Stopped evolving!
4325 if (NextPHI == 0)
4326 return 0; // Couldn't evaluate!
4327 PHIVal = NextPHI;
4328 }
4329}
4330
Dan Gohman07ad19b2009-07-27 16:09:48 +00004331/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004332/// constant number of times (the condition evolves only from constants),
4333/// try to evaluate a few iterations of the loop until we get the exit
4334/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004335/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004336const SCEV *
4337ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4338 Value *Cond,
4339 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004340 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004341 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004342
Dan Gohmanb92654d2010-06-19 14:17:24 +00004343 // If the loop is canonicalized, the PHI will have exactly two entries.
4344 // That's the only form we support here.
4345 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4346
4347 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004348 // second must be derived from the same PHI.
4349 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4350 Constant *StartCST =
4351 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004352 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004353
4354 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004355 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4356 !isa<Constant>(BEValue))
4357 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004358
4359 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4360 // the loop symbolically to determine when the condition gets a value of
4361 // "ExitWhen".
4362 unsigned IterationNum = 0;
4363 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4364 for (Constant *PHIVal = StartCST;
4365 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004366 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004367 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004368
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004369 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004370 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004371
Reid Spencere8019bb2007-03-01 07:25:48 +00004372 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004373 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004374 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004375 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004376
Chris Lattner3221ad02004-04-17 22:58:41 +00004377 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004378 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004379 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004380 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004381 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004382 }
4383
4384 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004385 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004386}
4387
Dan Gohmane7125f42009-09-03 15:00:26 +00004388/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004389/// at the specified scope in the program. The L value specifies a loop
4390/// nest to evaluate the expression at, where null is the top-level or a
4391/// specified loop is immediately inside of the loop.
4392///
4393/// This method can be used to compute the exit value for a variable defined
4394/// in a loop by querying what the value will hold in the parent loop.
4395///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004396/// In the case that a relevant loop exit value cannot be computed, the
4397/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004398const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004399 // Check to see if we've folded this expression at this loop before.
4400 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4401 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4402 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4403 if (!Pair.second)
4404 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004405
Dan Gohman42214892009-08-31 21:15:23 +00004406 // Otherwise compute it.
4407 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004408 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004409 return C;
4410}
4411
4412const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004413 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004414
Nick Lewycky3e630762008-02-20 06:48:22 +00004415 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004416 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004417 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004418 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004419 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004420 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4421 if (PHINode *PN = dyn_cast<PHINode>(I))
4422 if (PN->getParent() == LI->getHeader()) {
4423 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004424 // to see if the loop that contains it has a known backedge-taken
4425 // count. If so, we may be able to force computation of the exit
4426 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004427 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004428 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004429 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004430 // Okay, we know how many times the containing loop executes. If
4431 // this is a constant evolving PHI node, get the final value at
4432 // the specified iteration number.
4433 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004434 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004435 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004436 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004437 }
4438 }
4439
Reid Spencer09906f32006-12-04 21:33:23 +00004440 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004441 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004442 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004443 // result. This is particularly useful for computing loop exit values.
4444 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004445 SmallVector<Constant *, 4> Operands;
4446 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004447 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4448 Value *Op = I->getOperand(i);
4449 if (Constant *C = dyn_cast<Constant>(Op)) {
4450 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004451 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004452 }
Dan Gohman11046452010-06-29 23:43:06 +00004453
4454 // If any of the operands is non-constant and if they are
4455 // non-integer and non-pointer, don't even try to analyze them
4456 // with scev techniques.
4457 if (!isSCEVable(Op->getType()))
4458 return V;
4459
4460 const SCEV *OrigV = getSCEV(Op);
4461 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4462 MadeImprovement |= OrigV != OpV;
4463
4464 Constant *C = 0;
4465 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4466 C = SC->getValue();
4467 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4468 C = dyn_cast<Constant>(SU->getValue());
4469 if (!C) return V;
4470 if (C->getType() != Op->getType())
4471 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4472 Op->getType(),
4473 false),
4474 C, Op->getType());
4475 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004476 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004477
Dan Gohman11046452010-06-29 23:43:06 +00004478 // Check to see if getSCEVAtScope actually made an improvement.
4479 if (MadeImprovement) {
4480 Constant *C = 0;
4481 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4482 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4483 Operands[0], Operands[1], TD);
4484 else
4485 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4486 &Operands[0], Operands.size(), TD);
4487 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004488 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004489 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004490 }
4491 }
4492
4493 // This is some other type of SCEVUnknown, just return it.
4494 return V;
4495 }
4496
Dan Gohman622ed672009-05-04 22:02:23 +00004497 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004498 // Avoid performing the look-up in the common case where the specified
4499 // expression has no loop-variant portions.
4500 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004501 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004502 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004503 // Okay, at least one of these operands is loop variant but might be
4504 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004505 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4506 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004507 NewOps.push_back(OpAtScope);
4508
4509 for (++i; i != e; ++i) {
4510 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004511 NewOps.push_back(OpAtScope);
4512 }
4513 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004514 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004515 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004516 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004517 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004518 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004519 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004520 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004521 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004522 }
4523 }
4524 // If we got here, all operands are loop invariant.
4525 return Comm;
4526 }
4527
Dan Gohman622ed672009-05-04 22:02:23 +00004528 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004529 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4530 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004531 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4532 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004533 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004534 }
4535
4536 // If this is a loop recurrence for a loop that does not contain L, then we
4537 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004538 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004539 // First, attempt to evaluate each operand.
4540 // Avoid performing the look-up in the common case where the specified
4541 // expression has no loop-variant portions.
4542 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4543 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4544 if (OpAtScope == AddRec->getOperand(i))
4545 continue;
4546
4547 // Okay, at least one of these operands is loop variant but might be
4548 // foldable. Build a new instance of the folded commutative expression.
4549 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4550 AddRec->op_begin()+i);
4551 NewOps.push_back(OpAtScope);
4552 for (++i; i != e; ++i)
4553 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4554
4555 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4556 break;
4557 }
4558
4559 // If the scope is outside the addrec's loop, evaluate it by using the
4560 // loop exit value of the addrec.
4561 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004562 // To evaluate this recurrence, we need to know how many times the AddRec
4563 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004564 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004565 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004566
Eli Friedmanb42a6262008-08-04 23:49:06 +00004567 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004568 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004569 }
Dan Gohman11046452010-06-29 23:43:06 +00004570
Dan Gohmand594e6f2009-05-24 23:25:42 +00004571 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004572 }
4573
Dan Gohman622ed672009-05-04 22:02:23 +00004574 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004575 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004576 if (Op == Cast->getOperand())
4577 return Cast; // must be loop invariant
4578 return getZeroExtendExpr(Op, Cast->getType());
4579 }
4580
Dan Gohman622ed672009-05-04 22:02:23 +00004581 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004582 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004583 if (Op == Cast->getOperand())
4584 return Cast; // must be loop invariant
4585 return getSignExtendExpr(Op, Cast->getType());
4586 }
4587
Dan Gohman622ed672009-05-04 22:02:23 +00004588 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004589 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004590 if (Op == Cast->getOperand())
4591 return Cast; // must be loop invariant
4592 return getTruncateExpr(Op, Cast->getType());
4593 }
4594
Torok Edwinc23197a2009-07-14 16:55:14 +00004595 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004596 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004597}
4598
Dan Gohman66a7e852009-05-08 20:38:54 +00004599/// getSCEVAtScope - This is a convenience function which does
4600/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004601const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004602 return getSCEVAtScope(getSCEV(V), L);
4603}
4604
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004605/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4606/// following equation:
4607///
4608/// A * X = B (mod N)
4609///
4610/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4611/// A and B isn't important.
4612///
4613/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004614static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004615 ScalarEvolution &SE) {
4616 uint32_t BW = A.getBitWidth();
4617 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4618 assert(A != 0 && "A must be non-zero.");
4619
4620 // 1. D = gcd(A, N)
4621 //
4622 // The gcd of A and N may have only one prime factor: 2. The number of
4623 // trailing zeros in A is its multiplicity
4624 uint32_t Mult2 = A.countTrailingZeros();
4625 // D = 2^Mult2
4626
4627 // 2. Check if B is divisible by D.
4628 //
4629 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4630 // is not less than multiplicity of this prime factor for D.
4631 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004632 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004633
4634 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4635 // modulo (N / D).
4636 //
4637 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4638 // bit width during computations.
4639 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4640 APInt Mod(BW + 1, 0);
4641 Mod.set(BW - Mult2); // Mod = N / D
4642 APInt I = AD.multiplicativeInverse(Mod);
4643
4644 // 4. Compute the minimum unsigned root of the equation:
4645 // I * (B / D) mod (N / D)
4646 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4647
4648 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4649 // bits.
4650 return SE.getConstant(Result.trunc(BW));
4651}
Chris Lattner53e677a2004-04-02 20:23:17 +00004652
4653/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4654/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4655/// might be the same) or two SCEVCouldNotCompute objects.
4656///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004657static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004658SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004659 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004660 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4661 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4662 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004663
Chris Lattner53e677a2004-04-02 20:23:17 +00004664 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004665 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004666 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004667 return std::make_pair(CNC, CNC);
4668 }
4669
Reid Spencere8019bb2007-03-01 07:25:48 +00004670 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004671 const APInt &L = LC->getValue()->getValue();
4672 const APInt &M = MC->getValue()->getValue();
4673 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004674 APInt Two(BitWidth, 2);
4675 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004676
Dan Gohman64a845e2009-06-24 04:48:43 +00004677 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004678 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004679 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004680 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4681 // The B coefficient is M-N/2
4682 APInt B(M);
4683 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004684
Reid Spencere8019bb2007-03-01 07:25:48 +00004685 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004686 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004687
Reid Spencere8019bb2007-03-01 07:25:48 +00004688 // Compute the B^2-4ac term.
4689 APInt SqrtTerm(B);
4690 SqrtTerm *= B;
4691 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004692
Reid Spencere8019bb2007-03-01 07:25:48 +00004693 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4694 // integer value or else APInt::sqrt() will assert.
4695 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004696
Dan Gohman64a845e2009-06-24 04:48:43 +00004697 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004698 // The divisions must be performed as signed divisions.
4699 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004700 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004701 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004702 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004703 return std::make_pair(CNC, CNC);
4704 }
4705
Owen Andersone922c022009-07-22 00:24:57 +00004706 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004707
4708 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004709 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004710 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004711 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004712
Dan Gohman64a845e2009-06-24 04:48:43 +00004713 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004714 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004715 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004716}
4717
4718/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004719/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004720ScalarEvolution::BackedgeTakenInfo
4721ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004722 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004723 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004724 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004725 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004726 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004727 }
4728
Dan Gohman35738ac2009-05-04 22:30:44 +00004729 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004730 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004731 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004732
4733 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004734 // If this is an affine expression, the execution count of this branch is
4735 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004736 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004737 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004738 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004739 // equivalent to:
4740 //
4741 // Step*N = -Start (mod 2^BW)
4742 //
4743 // where BW is the common bit width of Start and Step.
4744
Chris Lattner53e677a2004-04-02 20:23:17 +00004745 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004746 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4747 L->getParentLoop());
4748 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4749 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004750
Dan Gohman622ed672009-05-04 22:02:23 +00004751 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004752 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004753
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004754 // First, handle unitary steps.
4755 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004756 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004757 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4758 return Start; // N = Start (as unsigned)
4759
4760 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004761 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004762 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004763 -StartC->getValue()->getValue(),
4764 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004765 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004766 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004767 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4768 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004769 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004770 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004771 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4772 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004773 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004774#if 0
David Greene25e0e872009-12-23 22:18:14 +00004775 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004776 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004777#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004778 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004779 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004780 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004781 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004782 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004783 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004784
Chris Lattner53e677a2004-04-02 20:23:17 +00004785 // We can only use this value if the chrec ends up with an exact zero
4786 // value at this index. When solving for "X*X != 5", for example, we
4787 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004788 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004789 if (Val->isZero())
4790 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004791 }
4792 }
4793 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004794
Dan Gohman1c343752009-06-27 21:21:31 +00004795 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004796}
4797
4798/// HowFarToNonZero - Return the number of times a backedge checking the
4799/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004800/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004801ScalarEvolution::BackedgeTakenInfo
4802ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004803 // Loops that look like: while (X == 0) are very strange indeed. We don't
4804 // handle them yet except for the trivial case. This could be expanded in the
4805 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004806
Chris Lattner53e677a2004-04-02 20:23:17 +00004807 // If the value is a constant, check to see if it is known to be non-zero
4808 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004809 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004810 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004811 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004812 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004813 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004814
Chris Lattner53e677a2004-04-02 20:23:17 +00004815 // We could implement others, but I really doubt anyone writes loops like
4816 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004817 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004818}
4819
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004820/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4821/// (which may not be an immediate predecessor) which has exactly one
4822/// successor from which BB is reachable, or null if no such block is
4823/// found.
4824///
Dan Gohman005752b2010-04-15 16:19:08 +00004825std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004826ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004827 // If the block has a unique predecessor, then there is no path from the
4828 // predecessor to the block that does not go through the direct edge
4829 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004830 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004831 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004832
4833 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004834 // If the header has a unique predecessor outside the loop, it must be
4835 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004836 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004837 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004838
Dan Gohman005752b2010-04-15 16:19:08 +00004839 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004840}
4841
Dan Gohman763bad12009-06-20 00:35:32 +00004842/// HasSameValue - SCEV structural equivalence is usually sufficient for
4843/// testing whether two expressions are equal, however for the purposes of
4844/// looking for a condition guarding a loop, it can be useful to be a little
4845/// more general, since a front-end may have replicated the controlling
4846/// expression.
4847///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004848static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004849 // Quick check to see if they are the same SCEV.
4850 if (A == B) return true;
4851
4852 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4853 // two different instructions with the same value. Check for this case.
4854 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4855 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4856 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4857 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004858 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004859 return true;
4860
4861 // Otherwise assume they may have a different value.
4862 return false;
4863}
4864
Dan Gohmane9796502010-04-24 01:28:42 +00004865/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4866/// predicate Pred. Return true iff any changes were made.
4867///
4868bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4869 const SCEV *&LHS, const SCEV *&RHS) {
4870 bool Changed = false;
4871
4872 // Canonicalize a constant to the right side.
4873 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4874 // Check for both operands constant.
4875 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4876 if (ConstantExpr::getICmp(Pred,
4877 LHSC->getValue(),
4878 RHSC->getValue())->isNullValue())
4879 goto trivially_false;
4880 else
4881 goto trivially_true;
4882 }
4883 // Otherwise swap the operands to put the constant on the right.
4884 std::swap(LHS, RHS);
4885 Pred = ICmpInst::getSwappedPredicate(Pred);
4886 Changed = true;
4887 }
4888
4889 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004890 // addrec's loop, put the addrec on the left. Also make a dominance check,
4891 // as both operands could be addrecs loop-invariant in each other's loop.
4892 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4893 const Loop *L = AR->getLoop();
4894 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004895 std::swap(LHS, RHS);
4896 Pred = ICmpInst::getSwappedPredicate(Pred);
4897 Changed = true;
4898 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004899 }
Dan Gohmane9796502010-04-24 01:28:42 +00004900
4901 // If there's a constant operand, canonicalize comparisons with boundary
4902 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4903 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4904 const APInt &RA = RC->getValue()->getValue();
4905 switch (Pred) {
4906 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4907 case ICmpInst::ICMP_EQ:
4908 case ICmpInst::ICMP_NE:
4909 break;
4910 case ICmpInst::ICMP_UGE:
4911 if ((RA - 1).isMinValue()) {
4912 Pred = ICmpInst::ICMP_NE;
4913 RHS = getConstant(RA - 1);
4914 Changed = true;
4915 break;
4916 }
4917 if (RA.isMaxValue()) {
4918 Pred = ICmpInst::ICMP_EQ;
4919 Changed = true;
4920 break;
4921 }
4922 if (RA.isMinValue()) goto trivially_true;
4923
4924 Pred = ICmpInst::ICMP_UGT;
4925 RHS = getConstant(RA - 1);
4926 Changed = true;
4927 break;
4928 case ICmpInst::ICMP_ULE:
4929 if ((RA + 1).isMaxValue()) {
4930 Pred = ICmpInst::ICMP_NE;
4931 RHS = getConstant(RA + 1);
4932 Changed = true;
4933 break;
4934 }
4935 if (RA.isMinValue()) {
4936 Pred = ICmpInst::ICMP_EQ;
4937 Changed = true;
4938 break;
4939 }
4940 if (RA.isMaxValue()) goto trivially_true;
4941
4942 Pred = ICmpInst::ICMP_ULT;
4943 RHS = getConstant(RA + 1);
4944 Changed = true;
4945 break;
4946 case ICmpInst::ICMP_SGE:
4947 if ((RA - 1).isMinSignedValue()) {
4948 Pred = ICmpInst::ICMP_NE;
4949 RHS = getConstant(RA - 1);
4950 Changed = true;
4951 break;
4952 }
4953 if (RA.isMaxSignedValue()) {
4954 Pred = ICmpInst::ICMP_EQ;
4955 Changed = true;
4956 break;
4957 }
4958 if (RA.isMinSignedValue()) goto trivially_true;
4959
4960 Pred = ICmpInst::ICMP_SGT;
4961 RHS = getConstant(RA - 1);
4962 Changed = true;
4963 break;
4964 case ICmpInst::ICMP_SLE:
4965 if ((RA + 1).isMaxSignedValue()) {
4966 Pred = ICmpInst::ICMP_NE;
4967 RHS = getConstant(RA + 1);
4968 Changed = true;
4969 break;
4970 }
4971 if (RA.isMinSignedValue()) {
4972 Pred = ICmpInst::ICMP_EQ;
4973 Changed = true;
4974 break;
4975 }
4976 if (RA.isMaxSignedValue()) goto trivially_true;
4977
4978 Pred = ICmpInst::ICMP_SLT;
4979 RHS = getConstant(RA + 1);
4980 Changed = true;
4981 break;
4982 case ICmpInst::ICMP_UGT:
4983 if (RA.isMinValue()) {
4984 Pred = ICmpInst::ICMP_NE;
4985 Changed = true;
4986 break;
4987 }
4988 if ((RA + 1).isMaxValue()) {
4989 Pred = ICmpInst::ICMP_EQ;
4990 RHS = getConstant(RA + 1);
4991 Changed = true;
4992 break;
4993 }
4994 if (RA.isMaxValue()) goto trivially_false;
4995 break;
4996 case ICmpInst::ICMP_ULT:
4997 if (RA.isMaxValue()) {
4998 Pred = ICmpInst::ICMP_NE;
4999 Changed = true;
5000 break;
5001 }
5002 if ((RA - 1).isMinValue()) {
5003 Pred = ICmpInst::ICMP_EQ;
5004 RHS = getConstant(RA - 1);
5005 Changed = true;
5006 break;
5007 }
5008 if (RA.isMinValue()) goto trivially_false;
5009 break;
5010 case ICmpInst::ICMP_SGT:
5011 if (RA.isMinSignedValue()) {
5012 Pred = ICmpInst::ICMP_NE;
5013 Changed = true;
5014 break;
5015 }
5016 if ((RA + 1).isMaxSignedValue()) {
5017 Pred = ICmpInst::ICMP_EQ;
5018 RHS = getConstant(RA + 1);
5019 Changed = true;
5020 break;
5021 }
5022 if (RA.isMaxSignedValue()) goto trivially_false;
5023 break;
5024 case ICmpInst::ICMP_SLT:
5025 if (RA.isMaxSignedValue()) {
5026 Pred = ICmpInst::ICMP_NE;
5027 Changed = true;
5028 break;
5029 }
5030 if ((RA - 1).isMinSignedValue()) {
5031 Pred = ICmpInst::ICMP_EQ;
5032 RHS = getConstant(RA - 1);
5033 Changed = true;
5034 break;
5035 }
5036 if (RA.isMinSignedValue()) goto trivially_false;
5037 break;
5038 }
5039 }
5040
5041 // Check for obvious equality.
5042 if (HasSameValue(LHS, RHS)) {
5043 if (ICmpInst::isTrueWhenEqual(Pred))
5044 goto trivially_true;
5045 if (ICmpInst::isFalseWhenEqual(Pred))
5046 goto trivially_false;
5047 }
5048
Dan Gohman03557dc2010-05-03 16:35:17 +00005049 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5050 // adding or subtracting 1 from one of the operands.
5051 switch (Pred) {
5052 case ICmpInst::ICMP_SLE:
5053 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5054 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5055 /*HasNUW=*/false, /*HasNSW=*/true);
5056 Pred = ICmpInst::ICMP_SLT;
5057 Changed = true;
5058 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005059 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005060 /*HasNUW=*/false, /*HasNSW=*/true);
5061 Pred = ICmpInst::ICMP_SLT;
5062 Changed = true;
5063 }
5064 break;
5065 case ICmpInst::ICMP_SGE:
5066 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005067 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005068 /*HasNUW=*/false, /*HasNSW=*/true);
5069 Pred = ICmpInst::ICMP_SGT;
5070 Changed = true;
5071 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5072 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5073 /*HasNUW=*/false, /*HasNSW=*/true);
5074 Pred = ICmpInst::ICMP_SGT;
5075 Changed = true;
5076 }
5077 break;
5078 case ICmpInst::ICMP_ULE:
5079 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005080 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005081 /*HasNUW=*/true, /*HasNSW=*/false);
5082 Pred = ICmpInst::ICMP_ULT;
5083 Changed = true;
5084 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005085 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005086 /*HasNUW=*/true, /*HasNSW=*/false);
5087 Pred = ICmpInst::ICMP_ULT;
5088 Changed = true;
5089 }
5090 break;
5091 case ICmpInst::ICMP_UGE:
5092 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005093 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005094 /*HasNUW=*/true, /*HasNSW=*/false);
5095 Pred = ICmpInst::ICMP_UGT;
5096 Changed = true;
5097 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005098 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005099 /*HasNUW=*/true, /*HasNSW=*/false);
5100 Pred = ICmpInst::ICMP_UGT;
5101 Changed = true;
5102 }
5103 break;
5104 default:
5105 break;
5106 }
5107
Dan Gohmane9796502010-04-24 01:28:42 +00005108 // TODO: More simplifications are possible here.
5109
5110 return Changed;
5111
5112trivially_true:
5113 // Return 0 == 0.
5114 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5115 Pred = ICmpInst::ICMP_EQ;
5116 return true;
5117
5118trivially_false:
5119 // Return 0 != 0.
5120 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5121 Pred = ICmpInst::ICMP_NE;
5122 return true;
5123}
5124
Dan Gohman85b05a22009-07-13 21:35:55 +00005125bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5126 return getSignedRange(S).getSignedMax().isNegative();
5127}
5128
5129bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5130 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5131}
5132
5133bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5134 return !getSignedRange(S).getSignedMin().isNegative();
5135}
5136
5137bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5138 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5139}
5140
5141bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5142 return isKnownNegative(S) || isKnownPositive(S);
5143}
5144
5145bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5146 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005147 // Canonicalize the inputs first.
5148 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5149
Dan Gohman53c66ea2010-04-11 22:16:48 +00005150 // If LHS or RHS is an addrec, check to see if the condition is true in
5151 // every iteration of the loop.
5152 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5153 if (isLoopEntryGuardedByCond(
5154 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5155 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005156 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005157 return true;
5158 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5159 if (isLoopEntryGuardedByCond(
5160 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5161 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005162 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005163 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005164
Dan Gohman53c66ea2010-04-11 22:16:48 +00005165 // Otherwise see what can be done with known constant ranges.
5166 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5167}
5168
5169bool
5170ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5171 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005172 if (HasSameValue(LHS, RHS))
5173 return ICmpInst::isTrueWhenEqual(Pred);
5174
Dan Gohman53c66ea2010-04-11 22:16:48 +00005175 // This code is split out from isKnownPredicate because it is called from
5176 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005177 switch (Pred) {
5178 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005179 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005180 break;
5181 case ICmpInst::ICMP_SGT:
5182 Pred = ICmpInst::ICMP_SLT;
5183 std::swap(LHS, RHS);
5184 case ICmpInst::ICMP_SLT: {
5185 ConstantRange LHSRange = getSignedRange(LHS);
5186 ConstantRange RHSRange = getSignedRange(RHS);
5187 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5188 return true;
5189 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5190 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005191 break;
5192 }
5193 case ICmpInst::ICMP_SGE:
5194 Pred = ICmpInst::ICMP_SLE;
5195 std::swap(LHS, RHS);
5196 case ICmpInst::ICMP_SLE: {
5197 ConstantRange LHSRange = getSignedRange(LHS);
5198 ConstantRange RHSRange = getSignedRange(RHS);
5199 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5200 return true;
5201 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5202 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005203 break;
5204 }
5205 case ICmpInst::ICMP_UGT:
5206 Pred = ICmpInst::ICMP_ULT;
5207 std::swap(LHS, RHS);
5208 case ICmpInst::ICMP_ULT: {
5209 ConstantRange LHSRange = getUnsignedRange(LHS);
5210 ConstantRange RHSRange = getUnsignedRange(RHS);
5211 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5212 return true;
5213 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5214 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005215 break;
5216 }
5217 case ICmpInst::ICMP_UGE:
5218 Pred = ICmpInst::ICMP_ULE;
5219 std::swap(LHS, RHS);
5220 case ICmpInst::ICMP_ULE: {
5221 ConstantRange LHSRange = getUnsignedRange(LHS);
5222 ConstantRange RHSRange = getUnsignedRange(RHS);
5223 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5224 return true;
5225 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5226 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005227 break;
5228 }
5229 case ICmpInst::ICMP_NE: {
5230 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5231 return true;
5232 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5233 return true;
5234
5235 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5236 if (isKnownNonZero(Diff))
5237 return true;
5238 break;
5239 }
5240 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005241 // The check at the top of the function catches the case where
5242 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005243 break;
5244 }
5245 return false;
5246}
5247
5248/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5249/// protected by a conditional between LHS and RHS. This is used to
5250/// to eliminate casts.
5251bool
5252ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5253 ICmpInst::Predicate Pred,
5254 const SCEV *LHS, const SCEV *RHS) {
5255 // Interpret a null as meaning no loop, where there is obviously no guard
5256 // (interprocedural conditions notwithstanding).
5257 if (!L) return true;
5258
5259 BasicBlock *Latch = L->getLoopLatch();
5260 if (!Latch)
5261 return false;
5262
5263 BranchInst *LoopContinuePredicate =
5264 dyn_cast<BranchInst>(Latch->getTerminator());
5265 if (!LoopContinuePredicate ||
5266 LoopContinuePredicate->isUnconditional())
5267 return false;
5268
Dan Gohmanaf08a362010-08-10 23:46:30 +00005269 return isImpliedCond(Pred, LHS, RHS,
5270 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005271 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005272}
5273
Dan Gohman3948d0b2010-04-11 19:27:13 +00005274/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005275/// by a conditional between LHS and RHS. This is used to help avoid max
5276/// expressions in loop trip counts, and to eliminate casts.
5277bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005278ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5279 ICmpInst::Predicate Pred,
5280 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005281 // Interpret a null as meaning no loop, where there is obviously no guard
5282 // (interprocedural conditions notwithstanding).
5283 if (!L) return false;
5284
Dan Gohman859b4822009-05-18 15:36:09 +00005285 // Starting at the loop predecessor, climb up the predecessor chain, as long
5286 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005287 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005288 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005289 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005290 Pair.first;
5291 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005292
5293 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005294 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005295 if (!LoopEntryPredicate ||
5296 LoopEntryPredicate->isUnconditional())
5297 continue;
5298
Dan Gohmanaf08a362010-08-10 23:46:30 +00005299 if (isImpliedCond(Pred, LHS, RHS,
5300 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005301 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005302 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005303 }
5304
Dan Gohman38372182008-08-12 20:17:31 +00005305 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005306}
5307
Dan Gohman0f4b2852009-07-21 23:03:19 +00005308/// isImpliedCond - Test whether the condition described by Pred, LHS,
5309/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005310bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005311 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005312 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005313 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005314 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005315 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005316 if (BO->getOpcode() == Instruction::And) {
5317 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005318 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5319 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005320 } else if (BO->getOpcode() == Instruction::Or) {
5321 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005322 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5323 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005324 }
5325 }
5326
Dan Gohmanaf08a362010-08-10 23:46:30 +00005327 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005328 if (!ICI) return false;
5329
Dan Gohman85b05a22009-07-13 21:35:55 +00005330 // Bail if the ICmp's operands' types are wider than the needed type
5331 // before attempting to call getSCEV on them. This avoids infinite
5332 // recursion, since the analysis of widening casts can require loop
5333 // exit condition information for overflow checking, which would
5334 // lead back here.
5335 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005336 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005337 return false;
5338
Dan Gohman0f4b2852009-07-21 23:03:19 +00005339 // Now that we found a conditional branch that dominates the loop, check to
5340 // see if it is the comparison we are looking for.
5341 ICmpInst::Predicate FoundPred;
5342 if (Inverse)
5343 FoundPred = ICI->getInversePredicate();
5344 else
5345 FoundPred = ICI->getPredicate();
5346
5347 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5348 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005349
5350 // Balance the types. The case where FoundLHS' type is wider than
5351 // LHS' type is checked for above.
5352 if (getTypeSizeInBits(LHS->getType()) >
5353 getTypeSizeInBits(FoundLHS->getType())) {
5354 if (CmpInst::isSigned(Pred)) {
5355 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5356 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5357 } else {
5358 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5359 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5360 }
5361 }
5362
Dan Gohman0f4b2852009-07-21 23:03:19 +00005363 // Canonicalize the query to match the way instcombine will have
5364 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005365 if (SimplifyICmpOperands(Pred, LHS, RHS))
5366 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005367 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005368 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5369 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005370 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005371
5372 // Check to see if we can make the LHS or RHS match.
5373 if (LHS == FoundRHS || RHS == FoundLHS) {
5374 if (isa<SCEVConstant>(RHS)) {
5375 std::swap(FoundLHS, FoundRHS);
5376 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5377 } else {
5378 std::swap(LHS, RHS);
5379 Pred = ICmpInst::getSwappedPredicate(Pred);
5380 }
5381 }
5382
5383 // Check whether the found predicate is the same as the desired predicate.
5384 if (FoundPred == Pred)
5385 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5386
5387 // Check whether swapping the found predicate makes it the same as the
5388 // desired predicate.
5389 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5390 if (isa<SCEVConstant>(RHS))
5391 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5392 else
5393 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5394 RHS, LHS, FoundLHS, FoundRHS);
5395 }
5396
5397 // Check whether the actual condition is beyond sufficient.
5398 if (FoundPred == ICmpInst::ICMP_EQ)
5399 if (ICmpInst::isTrueWhenEqual(Pred))
5400 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5401 return true;
5402 if (Pred == ICmpInst::ICMP_NE)
5403 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5404 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5405 return true;
5406
5407 // Otherwise assume the worst.
5408 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005409}
5410
Dan Gohman0f4b2852009-07-21 23:03:19 +00005411/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005412/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005413/// and FoundRHS is true.
5414bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5415 const SCEV *LHS, const SCEV *RHS,
5416 const SCEV *FoundLHS,
5417 const SCEV *FoundRHS) {
5418 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5419 FoundLHS, FoundRHS) ||
5420 // ~x < ~y --> x > y
5421 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5422 getNotSCEV(FoundRHS),
5423 getNotSCEV(FoundLHS));
5424}
5425
5426/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005427/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005428/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005429bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005430ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5431 const SCEV *LHS, const SCEV *RHS,
5432 const SCEV *FoundLHS,
5433 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005434 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005435 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5436 case ICmpInst::ICMP_EQ:
5437 case ICmpInst::ICMP_NE:
5438 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5439 return true;
5440 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005441 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005442 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005443 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5444 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005445 return true;
5446 break;
5447 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005448 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005449 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5450 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005451 return true;
5452 break;
5453 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005454 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005455 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5456 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005457 return true;
5458 break;
5459 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005460 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005461 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5462 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005463 return true;
5464 break;
5465 }
5466
5467 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005468}
5469
Dan Gohman51f53b72009-06-21 23:46:38 +00005470/// getBECount - Subtract the end and start values and divide by the step,
5471/// rounding up, to get the number of times the backedge is executed. Return
5472/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005473const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005474 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005475 const SCEV *Step,
5476 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005477 assert(!isKnownNegative(Step) &&
5478 "This code doesn't handle negative strides yet!");
5479
Dan Gohman51f53b72009-06-21 23:46:38 +00005480 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005481 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005482 const SCEV *Diff = getMinusSCEV(End, Start);
5483 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005484
5485 // Add an adjustment to the difference between End and Start so that
5486 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005487 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005488
Dan Gohman1f96e672009-09-17 18:05:20 +00005489 if (!NoWrap) {
5490 // Check Add for unsigned overflow.
5491 // TODO: More sophisticated things could be done here.
5492 const Type *WideTy = IntegerType::get(getContext(),
5493 getTypeSizeInBits(Ty) + 1);
5494 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5495 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5496 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5497 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5498 return getCouldNotCompute();
5499 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005500
5501 return getUDivExpr(Add, Step);
5502}
5503
Chris Lattnerdb25de42005-08-15 23:33:51 +00005504/// HowManyLessThans - Return the number of times a backedge containing the
5505/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005506/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005507ScalarEvolution::BackedgeTakenInfo
5508ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5509 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005510 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005511 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005512
Dan Gohman35738ac2009-05-04 22:30:44 +00005513 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005514 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005515 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005516
Dan Gohman1f96e672009-09-17 18:05:20 +00005517 // Check to see if we have a flag which makes analysis easy.
5518 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5519 AddRec->hasNoUnsignedWrap();
5520
Chris Lattnerdb25de42005-08-15 23:33:51 +00005521 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005522 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005523 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005524
Dan Gohman52fddd32010-01-26 04:40:18 +00005525 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005526 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005527 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005528 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005529 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005530 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005531 // value and past the maximum value for its type in a single step.
5532 // Note that it's not sufficient to check NoWrap here, because even
5533 // though the value after a wrap is undefined, it's not undefined
5534 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005535 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005536 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005537 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005538 if (isSigned) {
5539 APInt Max = APInt::getSignedMaxValue(BitWidth);
5540 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5541 .slt(getSignedRange(RHS).getSignedMax()))
5542 return getCouldNotCompute();
5543 } else {
5544 APInt Max = APInt::getMaxValue(BitWidth);
5545 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5546 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5547 return getCouldNotCompute();
5548 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005549 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005550 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005551 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005552
Dan Gohmana1af7572009-04-30 20:47:05 +00005553 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5554 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5555 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005556 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005557
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005558 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005559 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005560
Dan Gohmana1af7572009-04-30 20:47:05 +00005561 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005562 const SCEV *MinStart = getConstant(isSigned ?
5563 getSignedRange(Start).getSignedMin() :
5564 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005565
Dan Gohmana1af7572009-04-30 20:47:05 +00005566 // If we know that the condition is true in order to enter the loop,
5567 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005568 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5569 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005570 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005571 if (!isLoopEntryGuardedByCond(L,
5572 isSigned ? ICmpInst::ICMP_SLT :
5573 ICmpInst::ICMP_ULT,
5574 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005575 End = isSigned ? getSMaxExpr(RHS, Start)
5576 : getUMaxExpr(RHS, Start);
5577
5578 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005579 const SCEV *MaxEnd = getConstant(isSigned ?
5580 getSignedRange(End).getSignedMax() :
5581 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005582
Dan Gohman52fddd32010-01-26 04:40:18 +00005583 // If MaxEnd is within a step of the maximum integer value in its type,
5584 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005585 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005586 // compute the correct value.
5587 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005588 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005589 MaxEnd = isSigned ?
5590 getSMinExpr(MaxEnd,
5591 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5592 StepMinusOne)) :
5593 getUMinExpr(MaxEnd,
5594 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5595 StepMinusOne));
5596
Dan Gohmana1af7572009-04-30 20:47:05 +00005597 // Finally, we subtract these two values and divide, rounding up, to get
5598 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005599 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005600
5601 // The maximum backedge count is similar, except using the minimum start
5602 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005603 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005604
5605 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005606 }
5607
Dan Gohman1c343752009-06-27 21:21:31 +00005608 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005609}
5610
Chris Lattner53e677a2004-04-02 20:23:17 +00005611/// getNumIterationsInRange - Return the number of iterations of this loop that
5612/// produce values in the specified constant range. Another way of looking at
5613/// this is that it returns the first iteration number where the value is not in
5614/// the condition, thus computing the exit count. If the iteration count can't
5615/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005616const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005617 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005618 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005619 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005620
5621 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005622 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005623 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005624 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005625 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005626 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005627 if (const SCEVAddRecExpr *ShiftedAddRec =
5628 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005629 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005630 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005631 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005632 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005633 }
5634
5635 // The only time we can solve this is when we have all constant indices.
5636 // Otherwise, we cannot determine the overflow conditions.
5637 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5638 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005639 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005640
5641
5642 // Okay at this point we know that all elements of the chrec are constants and
5643 // that the start element is zero.
5644
5645 // First check to see if the range contains zero. If not, the first
5646 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005647 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005648 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005649 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005650
Chris Lattner53e677a2004-04-02 20:23:17 +00005651 if (isAffine()) {
5652 // If this is an affine expression then we have this situation:
5653 // Solve {0,+,A} in Range === Ax in Range
5654
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005655 // We know that zero is in the range. If A is positive then we know that
5656 // the upper value of the range must be the first possible exit value.
5657 // If A is negative then the lower of the range is the last possible loop
5658 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005659 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005660 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5661 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005662
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005663 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005664 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005665 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005666
5667 // Evaluate at the exit value. If we really did fall out of the valid
5668 // range, then we computed our trip count, otherwise wrap around or other
5669 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005670 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005671 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005672 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005673
5674 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005675 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005676 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005677 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005678 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005679 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005680 } else if (isQuadratic()) {
5681 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5682 // quadratic equation to solve it. To do this, we must frame our problem in
5683 // terms of figuring out when zero is crossed, instead of when
5684 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005685 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005686 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005687 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005688
5689 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005690 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005691 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005692 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5693 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005694 if (R1) {
5695 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005696 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005697 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005698 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005699 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005700 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005701
Chris Lattner53e677a2004-04-02 20:23:17 +00005702 // Make sure the root is not off by one. The returned iteration should
5703 // not be in the range, but the previous one should be. When solving
5704 // for "X*X < 5", for example, we should not return a root of 2.
5705 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005706 R1->getValue(),
5707 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005708 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005709 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005710 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005711 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005712
Dan Gohman246b2562007-10-22 18:31:58 +00005713 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005714 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005715 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005716 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005717 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005718
Chris Lattner53e677a2004-04-02 20:23:17 +00005719 // If R1 was not in the range, then it is a good return value. Make
5720 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005721 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005722 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005723 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005724 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005725 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005726 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005727 }
5728 }
5729 }
5730
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005731 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005732}
5733
5734
5735
5736//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005737// SCEVCallbackVH Class Implementation
5738//===----------------------------------------------------------------------===//
5739
Dan Gohman1959b752009-05-19 19:22:47 +00005740void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005741 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005742 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5743 SE->ConstantEvolutionLoopExitValue.erase(PN);
5744 SE->Scalars.erase(getValPtr());
5745 // this now dangles!
5746}
5747
Dan Gohman81f91212010-07-28 01:09:07 +00005748void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005749 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005750
Dan Gohman35738ac2009-05-04 22:30:44 +00005751 // Forget all the expressions associated with users of the old value,
5752 // so that future queries will recompute the expressions using the new
5753 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005754 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005755 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005756 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005757 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5758 UI != UE; ++UI)
5759 Worklist.push_back(*UI);
5760 while (!Worklist.empty()) {
5761 User *U = Worklist.pop_back_val();
5762 // Deleting the Old value will cause this to dangle. Postpone
5763 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005764 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005765 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005766 if (!Visited.insert(U))
5767 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005768 if (PHINode *PN = dyn_cast<PHINode>(U))
5769 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005770 SE->Scalars.erase(U);
5771 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5772 UI != UE; ++UI)
5773 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005774 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005775 // Delete the Old value.
5776 if (PHINode *PN = dyn_cast<PHINode>(Old))
5777 SE->ConstantEvolutionLoopExitValue.erase(PN);
5778 SE->Scalars.erase(Old);
5779 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005780}
5781
Dan Gohman1959b752009-05-19 19:22:47 +00005782ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005783 : CallbackVH(V), SE(se) {}
5784
5785//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005786// ScalarEvolution Class Implementation
5787//===----------------------------------------------------------------------===//
5788
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005789ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005790 : FunctionPass(ID), FirstUnknown(0) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005791}
5792
Chris Lattner53e677a2004-04-02 20:23:17 +00005793bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005794 this->F = &F;
5795 LI = &getAnalysis<LoopInfo>();
5796 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005797 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005798 return false;
5799}
5800
5801void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005802 // Iterate through all the SCEVUnknown instances and call their
5803 // destructors, so that they release their references to their values.
5804 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5805 U->~SCEVUnknown();
5806 FirstUnknown = 0;
5807
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005808 Scalars.clear();
5809 BackedgeTakenCounts.clear();
5810 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005811 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005812 UniqueSCEVs.clear();
5813 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005814}
5815
5816void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5817 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005818 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005819 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005820}
5821
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005822bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005823 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005824}
5825
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005826static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005827 const Loop *L) {
5828 // Print all inner loops first
5829 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5830 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005831
Dan Gohman30733292010-01-09 18:17:45 +00005832 OS << "Loop ";
5833 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5834 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005835
Dan Gohman5d984912009-12-18 01:14:11 +00005836 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005837 L->getExitBlocks(ExitBlocks);
5838 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005839 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005840
Dan Gohman46bdfb02009-02-24 18:55:53 +00005841 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5842 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005843 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005844 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005845 }
5846
Dan Gohman30733292010-01-09 18:17:45 +00005847 OS << "\n"
5848 "Loop ";
5849 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5850 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005851
5852 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5853 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5854 } else {
5855 OS << "Unpredictable max backedge-taken count. ";
5856 }
5857
5858 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005859}
5860
Dan Gohman5d984912009-12-18 01:14:11 +00005861void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005862 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005863 // out SCEV values of all instructions that are interesting. Doing
5864 // this potentially causes it to create new SCEV objects though,
5865 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005866 // observable from outside the class though, so casting away the
5867 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005868 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005869
Dan Gohman30733292010-01-09 18:17:45 +00005870 OS << "Classifying expressions for: ";
5871 WriteAsOperand(OS, F, /*PrintType=*/false);
5872 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005873 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005874 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005875 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005876 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005877 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005878 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005879
Dan Gohman0c689c52009-06-19 17:49:54 +00005880 const Loop *L = LI->getLoopFor((*I).getParent());
5881
Dan Gohman0bba49c2009-07-07 17:06:11 +00005882 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005883 if (AtUse != SV) {
5884 OS << " --> ";
5885 AtUse->print(OS);
5886 }
5887
5888 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005889 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005890 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005891 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005892 OS << "<<Unknown>>";
5893 } else {
5894 OS << *ExitValue;
5895 }
5896 }
5897
Chris Lattner53e677a2004-04-02 20:23:17 +00005898 OS << "\n";
5899 }
5900
Dan Gohman30733292010-01-09 18:17:45 +00005901 OS << "Determining loop execution counts for: ";
5902 WriteAsOperand(OS, F, /*PrintType=*/false);
5903 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005904 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5905 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005906}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005907