blob: a9679d91180d1895bd8f960c9bc61375eb5228fe [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Owen Andersond13db2c2010-07-21 22:09:45 +0000106INITIALIZE_PASS(ScalarEvolution, "scalar-evolution",
107 "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000144 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000180 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000181 UniqueSCEVs.InsertNode(S, IP);
182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000186 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Dan Gohman0bba49c2009-07-07 17:06:11 +0000189const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000191 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
192 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000193}
194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Dan Gohman3bf63762010-06-18 19:54:20 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000204
Dan Gohman84923602009-04-21 01:25:57 +0000205bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
207}
208
Dan Gohman6e70e312009-09-27 15:26:03 +0000209bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
211}
212
Dan Gohman3bf63762010-06-18 19:54:20 +0000213SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000215 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000216 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
217 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
Dan Gohman3bf63762010-06-18 19:54:20 +0000225SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000228 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
229 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000233void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
236
Dan Gohman3bf63762010-06-18 19:54:20 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000240 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
241 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000242 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000243}
244
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000245void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000247}
248
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000249void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250 const char *OpStr = getOperationStr();
Dan Gohmana5145c82010-04-16 15:03:25 +0000251 OS << "(";
252 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
253 OS << **I;
Oscar Fuentesee56c422010-08-02 06:00:15 +0000254 if (llvm::next(I) != E)
Dan Gohmana5145c82010-04-16 15:03:25 +0000255 OS << OpStr;
256 }
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000257 OS << ")";
258}
259
Dan Gohmanecb403a2009-05-07 14:00:19 +0000260bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
263 return false;
264 }
265 return true;
266}
267
Dan Gohman6e70e312009-09-27 15:26:03 +0000268bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
270 if (!getOperand(i)->properlyDominates(BB, DT))
271 return false;
272 }
273 return true;
274}
275
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000276bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
277 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
278}
279
Dan Gohman6e70e312009-09-27 15:26:03 +0000280bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
281 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
282}
283
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000284void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000285 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000286}
287
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000288const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000289 // In most cases the types of LHS and RHS will be the same, but in some
290 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
291 // depend on the type for correctness, but handling types carefully can
292 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
293 // a pointer type than the RHS, so use the RHS' type here.
294 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000295}
296
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000298 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000299 if (!QueryLoop)
300 return false;
301
302 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000303 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000304 return false;
305
Dan Gohman71c41442010-08-13 20:11:39 +0000306 // This recurrence is invariant w.r.t. QueryLoop if L contains QueryLoop.
307 if (L->contains(QueryLoop))
308 return true;
309
Dan Gohmane890eea2009-06-26 22:17:21 +0000310 // This recurrence is variant w.r.t. QueryLoop if any of its operands
311 // are variant.
312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
313 if (!getOperand(i)->isLoopInvariant(QueryLoop))
314 return false;
315
316 // Otherwise it's loop-invariant.
317 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000318}
319
Dan Gohman39125d82010-02-13 00:19:39 +0000320bool
321SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
322 return DT->dominates(L->getHeader(), BB) &&
323 SCEVNAryExpr::dominates(BB, DT);
324}
325
326bool
327SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
328 // This uses a "dominates" query instead of "properly dominates" query because
329 // the instruction which produces the addrec's value is a PHI, and a PHI
330 // effectively properly dominates its entire containing block.
331 return DT->dominates(L->getHeader(), BB) &&
332 SCEVNAryExpr::properlyDominates(BB, DT);
333}
334
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000335void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000337 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000339 OS << "}<";
340 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
341 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000342}
Chris Lattner53e677a2004-04-02 20:23:17 +0000343
Dan Gohmanab37f502010-08-02 23:49:30 +0000344void SCEVUnknown::deleted() {
345 // Clear this SCEVUnknown from ValuesAtScopes.
346 SE->ValuesAtScopes.erase(this);
347
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
350
351 // Release the value.
352 setValPtr(0);
353}
354
355void SCEVUnknown::allUsesReplacedWith(Value *New) {
356 // Clear this SCEVUnknown from ValuesAtScopes.
357 SE->ValuesAtScopes.erase(this);
358
359 // Remove this SCEVUnknown from the uniquing map.
360 SE->UniqueSCEVs.RemoveNode(this);
361
362 // Update this SCEVUnknown to point to the new value. This is needed
363 // because there may still be outstanding SCEVs which still point to
364 // this SCEVUnknown.
365 setValPtr(New);
366}
367
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000368bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
369 // All non-instruction values are loop invariant. All instructions are loop
370 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000371 // Instructions are never considered invariant in the function body
372 // (null loop) because they are defined within the "loop".
Dan Gohmanab37f502010-08-02 23:49:30 +0000373 if (Instruction *I = dyn_cast<Instruction>(getValue()))
Dan Gohman92329c72009-12-18 01:24:09 +0000374 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375 return true;
376}
Chris Lattner53e677a2004-04-02 20:23:17 +0000377
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000378bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
379 if (Instruction *I = dyn_cast<Instruction>(getValue()))
380 return DT->dominates(I->getParent(), BB);
381 return true;
382}
383
Dan Gohman6e70e312009-09-27 15:26:03 +0000384bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
385 if (Instruction *I = dyn_cast<Instruction>(getValue()))
386 return DT->properlyDominates(I->getParent(), BB);
387 return true;
388}
389
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000390const Type *SCEVUnknown::getType() const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000391 return getValue()->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000392}
Chris Lattner53e677a2004-04-02 20:23:17 +0000393
Dan Gohman0f5efe52010-01-28 02:15:55 +0000394bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000396 if (VCE->getOpcode() == Instruction::PtrToInt)
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000398 if (CE->getOpcode() == Instruction::GetElementPtr &&
399 CE->getOperand(0)->isNullValue() &&
400 CE->getNumOperands() == 2)
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
402 if (CI->isOne()) {
403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
404 ->getElementType();
405 return true;
406 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000407
408 return false;
409}
410
411bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000413 if (VCE->getOpcode() == Instruction::PtrToInt)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000415 if (CE->getOpcode() == Instruction::GetElementPtr &&
416 CE->getOperand(0)->isNullValue()) {
417 const Type *Ty =
418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
419 if (const StructType *STy = dyn_cast<StructType>(Ty))
420 if (!STy->isPacked() &&
421 CE->getNumOperands() == 3 &&
422 CE->getOperand(1)->isNullValue()) {
423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
424 if (CI->isOne() &&
425 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000426 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000427 AllocTy = STy->getElementType(1);
428 return true;
429 }
430 }
431 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000432
433 return false;
434}
435
Dan Gohman4f8eea82010-02-01 18:27:38 +0000436bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(0)->isNullValue() &&
443 CE->getOperand(1)->isNullValue()) {
444 const Type *Ty =
445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
446 // Ignore vector types here so that ScalarEvolutionExpander doesn't
447 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000448 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000449 CTy = Ty;
450 FieldNo = CE->getOperand(2);
451 return true;
452 }
453 }
454
455 return false;
456}
457
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000458void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000459 const Type *AllocTy;
460 if (isSizeOf(AllocTy)) {
461 OS << "sizeof(" << *AllocTy << ")";
462 return;
463 }
464 if (isAlignOf(AllocTy)) {
465 OS << "alignof(" << *AllocTy << ")";
466 return;
467 }
468
Dan Gohman4f8eea82010-02-01 18:27:38 +0000469 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000470 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000471 if (isOffsetOf(CTy, FieldNo)) {
472 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000473 WriteAsOperand(OS, FieldNo, false);
474 OS << ")";
475 return;
476 }
477
478 // Otherwise just print it normally.
Dan Gohmanab37f502010-08-02 23:49:30 +0000479 WriteAsOperand(OS, getValue(), false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000480}
481
Chris Lattner8d741b82004-06-20 06:23:15 +0000482//===----------------------------------------------------------------------===//
483// SCEV Utilities
484//===----------------------------------------------------------------------===//
485
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000486static bool CompareTypes(const Type *A, const Type *B) {
487 if (A->getTypeID() != B->getTypeID())
488 return A->getTypeID() < B->getTypeID();
489 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
490 const IntegerType *BI = cast<IntegerType>(B);
491 return AI->getBitWidth() < BI->getBitWidth();
492 }
493 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
494 const PointerType *BI = cast<PointerType>(B);
495 return CompareTypes(AI->getElementType(), BI->getElementType());
496 }
497 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
498 const ArrayType *BI = cast<ArrayType>(B);
499 if (AI->getNumElements() != BI->getNumElements())
500 return AI->getNumElements() < BI->getNumElements();
501 return CompareTypes(AI->getElementType(), BI->getElementType());
502 }
503 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
504 const VectorType *BI = cast<VectorType>(B);
505 if (AI->getNumElements() != BI->getNumElements())
506 return AI->getNumElements() < BI->getNumElements();
507 return CompareTypes(AI->getElementType(), BI->getElementType());
508 }
509 if (const StructType *AI = dyn_cast<StructType>(A)) {
510 const StructType *BI = cast<StructType>(B);
511 if (AI->getNumElements() != BI->getNumElements())
512 return AI->getNumElements() < BI->getNumElements();
513 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
514 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
515 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
516 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
517 }
518 return false;
519}
520
Chris Lattner8d741b82004-06-20 06:23:15 +0000521namespace {
522 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
523 /// than the complexity of the RHS. This comparator is used to canonicalize
524 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000525 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000526 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000527 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000528 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000529
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000530 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000531 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
532 if (LHS == RHS)
533 return false;
534
Dan Gohman72861302009-05-07 14:39:04 +0000535 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000536 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
537 if (LType != RType)
538 return LType < RType;
Dan Gohman72861302009-05-07 14:39:04 +0000539
Dan Gohman3bf63762010-06-18 19:54:20 +0000540 // Aside from the getSCEVType() ordering, the particular ordering
541 // isn't very important except that it's beneficial to be consistent,
542 // so that (a + b) and (b + a) don't end up as different expressions.
543
544 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
545 // not as complete as it could be.
546 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
547 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000548 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000549
550 // Order pointer values after integer values. This helps SCEVExpander
551 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000552 bool LIsPointer = LV->getType()->isPointerTy(),
553 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000554 if (LIsPointer != RIsPointer)
555 return RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000556
557 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000558 unsigned LID = LV->getValueID(),
559 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000560 if (LID != RID)
561 return LID < RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000562
563 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000564 if (const Argument *LA = dyn_cast<Argument>(LV)) {
565 const Argument *RA = cast<Argument>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000566 return LA->getArgNo() < RA->getArgNo();
567 }
568
569 // For instructions, compare their loop depth, and their opcode.
570 // This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000571 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
572 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000573
574 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000575 const BasicBlock *LParent = LInst->getParent(),
576 *RParent = RInst->getParent();
577 if (LParent != RParent) {
578 unsigned LDepth = LI->getLoopDepth(LParent),
579 RDepth = LI->getLoopDepth(RParent);
580 if (LDepth != RDepth)
581 return LDepth < RDepth;
582 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000583
584 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000585 unsigned LNumOps = LInst->getNumOperands(),
586 RNumOps = RInst->getNumOperands();
Dan Gohman304a7a62010-07-23 21:20:52 +0000587 if (LNumOps != RNumOps)
588 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000589 }
590
591 return false;
592 }
593
594 // Compare constant values.
595 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
596 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000597 const ConstantInt *LCC = LC->getValue();
598 const ConstantInt *RCC = RC->getValue();
599 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
600 if (LBitWidth != RBitWidth)
601 return LBitWidth < RBitWidth;
602 return LCC->getValue().ult(RCC->getValue());
Dan Gohman3bf63762010-06-18 19:54:20 +0000603 }
604
605 // Compare addrec loop depths.
606 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
607 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000608 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
609 if (LLoop != RLoop) {
610 unsigned LDepth = LLoop->getLoopDepth(),
611 RDepth = RLoop->getLoopDepth();
612 if (LDepth != RDepth)
613 return LDepth < RDepth;
614 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000615 }
616
617 // Lexicographically compare n-ary expressions.
618 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
619 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000620 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
621 for (unsigned i = 0; i != LNumOps; ++i) {
622 if (i >= RNumOps)
Dan Gohman3bf63762010-06-18 19:54:20 +0000623 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000624 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
625 if (operator()(LOp, ROp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000626 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000627 if (operator()(ROp, LOp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000628 return false;
629 }
Dan Gohman304a7a62010-07-23 21:20:52 +0000630 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000631 }
632
633 // Lexicographically compare udiv expressions.
634 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
635 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000636 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
637 *RL = RC->getLHS(), *RR = RC->getRHS();
638 if (operator()(LL, RL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000639 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000640 if (operator()(RL, LL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000641 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000642 if (operator()(LR, RR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000643 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000644 if (operator()(RR, LR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000645 return false;
646 return false;
647 }
648
649 // Compare cast expressions by operand.
650 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
651 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
652 return operator()(LC->getOperand(), RC->getOperand());
653 }
654
655 llvm_unreachable("Unknown SCEV kind!");
656 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000657 }
658 };
659}
660
661/// GroupByComplexity - Given a list of SCEV objects, order them by their
662/// complexity, and group objects of the same complexity together by value.
663/// When this routine is finished, we know that any duplicates in the vector are
664/// consecutive and that complexity is monotonically increasing.
665///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000666/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000667/// results from this routine. In other words, we don't want the results of
668/// this to depend on where the addresses of various SCEV objects happened to
669/// land in memory.
670///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000671static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000672 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000673 if (Ops.size() < 2) return; // Noop
674 if (Ops.size() == 2) {
675 // This is the common case, which also happens to be trivially simple.
676 // Special case it.
Dan Gohman3bf63762010-06-18 19:54:20 +0000677 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000678 std::swap(Ops[0], Ops[1]);
679 return;
680 }
681
Dan Gohman3bf63762010-06-18 19:54:20 +0000682 // Do the rough sort by complexity.
683 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
684
685 // Now that we are sorted by complexity, group elements of the same
686 // complexity. Note that this is, at worst, N^2, but the vector is likely to
687 // be extremely short in practice. Note that we take this approach because we
688 // do not want to depend on the addresses of the objects we are grouping.
689 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
690 const SCEV *S = Ops[i];
691 unsigned Complexity = S->getSCEVType();
692
693 // If there are any objects of the same complexity and same value as this
694 // one, group them.
695 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
696 if (Ops[j] == S) { // Found a duplicate.
697 // Move it to immediately after i'th element.
698 std::swap(Ops[i+1], Ops[j]);
699 ++i; // no need to rescan it.
700 if (i == e-2) return; // Done!
701 }
702 }
703 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000704}
705
Chris Lattner53e677a2004-04-02 20:23:17 +0000706
Chris Lattner53e677a2004-04-02 20:23:17 +0000707
708//===----------------------------------------------------------------------===//
709// Simple SCEV method implementations
710//===----------------------------------------------------------------------===//
711
Eli Friedmanb42a6262008-08-04 23:49:06 +0000712/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000713/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000714static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000715 ScalarEvolution &SE,
716 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000717 // Handle the simplest case efficiently.
718 if (K == 1)
719 return SE.getTruncateOrZeroExtend(It, ResultTy);
720
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000721 // We are using the following formula for BC(It, K):
722 //
723 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
724 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000725 // Suppose, W is the bitwidth of the return value. We must be prepared for
726 // overflow. Hence, we must assure that the result of our computation is
727 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
728 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000729 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000731 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000732 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
733 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000734 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000735 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000736 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000737 // This formula is trivially equivalent to the previous formula. However,
738 // this formula can be implemented much more efficiently. The trick is that
739 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
740 // arithmetic. To do exact division in modular arithmetic, all we have
741 // to do is multiply by the inverse. Therefore, this step can be done at
742 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000743 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000744 // The next issue is how to safely do the division by 2^T. The way this
745 // is done is by doing the multiplication step at a width of at least W + T
746 // bits. This way, the bottom W+T bits of the product are accurate. Then,
747 // when we perform the division by 2^T (which is equivalent to a right shift
748 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
749 // truncated out after the division by 2^T.
750 //
751 // In comparison to just directly using the first formula, this technique
752 // is much more efficient; using the first formula requires W * K bits,
753 // but this formula less than W + K bits. Also, the first formula requires
754 // a division step, whereas this formula only requires multiplies and shifts.
755 //
756 // It doesn't matter whether the subtraction step is done in the calculation
757 // width or the input iteration count's width; if the subtraction overflows,
758 // the result must be zero anyway. We prefer here to do it in the width of
759 // the induction variable because it helps a lot for certain cases; CodeGen
760 // isn't smart enough to ignore the overflow, which leads to much less
761 // efficient code if the width of the subtraction is wider than the native
762 // register width.
763 //
764 // (It's possible to not widen at all by pulling out factors of 2 before
765 // the multiplication; for example, K=2 can be calculated as
766 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
767 // extra arithmetic, so it's not an obvious win, and it gets
768 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000769
Eli Friedmanb42a6262008-08-04 23:49:06 +0000770 // Protection from insane SCEVs; this bound is conservative,
771 // but it probably doesn't matter.
772 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000773 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000774
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000775 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000776
Eli Friedmanb42a6262008-08-04 23:49:06 +0000777 // Calculate K! / 2^T and T; we divide out the factors of two before
778 // multiplying for calculating K! / 2^T to avoid overflow.
779 // Other overflow doesn't matter because we only care about the bottom
780 // W bits of the result.
781 APInt OddFactorial(W, 1);
782 unsigned T = 1;
783 for (unsigned i = 3; i <= K; ++i) {
784 APInt Mult(W, i);
785 unsigned TwoFactors = Mult.countTrailingZeros();
786 T += TwoFactors;
787 Mult = Mult.lshr(TwoFactors);
788 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000790
Eli Friedmanb42a6262008-08-04 23:49:06 +0000791 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000792 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000793
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000794 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000795 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
796
797 // Calculate the multiplicative inverse of K! / 2^T;
798 // this multiplication factor will perform the exact division by
799 // K! / 2^T.
800 APInt Mod = APInt::getSignedMinValue(W+1);
801 APInt MultiplyFactor = OddFactorial.zext(W+1);
802 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
803 MultiplyFactor = MultiplyFactor.trunc(W);
804
805 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000806 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
807 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000808 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000809 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000810 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000811 Dividend = SE.getMulExpr(Dividend,
812 SE.getTruncateOrZeroExtend(S, CalculationTy));
813 }
814
815 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000816 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000817
818 // Truncate the result, and divide by K! / 2^T.
819
820 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
821 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000822}
823
Chris Lattner53e677a2004-04-02 20:23:17 +0000824/// evaluateAtIteration - Return the value of this chain of recurrences at
825/// the specified iteration number. We can evaluate this recurrence by
826/// multiplying each element in the chain by the binomial coefficient
827/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
828///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000829/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000830///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000831/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000832///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000833const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000834 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000835 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000836 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000837 // The computation is correct in the face of overflow provided that the
838 // multiplication is performed _after_ the evaluation of the binomial
839 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000841 if (isa<SCEVCouldNotCompute>(Coeff))
842 return Coeff;
843
844 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000845 }
846 return Result;
847}
848
Chris Lattner53e677a2004-04-02 20:23:17 +0000849//===----------------------------------------------------------------------===//
850// SCEV Expression folder implementations
851//===----------------------------------------------------------------------===//
852
Dan Gohman0bba49c2009-07-07 17:06:11 +0000853const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000854 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000855 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000856 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000857 assert(isSCEVable(Ty) &&
858 "This is not a conversion to a SCEVable type!");
859 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000860
Dan Gohmanc050fd92009-07-13 20:50:19 +0000861 FoldingSetNodeID ID;
862 ID.AddInteger(scTruncate);
863 ID.AddPointer(Op);
864 ID.AddPointer(Ty);
865 void *IP = 0;
866 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
867
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000868 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000869 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000870 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000871 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
872 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000873
Dan Gohman20900ca2009-04-22 16:20:48 +0000874 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000875 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000876 return getTruncateExpr(ST->getOperand(), Ty);
877
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000878 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000879 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000880 return getTruncateOrSignExtend(SS->getOperand(), Ty);
881
882 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000883 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000884 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
885
Dan Gohman6864db62009-06-18 16:24:47 +0000886 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000887 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000888 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000889 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000890 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
891 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000892 }
893
Dan Gohmanf53462d2010-07-15 20:02:11 +0000894 // As a special case, fold trunc(undef) to undef. We don't want to
895 // know too much about SCEVUnknowns, but this special case is handy
896 // and harmless.
897 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
898 if (isa<UndefValue>(U->getValue()))
899 return getSCEV(UndefValue::get(Ty));
900
Dan Gohman420ab912010-06-25 18:47:08 +0000901 // The cast wasn't folded; create an explicit cast node. We can reuse
902 // the existing insert position since if we get here, we won't have
903 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000904 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
905 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000906 UniqueSCEVs.InsertNode(S, IP);
907 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000908}
909
Dan Gohman0bba49c2009-07-07 17:06:11 +0000910const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000911 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000912 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000913 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000914 assert(isSCEVable(Ty) &&
915 "This is not a conversion to a SCEVable type!");
916 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000917
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000918 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000919 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
920 return getConstant(
921 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
922 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000923
Dan Gohman20900ca2009-04-22 16:20:48 +0000924 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000925 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000926 return getZeroExtendExpr(SZ->getOperand(), Ty);
927
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000928 // Before doing any expensive analysis, check to see if we've already
929 // computed a SCEV for this Op and Ty.
930 FoldingSetNodeID ID;
931 ID.AddInteger(scZeroExtend);
932 ID.AddPointer(Op);
933 ID.AddPointer(Ty);
934 void *IP = 0;
935 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
936
Dan Gohman01ecca22009-04-27 20:16:15 +0000937 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000938 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000939 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000940 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000941 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000942 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000943 const SCEV *Start = AR->getStart();
944 const SCEV *Step = AR->getStepRecurrence(*this);
945 unsigned BitWidth = getTypeSizeInBits(AR->getType());
946 const Loop *L = AR->getLoop();
947
Dan Gohmaneb490a72009-07-25 01:22:26 +0000948 // If we have special knowledge that this addrec won't overflow,
949 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000950 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000951 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
952 getZeroExtendExpr(Step, Ty),
953 L);
954
Dan Gohman01ecca22009-04-27 20:16:15 +0000955 // Check whether the backedge-taken count is SCEVCouldNotCompute.
956 // Note that this serves two purposes: It filters out loops that are
957 // simply not analyzable, and it covers the case where this code is
958 // being called from within backedge-taken count analysis, such that
959 // attempting to ask for the backedge-taken count would likely result
960 // in infinite recursion. In the later case, the analysis code will
961 // cope with a conservative value, and it will take care to purge
962 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000963 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000964 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000965 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000966 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000967
968 // Check whether the backedge-taken count can be losslessly casted to
969 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000970 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000971 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000972 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000973 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
974 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000975 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000976 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000977 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000978 const SCEV *Add = getAddExpr(Start, ZMul);
979 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000980 getAddExpr(getZeroExtendExpr(Start, WideTy),
981 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
982 getZeroExtendExpr(Step, WideTy)));
983 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000984 // Return the expression with the addrec on the outside.
985 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
986 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000987 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000988
989 // Similar to above, only this time treat the step value as signed.
990 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000991 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000992 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000993 OperandExtendedAdd =
994 getAddExpr(getZeroExtendExpr(Start, WideTy),
995 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
996 getSignExtendExpr(Step, WideTy)));
997 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000998 // Return the expression with the addrec on the outside.
999 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1000 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001001 L);
1002 }
1003
1004 // If the backedge is guarded by a comparison with the pre-inc value
1005 // the addrec is safe. Also, if the entry is guarded by a comparison
1006 // with the start value and the backedge is guarded by a comparison
1007 // with the post-inc value, the addrec is safe.
1008 if (isKnownPositive(Step)) {
1009 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1010 getUnsignedRange(Step).getUnsignedMax());
1011 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001012 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001013 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1014 AR->getPostIncExpr(*this), N)))
1015 // Return the expression with the addrec on the outside.
1016 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1017 getZeroExtendExpr(Step, Ty),
1018 L);
1019 } else if (isKnownNegative(Step)) {
1020 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1021 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +00001022 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1023 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001024 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1025 AR->getPostIncExpr(*this), N)))
1026 // Return the expression with the addrec on the outside.
1027 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1028 getSignExtendExpr(Step, Ty),
1029 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001030 }
1031 }
1032 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001033
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001034 // The cast wasn't folded; create an explicit cast node.
1035 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001036 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001037 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1038 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001039 UniqueSCEVs.InsertNode(S, IP);
1040 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001041}
1042
Dan Gohman0bba49c2009-07-07 17:06:11 +00001043const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001044 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001045 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001046 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001047 assert(isSCEVable(Ty) &&
1048 "This is not a conversion to a SCEVable type!");
1049 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001050
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001051 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001052 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1053 return getConstant(
1054 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1055 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001056
Dan Gohman20900ca2009-04-22 16:20:48 +00001057 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001058 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001059 return getSignExtendExpr(SS->getOperand(), Ty);
1060
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001061 // Before doing any expensive analysis, check to see if we've already
1062 // computed a SCEV for this Op and Ty.
1063 FoldingSetNodeID ID;
1064 ID.AddInteger(scSignExtend);
1065 ID.AddPointer(Op);
1066 ID.AddPointer(Ty);
1067 void *IP = 0;
1068 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1069
Dan Gohman01ecca22009-04-27 20:16:15 +00001070 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001071 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001072 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001073 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001074 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001075 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001076 const SCEV *Start = AR->getStart();
1077 const SCEV *Step = AR->getStepRecurrence(*this);
1078 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1079 const Loop *L = AR->getLoop();
1080
Dan Gohmaneb490a72009-07-25 01:22:26 +00001081 // If we have special knowledge that this addrec won't overflow,
1082 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001083 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001084 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1085 getSignExtendExpr(Step, Ty),
1086 L);
1087
Dan Gohman01ecca22009-04-27 20:16:15 +00001088 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1089 // Note that this serves two purposes: It filters out loops that are
1090 // simply not analyzable, and it covers the case where this code is
1091 // being called from within backedge-taken count analysis, such that
1092 // attempting to ask for the backedge-taken count would likely result
1093 // in infinite recursion. In the later case, the analysis code will
1094 // cope with a conservative value, and it will take care to purge
1095 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001096 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001097 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001098 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001099 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001100
1101 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001102 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001103 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001104 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001105 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001106 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1107 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001108 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001109 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001110 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001111 const SCEV *Add = getAddExpr(Start, SMul);
1112 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001113 getAddExpr(getSignExtendExpr(Start, WideTy),
1114 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1115 getSignExtendExpr(Step, WideTy)));
1116 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001117 // Return the expression with the addrec on the outside.
1118 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1119 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001120 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001121
1122 // Similar to above, only this time treat the step value as unsigned.
1123 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001124 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001125 Add = getAddExpr(Start, UMul);
1126 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001127 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001128 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1129 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001130 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001131 // Return the expression with the addrec on the outside.
1132 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1133 getZeroExtendExpr(Step, Ty),
1134 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001135 }
1136
1137 // If the backedge is guarded by a comparison with the pre-inc value
1138 // the addrec is safe. Also, if the entry is guarded by a comparison
1139 // with the start value and the backedge is guarded by a comparison
1140 // with the post-inc value, the addrec is safe.
1141 if (isKnownPositive(Step)) {
1142 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1143 getSignedRange(Step).getSignedMax());
1144 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001145 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001146 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1147 AR->getPostIncExpr(*this), N)))
1148 // Return the expression with the addrec on the outside.
1149 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1150 getSignExtendExpr(Step, Ty),
1151 L);
1152 } else if (isKnownNegative(Step)) {
1153 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1154 getSignedRange(Step).getSignedMin());
1155 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001156 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001157 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1158 AR->getPostIncExpr(*this), N)))
1159 // Return the expression with the addrec on the outside.
1160 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1161 getSignExtendExpr(Step, Ty),
1162 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001163 }
1164 }
1165 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001166
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001167 // The cast wasn't folded; create an explicit cast node.
1168 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001169 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001170 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1171 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001172 UniqueSCEVs.InsertNode(S, IP);
1173 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001174}
1175
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001176/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1177/// unspecified bits out to the given type.
1178///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001179const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001180 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001181 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1182 "This is not an extending conversion!");
1183 assert(isSCEVable(Ty) &&
1184 "This is not a conversion to a SCEVable type!");
1185 Ty = getEffectiveSCEVType(Ty);
1186
1187 // Sign-extend negative constants.
1188 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1189 if (SC->getValue()->getValue().isNegative())
1190 return getSignExtendExpr(Op, Ty);
1191
1192 // Peel off a truncate cast.
1193 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001194 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001195 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1196 return getAnyExtendExpr(NewOp, Ty);
1197 return getTruncateOrNoop(NewOp, Ty);
1198 }
1199
1200 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001201 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001202 if (!isa<SCEVZeroExtendExpr>(ZExt))
1203 return ZExt;
1204
1205 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001206 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001207 if (!isa<SCEVSignExtendExpr>(SExt))
1208 return SExt;
1209
Dan Gohmana10756e2010-01-21 02:09:26 +00001210 // Force the cast to be folded into the operands of an addrec.
1211 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1212 SmallVector<const SCEV *, 4> Ops;
1213 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1214 I != E; ++I)
1215 Ops.push_back(getAnyExtendExpr(*I, Ty));
1216 return getAddRecExpr(Ops, AR->getLoop());
1217 }
1218
Dan Gohmanf53462d2010-07-15 20:02:11 +00001219 // As a special case, fold anyext(undef) to undef. We don't want to
1220 // know too much about SCEVUnknowns, but this special case is handy
1221 // and harmless.
1222 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1223 if (isa<UndefValue>(U->getValue()))
1224 return getSCEV(UndefValue::get(Ty));
1225
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001226 // If the expression is obviously signed, use the sext cast value.
1227 if (isa<SCEVSMaxExpr>(Op))
1228 return SExt;
1229
1230 // Absent any other information, use the zext cast value.
1231 return ZExt;
1232}
1233
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001234/// CollectAddOperandsWithScales - Process the given Ops list, which is
1235/// a list of operands to be added under the given scale, update the given
1236/// map. This is a helper function for getAddRecExpr. As an example of
1237/// what it does, given a sequence of operands that would form an add
1238/// expression like this:
1239///
1240/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1241///
1242/// where A and B are constants, update the map with these values:
1243///
1244/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1245///
1246/// and add 13 + A*B*29 to AccumulatedConstant.
1247/// This will allow getAddRecExpr to produce this:
1248///
1249/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1250///
1251/// This form often exposes folding opportunities that are hidden in
1252/// the original operand list.
1253///
1254/// Return true iff it appears that any interesting folding opportunities
1255/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1256/// the common case where no interesting opportunities are present, and
1257/// is also used as a check to avoid infinite recursion.
1258///
1259static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001260CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1261 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001262 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001263 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001264 const APInt &Scale,
1265 ScalarEvolution &SE) {
1266 bool Interesting = false;
1267
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001268 // Iterate over the add operands. They are sorted, with constants first.
1269 unsigned i = 0;
1270 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1271 ++i;
1272 // Pull a buried constant out to the outside.
1273 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1274 Interesting = true;
1275 AccumulatedConstant += Scale * C->getValue()->getValue();
1276 }
1277
1278 // Next comes everything else. We're especially interested in multiplies
1279 // here, but they're in the middle, so just visit the rest with one loop.
1280 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001281 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1282 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1283 APInt NewScale =
1284 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1285 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1286 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001287 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001288 Interesting |=
1289 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001290 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001291 NewScale, SE);
1292 } else {
1293 // A multiplication of a constant with some other value. Update
1294 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001295 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1296 const SCEV *Key = SE.getMulExpr(MulOps);
1297 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001298 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001299 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001300 NewOps.push_back(Pair.first->first);
1301 } else {
1302 Pair.first->second += NewScale;
1303 // The map already had an entry for this value, which may indicate
1304 // a folding opportunity.
1305 Interesting = true;
1306 }
1307 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001308 } else {
1309 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001310 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001311 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001312 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001313 NewOps.push_back(Pair.first->first);
1314 } else {
1315 Pair.first->second += Scale;
1316 // The map already had an entry for this value, which may indicate
1317 // a folding opportunity.
1318 Interesting = true;
1319 }
1320 }
1321 }
1322
1323 return Interesting;
1324}
1325
1326namespace {
1327 struct APIntCompare {
1328 bool operator()(const APInt &LHS, const APInt &RHS) const {
1329 return LHS.ult(RHS);
1330 }
1331 };
1332}
1333
Dan Gohman6c0866c2009-05-24 23:45:28 +00001334/// getAddExpr - Get a canonical add expression, or something simpler if
1335/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001336const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1337 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001339 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001340#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001341 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001342 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001343 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001344 "SCEVAddExpr operand types don't match!");
1345#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001346
Dan Gohmana10756e2010-01-21 02:09:26 +00001347 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1348 if (!HasNUW && HasNSW) {
1349 bool All = true;
1350 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1351 if (!isKnownNonNegative(Ops[i])) {
1352 All = false;
1353 break;
1354 }
1355 if (All) HasNUW = true;
1356 }
1357
Chris Lattner53e677a2004-04-02 20:23:17 +00001358 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001359 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001360
1361 // If there are any constants, fold them together.
1362 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001363 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001365 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001366 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001367 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001368 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1369 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001370 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001371 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001372 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001373 }
1374
1375 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001376 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 Ops.erase(Ops.begin());
1378 --Idx;
1379 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001380
Dan Gohmanbca091d2010-04-12 23:08:18 +00001381 if (Ops.size() == 1) return Ops[0];
1382 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001383
Chris Lattner53e677a2004-04-02 20:23:17 +00001384 // Okay, check to see if the same value occurs in the operand list twice. If
1385 // so, merge them together into an multiply expression. Since we sorted the
1386 // list, these values are required to be adjacent.
1387 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001388 bool FoundMatch = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1390 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1391 // Found a match, merge the two values into a multiply, and add any
1392 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001393 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman58a85b92010-08-13 20:17:14 +00001394 const SCEV *Mul = getMulExpr(Two, Ops[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 if (Ops.size() == 2)
1396 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001397 Ops[i] = Mul;
1398 Ops.erase(Ops.begin()+i+1);
1399 --i; --e;
1400 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001402 if (FoundMatch)
1403 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001404
Dan Gohman728c7f32009-05-08 21:03:19 +00001405 // Check for truncates. If all the operands are truncated from the same
1406 // type, see if factoring out the truncate would permit the result to be
1407 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1408 // if the contents of the resulting outer trunc fold to something simple.
1409 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1410 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1411 const Type *DstType = Trunc->getType();
1412 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001413 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001414 bool Ok = true;
1415 // Check all the operands to see if they can be represented in the
1416 // source type of the truncate.
1417 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1418 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1419 if (T->getOperand()->getType() != SrcType) {
1420 Ok = false;
1421 break;
1422 }
1423 LargeOps.push_back(T->getOperand());
1424 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001425 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001426 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001427 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001428 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1429 if (const SCEVTruncateExpr *T =
1430 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1431 if (T->getOperand()->getType() != SrcType) {
1432 Ok = false;
1433 break;
1434 }
1435 LargeMulOps.push_back(T->getOperand());
1436 } else if (const SCEVConstant *C =
1437 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001438 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001439 } else {
1440 Ok = false;
1441 break;
1442 }
1443 }
1444 if (Ok)
1445 LargeOps.push_back(getMulExpr(LargeMulOps));
1446 } else {
1447 Ok = false;
1448 break;
1449 }
1450 }
1451 if (Ok) {
1452 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001453 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001454 // If it folds to something simple, use it. Otherwise, don't.
1455 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1456 return getTruncateExpr(Fold, DstType);
1457 }
1458 }
1459
1460 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001461 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1462 ++Idx;
1463
1464 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 if (Idx < Ops.size()) {
1466 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001467 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 // If we have an add, expand the add operands onto the end of the operands
1469 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001471 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001472 DeletedAdd = true;
1473 }
1474
1475 // If we deleted at least one add, we added operands to the end of the list,
1476 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001477 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001478 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001479 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 }
1481
1482 // Skip over the add expression until we get to a multiply.
1483 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1484 ++Idx;
1485
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001486 // Check to see if there are any folding opportunities present with
1487 // operands multiplied by constant values.
1488 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1489 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001490 DenseMap<const SCEV *, APInt> M;
1491 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001492 APInt AccumulatedConstant(BitWidth, 0);
1493 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001494 Ops.data(), Ops.size(),
1495 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001496 // Some interesting folding opportunity is present, so its worthwhile to
1497 // re-generate the operands list. Group the operands by constant scale,
1498 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001499 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1500 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001501 E = NewOps.end(); I != E; ++I)
1502 MulOpLists[M.find(*I)->second].push_back(*I);
1503 // Re-generate the operands list.
1504 Ops.clear();
1505 if (AccumulatedConstant != 0)
1506 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001507 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1508 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001509 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001510 Ops.push_back(getMulExpr(getConstant(I->first),
1511 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001512 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001513 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001514 if (Ops.size() == 1)
1515 return Ops[0];
1516 return getAddExpr(Ops);
1517 }
1518 }
1519
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 // If we are adding something to a multiply expression, make sure the
1521 // something is not already an operand of the multiply. If so, merge it into
1522 // the multiply.
1523 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001524 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001525 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001526 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001527 if (isa<SCEVConstant>(MulOpSCEV))
1528 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001529 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001530 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001531 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001532 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 if (Mul->getNumOperands() != 2) {
1534 // If the multiply has more than two operands, we must get the
1535 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001536 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001538 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001540 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001541 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001542 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 if (Ops.size() == 2) return OuterMul;
1544 if (AddOp < Idx) {
1545 Ops.erase(Ops.begin()+AddOp);
1546 Ops.erase(Ops.begin()+Idx-1);
1547 } else {
1548 Ops.erase(Ops.begin()+Idx);
1549 Ops.erase(Ops.begin()+AddOp-1);
1550 }
1551 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001552 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001553 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001554
Chris Lattner53e677a2004-04-02 20:23:17 +00001555 // Check this multiply against other multiplies being added together.
Dan Gohman727356f2010-08-12 15:00:23 +00001556 bool AnyFold = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 for (unsigned OtherMulIdx = Idx+1;
1558 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1559 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001560 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001561 // If MulOp occurs in OtherMul, we can fold the two multiplies
1562 // together.
1563 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1564 OMulOp != e; ++OMulOp)
1565 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1566 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001567 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001569 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1570 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001571 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001572 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001573 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001574 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001576 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1577 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001578 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001579 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001581 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1582 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001583 if (Ops.size() == 2) return OuterMul;
Dan Gohman727356f2010-08-12 15:00:23 +00001584 Ops[Idx] = OuterMul;
1585 Ops.erase(Ops.begin()+OtherMulIdx);
1586 OtherMulIdx = Idx;
1587 AnyFold = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001588 }
1589 }
Dan Gohman727356f2010-08-12 15:00:23 +00001590 if (AnyFold)
1591 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001592 }
1593 }
1594
1595 // If there are any add recurrences in the operands list, see if any other
1596 // added values are loop invariant. If so, we can fold them into the
1597 // recurrence.
1598 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1599 ++Idx;
1600
1601 // Scan over all recurrences, trying to fold loop invariants into them.
1602 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1603 // Scan all of the other operands to this add and add them to the vector if
1604 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001605 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001606 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001607 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001608 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001609 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001610 LIOps.push_back(Ops[i]);
1611 Ops.erase(Ops.begin()+i);
1612 --i; --e;
1613 }
1614
1615 // If we found some loop invariants, fold them into the recurrence.
1616 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001617 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001618 LIOps.push_back(AddRec->getStart());
1619
Dan Gohman0bba49c2009-07-07 17:06:11 +00001620 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001621 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001622 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001623
Dan Gohmanb9f96512010-06-30 07:16:37 +00001624 // Build the new addrec. Propagate the NUW and NSW flags if both the
1625 // outer add and the inner addrec are guaranteed to have no overflow.
1626 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1627 HasNUW && AddRec->hasNoUnsignedWrap(),
1628 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001629
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 // If all of the other operands were loop invariant, we are done.
1631 if (Ops.size() == 1) return NewRec;
1632
1633 // Otherwise, add the folded AddRec by the non-liv parts.
1634 for (unsigned i = 0;; ++i)
1635 if (Ops[i] == AddRec) {
1636 Ops[i] = NewRec;
1637 break;
1638 }
Dan Gohman246b2562007-10-22 18:31:58 +00001639 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001640 }
1641
1642 // Okay, if there weren't any loop invariants to be folded, check to see if
1643 // there are multiple AddRec's with the same loop induction variable being
1644 // added together. If so, we can fold them.
1645 for (unsigned OtherIdx = Idx+1;
1646 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1647 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001648 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001649 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001651 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1652 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1654 if (i >= NewOps.size()) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001655 NewOps.append(OtherAddRec->op_begin()+i,
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 OtherAddRec->op_end());
1657 break;
1658 }
Dan Gohman246b2562007-10-22 18:31:58 +00001659 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001660 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001661 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001662
1663 if (Ops.size() == 2) return NewAddRec;
1664
1665 Ops.erase(Ops.begin()+Idx);
1666 Ops.erase(Ops.begin()+OtherIdx-1);
1667 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001668 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001669 }
1670 }
1671
1672 // Otherwise couldn't fold anything into this recurrence. Move onto the
1673 // next one.
1674 }
1675
1676 // Okay, it looks like we really DO need an add expr. Check to see if we
1677 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001678 FoldingSetNodeID ID;
1679 ID.AddInteger(scAddExpr);
1680 ID.AddInteger(Ops.size());
1681 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1682 ID.AddPointer(Ops[i]);
1683 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001684 SCEVAddExpr *S =
1685 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1686 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001687 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1688 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001689 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1690 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001691 UniqueSCEVs.InsertNode(S, IP);
1692 }
Dan Gohman3645b012009-10-09 00:10:36 +00001693 if (HasNUW) S->setHasNoUnsignedWrap(true);
1694 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001695 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001696}
1697
Dan Gohman6c0866c2009-05-24 23:45:28 +00001698/// getMulExpr - Get a canonical multiply expression, or something simpler if
1699/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001700const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1701 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001702 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001703 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001704#ifndef NDEBUG
1705 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1706 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1707 getEffectiveSCEVType(Ops[0]->getType()) &&
1708 "SCEVMulExpr operand types don't match!");
1709#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001710
Dan Gohmana10756e2010-01-21 02:09:26 +00001711 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1712 if (!HasNUW && HasNSW) {
1713 bool All = true;
1714 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1715 if (!isKnownNonNegative(Ops[i])) {
1716 All = false;
1717 break;
1718 }
1719 if (All) HasNUW = true;
1720 }
1721
Chris Lattner53e677a2004-04-02 20:23:17 +00001722 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001723 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001724
1725 // If there are any constants, fold them together.
1726 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001727 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001728
1729 // C1*(C2+V) -> C1*C2 + C1*V
1730 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001731 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001732 if (Add->getNumOperands() == 2 &&
1733 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001734 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1735 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001736
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001738 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001739 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001740 ConstantInt *Fold = ConstantInt::get(getContext(),
1741 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001742 RHSC->getValue()->getValue());
1743 Ops[0] = getConstant(Fold);
1744 Ops.erase(Ops.begin()+1); // Erase the folded element
1745 if (Ops.size() == 1) return Ops[0];
1746 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001747 }
1748
1749 // If we are left with a constant one being multiplied, strip it off.
1750 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1751 Ops.erase(Ops.begin());
1752 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001753 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001754 // If we have a multiply of zero, it will always be zero.
1755 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001756 } else if (Ops[0]->isAllOnesValue()) {
1757 // If we have a mul by -1 of an add, try distributing the -1 among the
1758 // add operands.
1759 if (Ops.size() == 2)
1760 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1761 SmallVector<const SCEV *, 4> NewOps;
1762 bool AnyFolded = false;
1763 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1764 I != E; ++I) {
1765 const SCEV *Mul = getMulExpr(Ops[0], *I);
1766 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1767 NewOps.push_back(Mul);
1768 }
1769 if (AnyFolded)
1770 return getAddExpr(NewOps);
1771 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001772 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001773
1774 if (Ops.size() == 1)
1775 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001776 }
1777
1778 // Skip over the add expression until we get to a multiply.
1779 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1780 ++Idx;
1781
Chris Lattner53e677a2004-04-02 20:23:17 +00001782 // If there are mul operands inline them all into this expression.
1783 if (Idx < Ops.size()) {
1784 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001785 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 // If we have an mul, expand the mul operands onto the end of the operands
1787 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001788 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001789 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001790 DeletedMul = true;
1791 }
1792
1793 // If we deleted at least one mul, we added operands to the end of the list,
1794 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001795 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001796 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001797 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001798 }
1799
1800 // If there are any add recurrences in the operands list, see if any other
1801 // added values are loop invariant. If so, we can fold them into the
1802 // recurrence.
1803 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1804 ++Idx;
1805
1806 // Scan over all recurrences, trying to fold loop invariants into them.
1807 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1808 // Scan all of the other operands to this mul and add them to the vector if
1809 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001810 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001811 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001812 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1813 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1814 LIOps.push_back(Ops[i]);
1815 Ops.erase(Ops.begin()+i);
1816 --i; --e;
1817 }
1818
1819 // If we found some loop invariants, fold them into the recurrence.
1820 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001821 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001822 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001823 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001824 const SCEV *Scale = getMulExpr(LIOps);
1825 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1826 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001827
Dan Gohmanb9f96512010-06-30 07:16:37 +00001828 // Build the new addrec. Propagate the NUW and NSW flags if both the
1829 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00001830 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1831 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001832 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001833
1834 // If all of the other operands were loop invariant, we are done.
1835 if (Ops.size() == 1) return NewRec;
1836
1837 // Otherwise, multiply the folded AddRec by the non-liv parts.
1838 for (unsigned i = 0;; ++i)
1839 if (Ops[i] == AddRec) {
1840 Ops[i] = NewRec;
1841 break;
1842 }
Dan Gohman246b2562007-10-22 18:31:58 +00001843 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001844 }
1845
1846 // Okay, if there weren't any loop invariants to be folded, check to see if
1847 // there are multiple AddRec's with the same loop induction variable being
1848 // multiplied together. If so, we can fold them.
1849 for (unsigned OtherIdx = Idx+1;
1850 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1851 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001852 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001853 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1854 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001855 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001856 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001857 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001858 const SCEV *B = F->getStepRecurrence(*this);
1859 const SCEV *D = G->getStepRecurrence(*this);
1860 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001861 getMulExpr(G, B),
1862 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001863 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001864 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001865 if (Ops.size() == 2) return NewAddRec;
1866
1867 Ops.erase(Ops.begin()+Idx);
1868 Ops.erase(Ops.begin()+OtherIdx-1);
1869 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001870 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001871 }
1872 }
1873
1874 // Otherwise couldn't fold anything into this recurrence. Move onto the
1875 // next one.
1876 }
1877
1878 // Okay, it looks like we really DO need an mul expr. Check to see if we
1879 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001880 FoldingSetNodeID ID;
1881 ID.AddInteger(scMulExpr);
1882 ID.AddInteger(Ops.size());
1883 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1884 ID.AddPointer(Ops[i]);
1885 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001886 SCEVMulExpr *S =
1887 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1888 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001889 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1890 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001891 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1892 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001893 UniqueSCEVs.InsertNode(S, IP);
1894 }
Dan Gohman3645b012009-10-09 00:10:36 +00001895 if (HasNUW) S->setHasNoUnsignedWrap(true);
1896 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001897 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001898}
1899
Andreas Bolka8a11c982009-08-07 22:55:26 +00001900/// getUDivExpr - Get a canonical unsigned division expression, or something
1901/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001902const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1903 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001904 assert(getEffectiveSCEVType(LHS->getType()) ==
1905 getEffectiveSCEVType(RHS->getType()) &&
1906 "SCEVUDivExpr operand types don't match!");
1907
Dan Gohman622ed672009-05-04 22:02:23 +00001908 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001909 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001910 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001911 // If the denominator is zero, the result of the udiv is undefined. Don't
1912 // try to analyze it, because the resolution chosen here may differ from
1913 // the resolution chosen in other parts of the compiler.
1914 if (!RHSC->getValue()->isZero()) {
1915 // Determine if the division can be folded into the operands of
1916 // its operands.
1917 // TODO: Generalize this to non-constants by using known-bits information.
1918 const Type *Ty = LHS->getType();
1919 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001920 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001921 // For non-power-of-two values, effectively round the value up to the
1922 // nearest power of two.
1923 if (!RHSC->getValue()->getValue().isPowerOf2())
1924 ++MaxShiftAmt;
1925 const IntegerType *ExtTy =
1926 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1927 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1928 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1929 if (const SCEVConstant *Step =
1930 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1931 if (!Step->getValue()->getValue()
1932 .urem(RHSC->getValue()->getValue()) &&
1933 getZeroExtendExpr(AR, ExtTy) ==
1934 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1935 getZeroExtendExpr(Step, ExtTy),
1936 AR->getLoop())) {
1937 SmallVector<const SCEV *, 4> Operands;
1938 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1939 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1940 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001941 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001942 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1943 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1944 SmallVector<const SCEV *, 4> Operands;
1945 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1946 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1947 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1948 // Find an operand that's safely divisible.
1949 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1950 const SCEV *Op = M->getOperand(i);
1951 const SCEV *Div = getUDivExpr(Op, RHSC);
1952 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1953 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1954 M->op_end());
1955 Operands[i] = Div;
1956 return getMulExpr(Operands);
1957 }
1958 }
Dan Gohman185cf032009-05-08 20:18:49 +00001959 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001960 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1961 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1962 SmallVector<const SCEV *, 4> Operands;
1963 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1964 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1965 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1966 Operands.clear();
1967 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1968 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1969 if (isa<SCEVUDivExpr>(Op) ||
1970 getMulExpr(Op, RHS) != A->getOperand(i))
1971 break;
1972 Operands.push_back(Op);
1973 }
1974 if (Operands.size() == A->getNumOperands())
1975 return getAddExpr(Operands);
1976 }
1977 }
Dan Gohman185cf032009-05-08 20:18:49 +00001978
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001979 // Fold if both operands are constant.
1980 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1981 Constant *LHSCV = LHSC->getValue();
1982 Constant *RHSCV = RHSC->getValue();
1983 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1984 RHSCV)));
1985 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001986 }
1987 }
1988
Dan Gohman1c343752009-06-27 21:21:31 +00001989 FoldingSetNodeID ID;
1990 ID.AddInteger(scUDivExpr);
1991 ID.AddPointer(LHS);
1992 ID.AddPointer(RHS);
1993 void *IP = 0;
1994 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001995 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1996 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001997 UniqueSCEVs.InsertNode(S, IP);
1998 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001999}
2000
2001
Dan Gohman6c0866c2009-05-24 23:45:28 +00002002/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2003/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002004const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00002005 const SCEV *Step, const Loop *L,
2006 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002007 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002008 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002009 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002010 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002011 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002012 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002013 }
2014
2015 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00002016 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002017}
2018
Dan Gohman6c0866c2009-05-24 23:45:28 +00002019/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2020/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002021const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002022ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00002023 const Loop *L,
2024 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002025 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002026#ifndef NDEBUG
2027 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2028 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
2029 getEffectiveSCEVType(Operands[0]->getType()) &&
2030 "SCEVAddRecExpr operand types don't match!");
2031#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002032
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002033 if (Operands.back()->isZero()) {
2034 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00002035 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002036 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002037
Dan Gohmanbc028532010-02-19 18:49:22 +00002038 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2039 // use that information to infer NUW and NSW flags. However, computing a
2040 // BE count requires calling getAddRecExpr, so we may not yet have a
2041 // meaningful BE count at this point (and if we don't, we'd be stuck
2042 // with a SCEVCouldNotCompute as the cached BE count).
2043
Dan Gohmana10756e2010-01-21 02:09:26 +00002044 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2045 if (!HasNUW && HasNSW) {
2046 bool All = true;
2047 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2048 if (!isKnownNonNegative(Operands[i])) {
2049 All = false;
2050 break;
2051 }
2052 if (All) HasNUW = true;
2053 }
2054
Dan Gohmand9cc7492008-08-08 18:33:12 +00002055 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002056 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002057 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002058 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002059 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002060 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002061 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002062 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002063 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002064 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002065 // AddRecs require their operands be loop-invariant with respect to their
2066 // loops. Don't perform this transformation if it would break this
2067 // requirement.
2068 bool AllInvariant = true;
2069 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2070 if (!Operands[i]->isLoopInvariant(L)) {
2071 AllInvariant = false;
2072 break;
2073 }
2074 if (AllInvariant) {
2075 NestedOperands[0] = getAddRecExpr(Operands, L);
2076 AllInvariant = true;
2077 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2078 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2079 AllInvariant = false;
2080 break;
2081 }
2082 if (AllInvariant)
2083 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002084 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002085 }
2086 // Reset Operands to its original state.
2087 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002088 }
2089 }
2090
Dan Gohman67847532010-01-19 22:27:22 +00002091 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2092 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002093 FoldingSetNodeID ID;
2094 ID.AddInteger(scAddRecExpr);
2095 ID.AddInteger(Operands.size());
2096 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2097 ID.AddPointer(Operands[i]);
2098 ID.AddPointer(L);
2099 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002100 SCEVAddRecExpr *S =
2101 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2102 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002103 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2104 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002105 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2106 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002107 UniqueSCEVs.InsertNode(S, IP);
2108 }
Dan Gohman3645b012009-10-09 00:10:36 +00002109 if (HasNUW) S->setHasNoUnsignedWrap(true);
2110 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002111 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002112}
2113
Dan Gohman9311ef62009-06-24 14:49:00 +00002114const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2115 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002116 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002117 Ops.push_back(LHS);
2118 Ops.push_back(RHS);
2119 return getSMaxExpr(Ops);
2120}
2121
Dan Gohman0bba49c2009-07-07 17:06:11 +00002122const SCEV *
2123ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002124 assert(!Ops.empty() && "Cannot get empty smax!");
2125 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002126#ifndef NDEBUG
2127 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2128 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2129 getEffectiveSCEVType(Ops[0]->getType()) &&
2130 "SCEVSMaxExpr operand types don't match!");
2131#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002132
2133 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002134 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002135
2136 // If there are any constants, fold them together.
2137 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002138 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002139 ++Idx;
2140 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002141 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002142 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002143 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002144 APIntOps::smax(LHSC->getValue()->getValue(),
2145 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002146 Ops[0] = getConstant(Fold);
2147 Ops.erase(Ops.begin()+1); // Erase the folded element
2148 if (Ops.size() == 1) return Ops[0];
2149 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002150 }
2151
Dan Gohmane5aceed2009-06-24 14:46:22 +00002152 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002153 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2154 Ops.erase(Ops.begin());
2155 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002156 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2157 // If we have an smax with a constant maximum-int, it will always be
2158 // maximum-int.
2159 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002160 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002161
Dan Gohman3ab13122010-04-13 16:49:23 +00002162 if (Ops.size() == 1) return Ops[0];
2163 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002164
2165 // Find the first SMax
2166 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2167 ++Idx;
2168
2169 // Check to see if one of the operands is an SMax. If so, expand its operands
2170 // onto our operand list, and recurse to simplify.
2171 if (Idx < Ops.size()) {
2172 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002173 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002174 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002175 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002176 DeletedSMax = true;
2177 }
2178
2179 if (DeletedSMax)
2180 return getSMaxExpr(Ops);
2181 }
2182
2183 // Okay, check to see if the same value occurs in the operand list twice. If
2184 // so, delete one. Since we sorted the list, these values are required to
2185 // be adjacent.
2186 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002187 // X smax Y smax Y --> X smax Y
2188 // X smax Y --> X, if X is always greater than Y
2189 if (Ops[i] == Ops[i+1] ||
2190 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2191 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2192 --i; --e;
2193 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002194 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2195 --i; --e;
2196 }
2197
2198 if (Ops.size() == 1) return Ops[0];
2199
2200 assert(!Ops.empty() && "Reduced smax down to nothing!");
2201
Nick Lewycky3e630762008-02-20 06:48:22 +00002202 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002203 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002204 FoldingSetNodeID ID;
2205 ID.AddInteger(scSMaxExpr);
2206 ID.AddInteger(Ops.size());
2207 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2208 ID.AddPointer(Ops[i]);
2209 void *IP = 0;
2210 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002211 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2212 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002213 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2214 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002215 UniqueSCEVs.InsertNode(S, IP);
2216 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002217}
2218
Dan Gohman9311ef62009-06-24 14:49:00 +00002219const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2220 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002221 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002222 Ops.push_back(LHS);
2223 Ops.push_back(RHS);
2224 return getUMaxExpr(Ops);
2225}
2226
Dan Gohman0bba49c2009-07-07 17:06:11 +00002227const SCEV *
2228ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002229 assert(!Ops.empty() && "Cannot get empty umax!");
2230 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002231#ifndef NDEBUG
2232 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2233 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2234 getEffectiveSCEVType(Ops[0]->getType()) &&
2235 "SCEVUMaxExpr operand types don't match!");
2236#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002237
2238 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002239 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002240
2241 // If there are any constants, fold them together.
2242 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002243 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002244 ++Idx;
2245 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002246 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002247 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002248 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002249 APIntOps::umax(LHSC->getValue()->getValue(),
2250 RHSC->getValue()->getValue()));
2251 Ops[0] = getConstant(Fold);
2252 Ops.erase(Ops.begin()+1); // Erase the folded element
2253 if (Ops.size() == 1) return Ops[0];
2254 LHSC = cast<SCEVConstant>(Ops[0]);
2255 }
2256
Dan Gohmane5aceed2009-06-24 14:46:22 +00002257 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002258 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2259 Ops.erase(Ops.begin());
2260 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002261 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2262 // If we have an umax with a constant maximum-int, it will always be
2263 // maximum-int.
2264 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002265 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002266
Dan Gohman3ab13122010-04-13 16:49:23 +00002267 if (Ops.size() == 1) return Ops[0];
2268 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002269
2270 // Find the first UMax
2271 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2272 ++Idx;
2273
2274 // Check to see if one of the operands is a UMax. If so, expand its operands
2275 // onto our operand list, and recurse to simplify.
2276 if (Idx < Ops.size()) {
2277 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002278 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002279 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002280 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002281 DeletedUMax = true;
2282 }
2283
2284 if (DeletedUMax)
2285 return getUMaxExpr(Ops);
2286 }
2287
2288 // Okay, check to see if the same value occurs in the operand list twice. If
2289 // so, delete one. Since we sorted the list, these values are required to
2290 // be adjacent.
2291 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002292 // X umax Y umax Y --> X umax Y
2293 // X umax Y --> X, if X is always greater than Y
2294 if (Ops[i] == Ops[i+1] ||
2295 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2296 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2297 --i; --e;
2298 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002299 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2300 --i; --e;
2301 }
2302
2303 if (Ops.size() == 1) return Ops[0];
2304
2305 assert(!Ops.empty() && "Reduced umax down to nothing!");
2306
2307 // Okay, it looks like we really DO need a umax expr. Check to see if we
2308 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002309 FoldingSetNodeID ID;
2310 ID.AddInteger(scUMaxExpr);
2311 ID.AddInteger(Ops.size());
2312 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2313 ID.AddPointer(Ops[i]);
2314 void *IP = 0;
2315 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002316 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2317 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002318 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2319 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002320 UniqueSCEVs.InsertNode(S, IP);
2321 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002322}
2323
Dan Gohman9311ef62009-06-24 14:49:00 +00002324const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2325 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002326 // ~smax(~x, ~y) == smin(x, y).
2327 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2328}
2329
Dan Gohman9311ef62009-06-24 14:49:00 +00002330const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2331 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002332 // ~umax(~x, ~y) == umin(x, y)
2333 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2334}
2335
Dan Gohman4f8eea82010-02-01 18:27:38 +00002336const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002337 // If we have TargetData, we can bypass creating a target-independent
2338 // constant expression and then folding it back into a ConstantInt.
2339 // This is just a compile-time optimization.
2340 if (TD)
2341 return getConstant(TD->getIntPtrType(getContext()),
2342 TD->getTypeAllocSize(AllocTy));
2343
Dan Gohman4f8eea82010-02-01 18:27:38 +00002344 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2345 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002346 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2347 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002348 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2349 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2350}
2351
2352const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2353 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2354 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002355 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2356 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002357 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2358 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2359}
2360
2361const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2362 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002363 // If we have TargetData, we can bypass creating a target-independent
2364 // constant expression and then folding it back into a ConstantInt.
2365 // This is just a compile-time optimization.
2366 if (TD)
2367 return getConstant(TD->getIntPtrType(getContext()),
2368 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2369
Dan Gohman0f5efe52010-01-28 02:15:55 +00002370 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2371 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002372 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2373 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002374 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002375 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002376}
2377
Dan Gohman4f8eea82010-02-01 18:27:38 +00002378const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2379 Constant *FieldNo) {
2380 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002381 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002382 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2383 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002384 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002385 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002386}
2387
Dan Gohman0bba49c2009-07-07 17:06:11 +00002388const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002389 // Don't attempt to do anything other than create a SCEVUnknown object
2390 // here. createSCEV only calls getUnknown after checking for all other
2391 // interesting possibilities, and any other code that calls getUnknown
2392 // is doing so in order to hide a value from SCEV canonicalization.
2393
Dan Gohman1c343752009-06-27 21:21:31 +00002394 FoldingSetNodeID ID;
2395 ID.AddInteger(scUnknown);
2396 ID.AddPointer(V);
2397 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002398 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2399 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2400 "Stale SCEVUnknown in uniquing map!");
2401 return S;
2402 }
2403 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2404 FirstUnknown);
2405 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002406 UniqueSCEVs.InsertNode(S, IP);
2407 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002408}
2409
Chris Lattner53e677a2004-04-02 20:23:17 +00002410//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002411// Basic SCEV Analysis and PHI Idiom Recognition Code
2412//
2413
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002414/// isSCEVable - Test if values of the given type are analyzable within
2415/// the SCEV framework. This primarily includes integer types, and it
2416/// can optionally include pointer types if the ScalarEvolution class
2417/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002418bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002419 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002420 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002421}
2422
2423/// getTypeSizeInBits - Return the size in bits of the specified type,
2424/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002425uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002426 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2427
2428 // If we have a TargetData, use it!
2429 if (TD)
2430 return TD->getTypeSizeInBits(Ty);
2431
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002432 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002433 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002434 return Ty->getPrimitiveSizeInBits();
2435
2436 // The only other support type is pointer. Without TargetData, conservatively
2437 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002438 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002439 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002440}
2441
2442/// getEffectiveSCEVType - Return a type with the same bitwidth as
2443/// the given type and which represents how SCEV will treat the given
2444/// type, for which isSCEVable must return true. For pointer types,
2445/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002446const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002447 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2448
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002449 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002450 return Ty;
2451
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002452 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002453 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002454 if (TD) return TD->getIntPtrType(getContext());
2455
2456 // Without TargetData, conservatively assume pointers are 64-bit.
2457 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002458}
Chris Lattner53e677a2004-04-02 20:23:17 +00002459
Dan Gohman0bba49c2009-07-07 17:06:11 +00002460const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002461 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002462}
2463
Chris Lattner53e677a2004-04-02 20:23:17 +00002464/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2465/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002466const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002467 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002468
Dan Gohman0bba49c2009-07-07 17:06:11 +00002469 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002470 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002471 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002472 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002473 return S;
2474}
2475
Dan Gohman2d1be872009-04-16 03:18:22 +00002476/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2477///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002478const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002479 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002480 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002481 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002482
2483 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002484 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002485 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002486 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002487}
2488
2489/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002490const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002491 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002492 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002493 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002494
2495 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002496 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002497 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002498 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002499 return getMinusSCEV(AllOnes, V);
2500}
2501
2502/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2503///
Dan Gohman9311ef62009-06-24 14:49:00 +00002504const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2505 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002506 // Fast path: X - X --> 0.
2507 if (LHS == RHS)
2508 return getConstant(LHS->getType(), 0);
2509
Dan Gohman2d1be872009-04-16 03:18:22 +00002510 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002511 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002512}
2513
2514/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2515/// input value to the specified type. If the type must be extended, it is zero
2516/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002517const SCEV *
2518ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002519 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002520 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002521 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2522 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002523 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002525 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002526 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002527 return getTruncateExpr(V, Ty);
2528 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002529}
2530
2531/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2532/// input value to the specified type. If the type must be extended, it is sign
2533/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002534const SCEV *
2535ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002536 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002537 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002538 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2539 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002540 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002541 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002542 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002543 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002544 return getTruncateExpr(V, Ty);
2545 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002546}
2547
Dan Gohman467c4302009-05-13 03:46:30 +00002548/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2549/// input value to the specified type. If the type must be extended, it is zero
2550/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002551const SCEV *
2552ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002553 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002554 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2555 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002556 "Cannot noop or zero extend with non-integer arguments!");
2557 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2558 "getNoopOrZeroExtend cannot truncate!");
2559 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2560 return V; // No conversion
2561 return getZeroExtendExpr(V, Ty);
2562}
2563
2564/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2565/// input value to the specified type. If the type must be extended, it is sign
2566/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002567const SCEV *
2568ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002569 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002570 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2571 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002572 "Cannot noop or sign extend with non-integer arguments!");
2573 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2574 "getNoopOrSignExtend cannot truncate!");
2575 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2576 return V; // No conversion
2577 return getSignExtendExpr(V, Ty);
2578}
2579
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002580/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2581/// the input value to the specified type. If the type must be extended,
2582/// it is extended with unspecified bits. The conversion must not be
2583/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002584const SCEV *
2585ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002586 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002587 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2588 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002589 "Cannot noop or any extend with non-integer arguments!");
2590 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2591 "getNoopOrAnyExtend cannot truncate!");
2592 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2593 return V; // No conversion
2594 return getAnyExtendExpr(V, Ty);
2595}
2596
Dan Gohman467c4302009-05-13 03:46:30 +00002597/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2598/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002599const SCEV *
2600ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002601 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002602 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2603 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002604 "Cannot truncate or noop with non-integer arguments!");
2605 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2606 "getTruncateOrNoop cannot extend!");
2607 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2608 return V; // No conversion
2609 return getTruncateExpr(V, Ty);
2610}
2611
Dan Gohmana334aa72009-06-22 00:31:57 +00002612/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2613/// the types using zero-extension, and then perform a umax operation
2614/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002615const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2616 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002617 const SCEV *PromotedLHS = LHS;
2618 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002619
2620 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2621 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2622 else
2623 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2624
2625 return getUMaxExpr(PromotedLHS, PromotedRHS);
2626}
2627
Dan Gohmanc9759e82009-06-22 15:03:27 +00002628/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2629/// the types using zero-extension, and then perform a umin operation
2630/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002631const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2632 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002633 const SCEV *PromotedLHS = LHS;
2634 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002635
2636 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2637 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2638 else
2639 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2640
2641 return getUMinExpr(PromotedLHS, PromotedRHS);
2642}
2643
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002644/// PushDefUseChildren - Push users of the given Instruction
2645/// onto the given Worklist.
2646static void
2647PushDefUseChildren(Instruction *I,
2648 SmallVectorImpl<Instruction *> &Worklist) {
2649 // Push the def-use children onto the Worklist stack.
2650 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2651 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002652 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002653}
2654
2655/// ForgetSymbolicValue - This looks up computed SCEV values for all
2656/// instructions that depend on the given instruction and removes them from
2657/// the Scalars map if they reference SymName. This is used during PHI
2658/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002659void
Dan Gohman85669632010-02-25 06:57:05 +00002660ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002661 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002662 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002663
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002664 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002665 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002666 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002667 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002668 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002669
Dan Gohman5d984912009-12-18 01:14:11 +00002670 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002671 Scalars.find(static_cast<Value *>(I));
2672 if (It != Scalars.end()) {
2673 // Short-circuit the def-use traversal if the symbolic name
2674 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002675 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002676 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002677
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002678 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002679 // structure, it's a PHI that's in the progress of being computed
2680 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2681 // additional loop trip count information isn't going to change anything.
2682 // In the second case, createNodeForPHI will perform the necessary
2683 // updates on its own when it gets to that point. In the third, we do
2684 // want to forget the SCEVUnknown.
2685 if (!isa<PHINode>(I) ||
2686 !isa<SCEVUnknown>(It->second) ||
2687 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002688 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002689 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002690 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002691 }
2692
2693 PushDefUseChildren(I, Worklist);
2694 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002695}
Chris Lattner53e677a2004-04-02 20:23:17 +00002696
2697/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2698/// a loop header, making it a potential recurrence, or it doesn't.
2699///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002700const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002701 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2702 if (L->getHeader() == PN->getParent()) {
2703 // The loop may have multiple entrances or multiple exits; we can analyze
2704 // this phi as an addrec if it has a unique entry value and a unique
2705 // backedge value.
2706 Value *BEValueV = 0, *StartValueV = 0;
2707 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2708 Value *V = PN->getIncomingValue(i);
2709 if (L->contains(PN->getIncomingBlock(i))) {
2710 if (!BEValueV) {
2711 BEValueV = V;
2712 } else if (BEValueV != V) {
2713 BEValueV = 0;
2714 break;
2715 }
2716 } else if (!StartValueV) {
2717 StartValueV = V;
2718 } else if (StartValueV != V) {
2719 StartValueV = 0;
2720 break;
2721 }
2722 }
2723 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002724 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002725 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002726 assert(Scalars.find(PN) == Scalars.end() &&
2727 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002728 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002729
2730 // Using this symbolic name for the PHI, analyze the value coming around
2731 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002732 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002733
2734 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2735 // has a special value for the first iteration of the loop.
2736
2737 // If the value coming around the backedge is an add with the symbolic
2738 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002739 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002740 // If there is a single occurrence of the symbolic value, replace it
2741 // with a recurrence.
2742 unsigned FoundIndex = Add->getNumOperands();
2743 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2744 if (Add->getOperand(i) == SymbolicName)
2745 if (FoundIndex == e) {
2746 FoundIndex = i;
2747 break;
2748 }
2749
2750 if (FoundIndex != Add->getNumOperands()) {
2751 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002752 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002753 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2754 if (i != FoundIndex)
2755 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002756 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002757
2758 // This is not a valid addrec if the step amount is varying each
2759 // loop iteration, but is not itself an addrec in this loop.
2760 if (Accum->isLoopInvariant(L) ||
2761 (isa<SCEVAddRecExpr>(Accum) &&
2762 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002763 bool HasNUW = false;
2764 bool HasNSW = false;
2765
2766 // If the increment doesn't overflow, then neither the addrec nor
2767 // the post-increment will overflow.
2768 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2769 if (OBO->hasNoUnsignedWrap())
2770 HasNUW = true;
2771 if (OBO->hasNoSignedWrap())
2772 HasNSW = true;
2773 }
2774
Dan Gohman27dead42010-04-12 07:49:36 +00002775 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002776 const SCEV *PHISCEV =
2777 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002778
Dan Gohmana10756e2010-01-21 02:09:26 +00002779 // Since the no-wrap flags are on the increment, they apply to the
2780 // post-incremented value as well.
2781 if (Accum->isLoopInvariant(L))
2782 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2783 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002784
2785 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002786 // to be symbolic. We now need to go back and purge all of the
2787 // entries for the scalars that use the symbolic expression.
2788 ForgetSymbolicName(PN, SymbolicName);
2789 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002790 return PHISCEV;
2791 }
2792 }
Dan Gohman622ed672009-05-04 22:02:23 +00002793 } else if (const SCEVAddRecExpr *AddRec =
2794 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002795 // Otherwise, this could be a loop like this:
2796 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2797 // In this case, j = {1,+,1} and BEValue is j.
2798 // Because the other in-value of i (0) fits the evolution of BEValue
2799 // i really is an addrec evolution.
2800 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002801 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002802
2803 // If StartVal = j.start - j.stride, we can use StartVal as the
2804 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002805 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002806 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002807 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002808 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002809
2810 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002811 // to be symbolic. We now need to go back and purge all of the
2812 // entries for the scalars that use the symbolic expression.
2813 ForgetSymbolicName(PN, SymbolicName);
2814 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002815 return PHISCEV;
2816 }
2817 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002818 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002819 }
Dan Gohman27dead42010-04-12 07:49:36 +00002820 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002821
Dan Gohman85669632010-02-25 06:57:05 +00002822 // If the PHI has a single incoming value, follow that value, unless the
2823 // PHI's incoming blocks are in a different loop, in which case doing so
2824 // risks breaking LCSSA form. Instcombine would normally zap these, but
2825 // it doesn't have DominatorTree information, so it may miss cases.
2826 if (Value *V = PN->hasConstantValue(DT)) {
2827 bool AllSameLoop = true;
2828 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2829 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2830 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2831 AllSameLoop = false;
2832 break;
2833 }
2834 if (AllSameLoop)
2835 return getSCEV(V);
2836 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002837
Chris Lattner53e677a2004-04-02 20:23:17 +00002838 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002839 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002840}
2841
Dan Gohman26466c02009-05-08 20:26:55 +00002842/// createNodeForGEP - Expand GEP instructions into add and multiply
2843/// operations. This allows them to be analyzed by regular SCEV code.
2844///
Dan Gohmand281ed22009-12-18 02:09:29 +00002845const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002846
Dan Gohmanb9f96512010-06-30 07:16:37 +00002847 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2848 // Add expression, because the Instruction may be guarded by control flow
2849 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002850 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002851
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002852 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002853 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002854 // Don't attempt to analyze GEPs over unsized objects.
2855 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2856 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002857 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002858 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002859 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002860 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002861 I != E; ++I) {
2862 Value *Index = *I;
2863 // Compute the (potentially symbolic) offset in bytes for this index.
2864 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2865 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002866 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002867 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2868
Dan Gohmanb9f96512010-06-30 07:16:37 +00002869 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002870 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002871 } else {
2872 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002873 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2874 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002875 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002876 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2877
Dan Gohmanb9f96512010-06-30 07:16:37 +00002878 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002879 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002880
2881 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002882 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002883 }
2884 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002885
2886 // Get the SCEV for the GEP base.
2887 const SCEV *BaseS = getSCEV(Base);
2888
Dan Gohmanb9f96512010-06-30 07:16:37 +00002889 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002890 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002891}
2892
Nick Lewycky83bb0052007-11-22 07:59:40 +00002893/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2894/// guaranteed to end in (at every loop iteration). It is, at the same time,
2895/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2896/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002897uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002898ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002899 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002900 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002901
Dan Gohman622ed672009-05-04 22:02:23 +00002902 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002903 return std::min(GetMinTrailingZeros(T->getOperand()),
2904 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002905
Dan Gohman622ed672009-05-04 22:02:23 +00002906 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002907 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2908 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2909 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002910 }
2911
Dan Gohman622ed672009-05-04 22:02:23 +00002912 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002913 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2914 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2915 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002916 }
2917
Dan Gohman622ed672009-05-04 22:02:23 +00002918 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002919 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002920 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002921 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002922 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002923 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002924 }
2925
Dan Gohman622ed672009-05-04 22:02:23 +00002926 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002927 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002928 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2929 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002930 for (unsigned i = 1, e = M->getNumOperands();
2931 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002932 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002933 BitWidth);
2934 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002935 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002936
Dan Gohman622ed672009-05-04 22:02:23 +00002937 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002938 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002939 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002940 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002941 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002942 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002943 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002944
Dan Gohman622ed672009-05-04 22:02:23 +00002945 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002946 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002947 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002948 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002949 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002950 return MinOpRes;
2951 }
2952
Dan Gohman622ed672009-05-04 22:02:23 +00002953 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002954 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002955 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002956 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002957 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002958 return MinOpRes;
2959 }
2960
Dan Gohman2c364ad2009-06-19 23:29:04 +00002961 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2962 // For a SCEVUnknown, ask ValueTracking.
2963 unsigned BitWidth = getTypeSizeInBits(U->getType());
2964 APInt Mask = APInt::getAllOnesValue(BitWidth);
2965 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2966 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2967 return Zeros.countTrailingOnes();
2968 }
2969
2970 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002971 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002972}
Chris Lattner53e677a2004-04-02 20:23:17 +00002973
Dan Gohman85b05a22009-07-13 21:35:55 +00002974/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2975///
2976ConstantRange
2977ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002978
2979 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002980 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002981
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002982 unsigned BitWidth = getTypeSizeInBits(S->getType());
2983 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2984
2985 // If the value has known zeros, the maximum unsigned value will have those
2986 // known zeros as well.
2987 uint32_t TZ = GetMinTrailingZeros(S);
2988 if (TZ != 0)
2989 ConservativeResult =
2990 ConstantRange(APInt::getMinValue(BitWidth),
2991 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2992
Dan Gohman85b05a22009-07-13 21:35:55 +00002993 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2994 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2995 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2996 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002997 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002998 }
2999
3000 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3001 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3002 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3003 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003004 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003005 }
3006
3007 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3008 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3009 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3010 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003011 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003012 }
3013
3014 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3015 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3016 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3017 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003018 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003019 }
3020
3021 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3022 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3023 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003024 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003025 }
3026
3027 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3028 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003029 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003030 }
3031
3032 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3033 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003034 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003035 }
3036
3037 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3038 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003039 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003040 }
3041
Dan Gohman85b05a22009-07-13 21:35:55 +00003042 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003043 // If there's no unsigned wrap, the value will never be less than its
3044 // initial value.
3045 if (AddRec->hasNoUnsignedWrap())
3046 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003047 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003048 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003049 ConservativeResult.intersectWith(
3050 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003051
3052 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003053 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003054 const Type *Ty = AddRec->getType();
3055 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003056 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3057 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003058 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3059
3060 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003061 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003062
3063 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003064 ConstantRange StepRange = getSignedRange(Step);
3065 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3066 ConstantRange EndRange =
3067 StartRange.add(MaxBECountRange.multiply(StepRange));
3068
3069 // Check for overflow. This must be done with ConstantRange arithmetic
3070 // because we could be called from within the ScalarEvolution overflow
3071 // checking code.
3072 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3073 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3074 ConstantRange ExtMaxBECountRange =
3075 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3076 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3077 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3078 ExtEndRange)
3079 return ConservativeResult;
3080
Dan Gohman85b05a22009-07-13 21:35:55 +00003081 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3082 EndRange.getUnsignedMin());
3083 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3084 EndRange.getUnsignedMax());
3085 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003086 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003087 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00003088 }
3089 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003090
3091 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003092 }
3093
3094 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3095 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003096 APInt Mask = APInt::getAllOnesValue(BitWidth);
3097 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3098 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003099 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003100 return ConservativeResult;
3101 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003102 }
3103
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003104 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003105}
3106
Dan Gohman85b05a22009-07-13 21:35:55 +00003107/// getSignedRange - Determine the signed range for a particular SCEV.
3108///
3109ConstantRange
3110ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003111
Dan Gohman85b05a22009-07-13 21:35:55 +00003112 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3113 return ConstantRange(C->getValue()->getValue());
3114
Dan Gohman52fddd32010-01-26 04:40:18 +00003115 unsigned BitWidth = getTypeSizeInBits(S->getType());
3116 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3117
3118 // If the value has known zeros, the maximum signed value will have those
3119 // known zeros as well.
3120 uint32_t TZ = GetMinTrailingZeros(S);
3121 if (TZ != 0)
3122 ConservativeResult =
3123 ConstantRange(APInt::getSignedMinValue(BitWidth),
3124 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3125
Dan Gohman85b05a22009-07-13 21:35:55 +00003126 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3127 ConstantRange X = getSignedRange(Add->getOperand(0));
3128 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3129 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003130 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003131 }
3132
Dan Gohman85b05a22009-07-13 21:35:55 +00003133 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3134 ConstantRange X = getSignedRange(Mul->getOperand(0));
3135 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3136 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003137 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003138 }
3139
Dan Gohman85b05a22009-07-13 21:35:55 +00003140 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3141 ConstantRange X = getSignedRange(SMax->getOperand(0));
3142 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3143 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003144 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003145 }
Dan Gohman62849c02009-06-24 01:05:09 +00003146
Dan Gohman85b05a22009-07-13 21:35:55 +00003147 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3148 ConstantRange X = getSignedRange(UMax->getOperand(0));
3149 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3150 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003151 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003152 }
Dan Gohman62849c02009-06-24 01:05:09 +00003153
Dan Gohman85b05a22009-07-13 21:35:55 +00003154 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3155 ConstantRange X = getSignedRange(UDiv->getLHS());
3156 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003157 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003158 }
Dan Gohman62849c02009-06-24 01:05:09 +00003159
Dan Gohman85b05a22009-07-13 21:35:55 +00003160 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3161 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003162 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003163 }
3164
3165 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3166 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003167 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003168 }
3169
3170 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3171 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003172 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003173 }
3174
Dan Gohman85b05a22009-07-13 21:35:55 +00003175 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003176 // If there's no signed wrap, and all the operands have the same sign or
3177 // zero, the value won't ever change sign.
3178 if (AddRec->hasNoSignedWrap()) {
3179 bool AllNonNeg = true;
3180 bool AllNonPos = true;
3181 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3182 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3183 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3184 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003185 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003186 ConservativeResult = ConservativeResult.intersectWith(
3187 ConstantRange(APInt(BitWidth, 0),
3188 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003189 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003190 ConservativeResult = ConservativeResult.intersectWith(
3191 ConstantRange(APInt::getSignedMinValue(BitWidth),
3192 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003193 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003194
3195 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003196 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003197 const Type *Ty = AddRec->getType();
3198 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003199 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3200 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003201 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3202
3203 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003204 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003205
3206 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003207 ConstantRange StepRange = getSignedRange(Step);
3208 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3209 ConstantRange EndRange =
3210 StartRange.add(MaxBECountRange.multiply(StepRange));
3211
3212 // Check for overflow. This must be done with ConstantRange arithmetic
3213 // because we could be called from within the ScalarEvolution overflow
3214 // checking code.
3215 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3216 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3217 ConstantRange ExtMaxBECountRange =
3218 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3219 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3220 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3221 ExtEndRange)
3222 return ConservativeResult;
3223
Dan Gohman85b05a22009-07-13 21:35:55 +00003224 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3225 EndRange.getSignedMin());
3226 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3227 EndRange.getSignedMax());
3228 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003229 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003230 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003231 }
Dan Gohman62849c02009-06-24 01:05:09 +00003232 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003233
3234 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003235 }
3236
Dan Gohman2c364ad2009-06-19 23:29:04 +00003237 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3238 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003239 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003240 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003241 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3242 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003243 return ConservativeResult;
3244 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003245 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003246 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003247 }
3248
Dan Gohman52fddd32010-01-26 04:40:18 +00003249 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003250}
3251
Chris Lattner53e677a2004-04-02 20:23:17 +00003252/// createSCEV - We know that there is no SCEV for the specified value.
3253/// Analyze the expression.
3254///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003255const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003256 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003257 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003258
Dan Gohman6c459a22008-06-22 19:56:46 +00003259 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003260 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003261 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003262
3263 // Don't attempt to analyze instructions in blocks that aren't
3264 // reachable. Such instructions don't matter, and they aren't required
3265 // to obey basic rules for definitions dominating uses which this
3266 // analysis depends on.
3267 if (!DT->isReachableFromEntry(I->getParent()))
3268 return getUnknown(V);
3269 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003270 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003271 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3272 return getConstant(CI);
3273 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003274 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003275 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3276 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003277 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003278 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003279
Dan Gohmanca178902009-07-17 20:47:02 +00003280 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003281 switch (Opcode) {
Dan Gohman70eff632010-06-30 17:27:11 +00003282 case Instruction::Add:
3283 return getAddExpr(getSCEV(U->getOperand(0)),
3284 getSCEV(U->getOperand(1)));
3285 case Instruction::Mul:
3286 return getMulExpr(getSCEV(U->getOperand(0)),
3287 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003288 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003289 return getUDivExpr(getSCEV(U->getOperand(0)),
3290 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003291 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003292 return getMinusSCEV(getSCEV(U->getOperand(0)),
3293 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003294 case Instruction::And:
3295 // For an expression like x&255 that merely masks off the high bits,
3296 // use zext(trunc(x)) as the SCEV expression.
3297 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003298 if (CI->isNullValue())
3299 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003300 if (CI->isAllOnesValue())
3301 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003302 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003303
3304 // Instcombine's ShrinkDemandedConstant may strip bits out of
3305 // constants, obscuring what would otherwise be a low-bits mask.
3306 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3307 // knew about to reconstruct a low-bits mask value.
3308 unsigned LZ = A.countLeadingZeros();
3309 unsigned BitWidth = A.getBitWidth();
3310 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3311 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3312 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3313
3314 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3315
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003316 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003317 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003318 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003319 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003320 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003321 }
3322 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003323
Dan Gohman6c459a22008-06-22 19:56:46 +00003324 case Instruction::Or:
3325 // If the RHS of the Or is a constant, we may have something like:
3326 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3327 // optimizations will transparently handle this case.
3328 //
3329 // In order for this transformation to be safe, the LHS must be of the
3330 // form X*(2^n) and the Or constant must be less than 2^n.
3331 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003332 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003333 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003334 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003335 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3336 // Build a plain add SCEV.
3337 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3338 // If the LHS of the add was an addrec and it has no-wrap flags,
3339 // transfer the no-wrap flags, since an or won't introduce a wrap.
3340 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3341 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3342 if (OldAR->hasNoUnsignedWrap())
3343 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3344 if (OldAR->hasNoSignedWrap())
3345 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3346 }
3347 return S;
3348 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003349 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003350 break;
3351 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003352 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003353 // If the RHS of the xor is a signbit, then this is just an add.
3354 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003355 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003356 return getAddExpr(getSCEV(U->getOperand(0)),
3357 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003358
3359 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003360 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003361 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003362
3363 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3364 // This is a variant of the check for xor with -1, and it handles
3365 // the case where instcombine has trimmed non-demanded bits out
3366 // of an xor with -1.
3367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3368 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3369 if (BO->getOpcode() == Instruction::And &&
3370 LCI->getValue() == CI->getValue())
3371 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003372 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003373 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003374 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003375 const Type *Z0Ty = Z0->getType();
3376 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3377
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003378 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003379 // mask off the high bits. Complement the operand and
3380 // re-apply the zext.
3381 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3382 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3383
3384 // If C is a single bit, it may be in the sign-bit position
3385 // before the zero-extend. In this case, represent the xor
3386 // using an add, which is equivalent, and re-apply the zext.
3387 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3388 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3389 Trunc.isSignBit())
3390 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3391 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003392 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003393 }
3394 break;
3395
3396 case Instruction::Shl:
3397 // Turn shift left of a constant amount into a multiply.
3398 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003399 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003400
3401 // If the shift count is not less than the bitwidth, the result of
3402 // the shift is undefined. Don't try to analyze it, because the
3403 // resolution chosen here may differ from the resolution chosen in
3404 // other parts of the compiler.
3405 if (SA->getValue().uge(BitWidth))
3406 break;
3407
Owen Andersoneed707b2009-07-24 23:12:02 +00003408 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003409 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003410 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003411 }
3412 break;
3413
Nick Lewycky01eaf802008-07-07 06:15:49 +00003414 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003415 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003416 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003417 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003418
3419 // If the shift count is not less than the bitwidth, the result of
3420 // the shift is undefined. Don't try to analyze it, because the
3421 // resolution chosen here may differ from the resolution chosen in
3422 // other parts of the compiler.
3423 if (SA->getValue().uge(BitWidth))
3424 break;
3425
Owen Andersoneed707b2009-07-24 23:12:02 +00003426 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003427 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003428 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003429 }
3430 break;
3431
Dan Gohman4ee29af2009-04-21 02:26:00 +00003432 case Instruction::AShr:
3433 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3434 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003435 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003436 if (L->getOpcode() == Instruction::Shl &&
3437 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003438 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3439
3440 // If the shift count is not less than the bitwidth, the result of
3441 // the shift is undefined. Don't try to analyze it, because the
3442 // resolution chosen here may differ from the resolution chosen in
3443 // other parts of the compiler.
3444 if (CI->getValue().uge(BitWidth))
3445 break;
3446
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003447 uint64_t Amt = BitWidth - CI->getZExtValue();
3448 if (Amt == BitWidth)
3449 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003450 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003451 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003452 IntegerType::get(getContext(),
3453 Amt)),
3454 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003455 }
3456 break;
3457
Dan Gohman6c459a22008-06-22 19:56:46 +00003458 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003459 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003460
3461 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003462 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003463
3464 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003465 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003466
3467 case Instruction::BitCast:
3468 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003469 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003470 return getSCEV(U->getOperand(0));
3471 break;
3472
Dan Gohman4f8eea82010-02-01 18:27:38 +00003473 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3474 // lead to pointer expressions which cannot safely be expanded to GEPs,
3475 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3476 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003477
Dan Gohman26466c02009-05-08 20:26:55 +00003478 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003479 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003480
Dan Gohman6c459a22008-06-22 19:56:46 +00003481 case Instruction::PHI:
3482 return createNodeForPHI(cast<PHINode>(U));
3483
3484 case Instruction::Select:
3485 // This could be a smax or umax that was lowered earlier.
3486 // Try to recover it.
3487 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3488 Value *LHS = ICI->getOperand(0);
3489 Value *RHS = ICI->getOperand(1);
3490 switch (ICI->getPredicate()) {
3491 case ICmpInst::ICMP_SLT:
3492 case ICmpInst::ICMP_SLE:
3493 std::swap(LHS, RHS);
3494 // fall through
3495 case ICmpInst::ICMP_SGT:
3496 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003497 // a >s b ? a+x : b+x -> smax(a, b)+x
3498 // a >s b ? b+x : a+x -> smin(a, b)+x
3499 if (LHS->getType() == U->getType()) {
3500 const SCEV *LS = getSCEV(LHS);
3501 const SCEV *RS = getSCEV(RHS);
3502 const SCEV *LA = getSCEV(U->getOperand(1));
3503 const SCEV *RA = getSCEV(U->getOperand(2));
3504 const SCEV *LDiff = getMinusSCEV(LA, LS);
3505 const SCEV *RDiff = getMinusSCEV(RA, RS);
3506 if (LDiff == RDiff)
3507 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3508 LDiff = getMinusSCEV(LA, RS);
3509 RDiff = getMinusSCEV(RA, LS);
3510 if (LDiff == RDiff)
3511 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3512 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003513 break;
3514 case ICmpInst::ICMP_ULT:
3515 case ICmpInst::ICMP_ULE:
3516 std::swap(LHS, RHS);
3517 // fall through
3518 case ICmpInst::ICMP_UGT:
3519 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003520 // a >u b ? a+x : b+x -> umax(a, b)+x
3521 // a >u b ? b+x : a+x -> umin(a, b)+x
3522 if (LHS->getType() == U->getType()) {
3523 const SCEV *LS = getSCEV(LHS);
3524 const SCEV *RS = getSCEV(RHS);
3525 const SCEV *LA = getSCEV(U->getOperand(1));
3526 const SCEV *RA = getSCEV(U->getOperand(2));
3527 const SCEV *LDiff = getMinusSCEV(LA, LS);
3528 const SCEV *RDiff = getMinusSCEV(RA, RS);
3529 if (LDiff == RDiff)
3530 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3531 LDiff = getMinusSCEV(LA, RS);
3532 RDiff = getMinusSCEV(RA, LS);
3533 if (LDiff == RDiff)
3534 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3535 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003536 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003537 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003538 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3539 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003540 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003541 cast<ConstantInt>(RHS)->isZero()) {
3542 const SCEV *One = getConstant(LHS->getType(), 1);
3543 const SCEV *LS = getSCEV(LHS);
3544 const SCEV *LA = getSCEV(U->getOperand(1));
3545 const SCEV *RA = getSCEV(U->getOperand(2));
3546 const SCEV *LDiff = getMinusSCEV(LA, LS);
3547 const SCEV *RDiff = getMinusSCEV(RA, One);
3548 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003549 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003550 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003551 break;
3552 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003553 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3554 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003555 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003556 cast<ConstantInt>(RHS)->isZero()) {
3557 const SCEV *One = getConstant(LHS->getType(), 1);
3558 const SCEV *LS = getSCEV(LHS);
3559 const SCEV *LA = getSCEV(U->getOperand(1));
3560 const SCEV *RA = getSCEV(U->getOperand(2));
3561 const SCEV *LDiff = getMinusSCEV(LA, One);
3562 const SCEV *RDiff = getMinusSCEV(RA, LS);
3563 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003564 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003565 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003566 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003567 default:
3568 break;
3569 }
3570 }
3571
3572 default: // We cannot analyze this expression.
3573 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003574 }
3575
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003576 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003577}
3578
3579
3580
3581//===----------------------------------------------------------------------===//
3582// Iteration Count Computation Code
3583//
3584
Dan Gohman46bdfb02009-02-24 18:55:53 +00003585/// getBackedgeTakenCount - If the specified loop has a predictable
3586/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3587/// object. The backedge-taken count is the number of times the loop header
3588/// will be branched to from within the loop. This is one less than the
3589/// trip count of the loop, since it doesn't count the first iteration,
3590/// when the header is branched to from outside the loop.
3591///
3592/// Note that it is not valid to call this method on a loop without a
3593/// loop-invariant backedge-taken count (see
3594/// hasLoopInvariantBackedgeTakenCount).
3595///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003596const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003597 return getBackedgeTakenInfo(L).Exact;
3598}
3599
3600/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3601/// return the least SCEV value that is known never to be less than the
3602/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003603const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003604 return getBackedgeTakenInfo(L).Max;
3605}
3606
Dan Gohman59ae6b92009-07-08 19:23:34 +00003607/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3608/// onto the given Worklist.
3609static void
3610PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3611 BasicBlock *Header = L->getHeader();
3612
3613 // Push all Loop-header PHIs onto the Worklist stack.
3614 for (BasicBlock::iterator I = Header->begin();
3615 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3616 Worklist.push_back(PN);
3617}
3618
Dan Gohmana1af7572009-04-30 20:47:05 +00003619const ScalarEvolution::BackedgeTakenInfo &
3620ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003621 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003622 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003623 // update the value. The temporary CouldNotCompute value tells SCEV
3624 // code elsewhere that it shouldn't attempt to request a new
3625 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003626 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003627 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3628 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003629 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3630 if (BECount.Exact != getCouldNotCompute()) {
3631 assert(BECount.Exact->isLoopInvariant(L) &&
3632 BECount.Max->isLoopInvariant(L) &&
3633 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003634 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003635
Dan Gohman01ecca22009-04-27 20:16:15 +00003636 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003637 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003638 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003639 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003640 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003641 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003642 if (isa<PHINode>(L->getHeader()->begin()))
3643 // Only count loops that have phi nodes as not being computable.
3644 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003645 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003646
3647 // Now that we know more about the trip count for this loop, forget any
3648 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003649 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003650 // information. This is similar to the code in forgetLoop, except that
3651 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003652 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003653 SmallVector<Instruction *, 16> Worklist;
3654 PushLoopPHIs(L, Worklist);
3655
3656 SmallPtrSet<Instruction *, 8> Visited;
3657 while (!Worklist.empty()) {
3658 Instruction *I = Worklist.pop_back_val();
3659 if (!Visited.insert(I)) continue;
3660
Dan Gohman5d984912009-12-18 01:14:11 +00003661 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003662 Scalars.find(static_cast<Value *>(I));
3663 if (It != Scalars.end()) {
3664 // SCEVUnknown for a PHI either means that it has an unrecognized
3665 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003666 // by createNodeForPHI. In the former case, additional loop trip
3667 // count information isn't going to change anything. In the later
3668 // case, createNodeForPHI will perform the necessary updates on its
3669 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003670 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3671 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003672 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003673 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003674 if (PHINode *PN = dyn_cast<PHINode>(I))
3675 ConstantEvolutionLoopExitValue.erase(PN);
3676 }
3677
3678 PushDefUseChildren(I, Worklist);
3679 }
3680 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003681 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003682 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003683}
3684
Dan Gohman4c7279a2009-10-31 15:04:55 +00003685/// forgetLoop - This method should be called by the client when it has
3686/// changed a loop in a way that may effect ScalarEvolution's ability to
3687/// compute a trip count, or if the loop is deleted.
3688void ScalarEvolution::forgetLoop(const Loop *L) {
3689 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003690 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003691
Dan Gohman4c7279a2009-10-31 15:04:55 +00003692 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003693 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003694 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003695
Dan Gohman59ae6b92009-07-08 19:23:34 +00003696 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003697 while (!Worklist.empty()) {
3698 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003699 if (!Visited.insert(I)) continue;
3700
Dan Gohman5d984912009-12-18 01:14:11 +00003701 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003702 Scalars.find(static_cast<Value *>(I));
3703 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003704 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003705 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003706 if (PHINode *PN = dyn_cast<PHINode>(I))
3707 ConstantEvolutionLoopExitValue.erase(PN);
3708 }
3709
3710 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003711 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003712}
3713
Eric Christophere6cbfa62010-07-29 01:25:38 +00003714/// forgetValue - This method should be called by the client when it has
3715/// changed a value in a way that may effect its value, or which may
3716/// disconnect it from a def-use chain linking it to a loop.
3717void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003718 Instruction *I = dyn_cast<Instruction>(V);
3719 if (!I) return;
3720
3721 // Drop information about expressions based on loop-header PHIs.
3722 SmallVector<Instruction *, 16> Worklist;
3723 Worklist.push_back(I);
3724
3725 SmallPtrSet<Instruction *, 8> Visited;
3726 while (!Worklist.empty()) {
3727 I = Worklist.pop_back_val();
3728 if (!Visited.insert(I)) continue;
3729
3730 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3731 Scalars.find(static_cast<Value *>(I));
3732 if (It != Scalars.end()) {
3733 ValuesAtScopes.erase(It->second);
3734 Scalars.erase(It);
3735 if (PHINode *PN = dyn_cast<PHINode>(I))
3736 ConstantEvolutionLoopExitValue.erase(PN);
3737 }
3738
3739 PushDefUseChildren(I, Worklist);
3740 }
3741}
3742
Dan Gohman46bdfb02009-02-24 18:55:53 +00003743/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3744/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003745ScalarEvolution::BackedgeTakenInfo
3746ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003747 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003748 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003749
Dan Gohmana334aa72009-06-22 00:31:57 +00003750 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003751 const SCEV *BECount = getCouldNotCompute();
3752 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003753 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003754 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3755 BackedgeTakenInfo NewBTI =
3756 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003757
Dan Gohman1c343752009-06-27 21:21:31 +00003758 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003759 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003760 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003761 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003762 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003763 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003764 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003765 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003766 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003767 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003768 }
Dan Gohman1c343752009-06-27 21:21:31 +00003769 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003770 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003771 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003772 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003773 }
3774
3775 return BackedgeTakenInfo(BECount, MaxBECount);
3776}
3777
3778/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3779/// of the specified loop will execute if it exits via the specified block.
3780ScalarEvolution::BackedgeTakenInfo
3781ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3782 BasicBlock *ExitingBlock) {
3783
3784 // Okay, we've chosen an exiting block. See what condition causes us to
3785 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003786 //
3787 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003788 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003789 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003790 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003791
Chris Lattner8b0e3602007-01-07 02:24:26 +00003792 // At this point, we know we have a conditional branch that determines whether
3793 // the loop is exited. However, we don't know if the branch is executed each
3794 // time through the loop. If not, then the execution count of the branch will
3795 // not be equal to the trip count of the loop.
3796 //
3797 // Currently we check for this by checking to see if the Exit branch goes to
3798 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003799 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003800 // loop header. This is common for un-rotated loops.
3801 //
3802 // If both of those tests fail, walk up the unique predecessor chain to the
3803 // header, stopping if there is an edge that doesn't exit the loop. If the
3804 // header is reached, the execution count of the branch will be equal to the
3805 // trip count of the loop.
3806 //
3807 // More extensive analysis could be done to handle more cases here.
3808 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003809 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003810 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003811 ExitBr->getParent() != L->getHeader()) {
3812 // The simple checks failed, try climbing the unique predecessor chain
3813 // up to the header.
3814 bool Ok = false;
3815 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3816 BasicBlock *Pred = BB->getUniquePredecessor();
3817 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003818 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003819 TerminatorInst *PredTerm = Pred->getTerminator();
3820 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3821 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3822 if (PredSucc == BB)
3823 continue;
3824 // If the predecessor has a successor that isn't BB and isn't
3825 // outside the loop, assume the worst.
3826 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003827 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003828 }
3829 if (Pred == L->getHeader()) {
3830 Ok = true;
3831 break;
3832 }
3833 BB = Pred;
3834 }
3835 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003836 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003837 }
3838
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003839 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003840 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3841 ExitBr->getSuccessor(0),
3842 ExitBr->getSuccessor(1));
3843}
3844
3845/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3846/// backedge of the specified loop will execute if its exit condition
3847/// were a conditional branch of ExitCond, TBB, and FBB.
3848ScalarEvolution::BackedgeTakenInfo
3849ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3850 Value *ExitCond,
3851 BasicBlock *TBB,
3852 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003853 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003854 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3855 if (BO->getOpcode() == Instruction::And) {
3856 // Recurse on the operands of the and.
3857 BackedgeTakenInfo BTI0 =
3858 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3859 BackedgeTakenInfo BTI1 =
3860 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003861 const SCEV *BECount = getCouldNotCompute();
3862 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003863 if (L->contains(TBB)) {
3864 // Both conditions must be true for the loop to continue executing.
3865 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003866 if (BTI0.Exact == getCouldNotCompute() ||
3867 BTI1.Exact == getCouldNotCompute())
3868 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003869 else
3870 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003871 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003872 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003873 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003874 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003875 else
3876 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003877 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003878 // Both conditions must be true at the same time for the loop to exit.
3879 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003880 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003881 if (BTI0.Max == BTI1.Max)
3882 MaxBECount = BTI0.Max;
3883 if (BTI0.Exact == BTI1.Exact)
3884 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003885 }
3886
3887 return BackedgeTakenInfo(BECount, MaxBECount);
3888 }
3889 if (BO->getOpcode() == Instruction::Or) {
3890 // Recurse on the operands of the or.
3891 BackedgeTakenInfo BTI0 =
3892 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3893 BackedgeTakenInfo BTI1 =
3894 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003895 const SCEV *BECount = getCouldNotCompute();
3896 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003897 if (L->contains(FBB)) {
3898 // Both conditions must be false for the loop to continue executing.
3899 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003900 if (BTI0.Exact == getCouldNotCompute() ||
3901 BTI1.Exact == getCouldNotCompute())
3902 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003903 else
3904 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003905 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003906 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003907 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003908 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003909 else
3910 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003911 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003912 // Both conditions must be false at the same time for the loop to exit.
3913 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003914 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003915 if (BTI0.Max == BTI1.Max)
3916 MaxBECount = BTI0.Max;
3917 if (BTI0.Exact == BTI1.Exact)
3918 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003919 }
3920
3921 return BackedgeTakenInfo(BECount, MaxBECount);
3922 }
3923 }
3924
3925 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003926 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003927 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3928 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929
Dan Gohman00cb5b72010-02-19 18:12:07 +00003930 // Check for a constant condition. These are normally stripped out by
3931 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3932 // preserve the CFG and is temporarily leaving constant conditions
3933 // in place.
3934 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3935 if (L->contains(FBB) == !CI->getZExtValue())
3936 // The backedge is always taken.
3937 return getCouldNotCompute();
3938 else
3939 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003940 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003941 }
3942
Eli Friedman361e54d2009-05-09 12:32:42 +00003943 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003944 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3945}
3946
3947/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3948/// backedge of the specified loop will execute if its exit condition
3949/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3950ScalarEvolution::BackedgeTakenInfo
3951ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3952 ICmpInst *ExitCond,
3953 BasicBlock *TBB,
3954 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003955
Reid Spencere4d87aa2006-12-23 06:05:41 +00003956 // If the condition was exit on true, convert the condition to exit on false
3957 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003958 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003959 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003960 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003961 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003962
3963 // Handle common loops like: for (X = "string"; *X; ++X)
3964 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3965 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003966 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003967 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003968 if (ItCnt.hasAnyInfo())
3969 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003970 }
3971
Dan Gohman0bba49c2009-07-07 17:06:11 +00003972 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3973 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003974
3975 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003976 LHS = getSCEVAtScope(LHS, L);
3977 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003978
Dan Gohman64a845e2009-06-24 04:48:43 +00003979 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003980 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003981 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3982 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003983 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003985 }
3986
Dan Gohman03557dc2010-05-03 16:35:17 +00003987 // Simplify the operands before analyzing them.
3988 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3989
Chris Lattner53e677a2004-04-02 20:23:17 +00003990 // If we have a comparison of a chrec against a constant, try to use value
3991 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003992 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3993 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003994 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003995 // Form the constant range.
3996 ConstantRange CompRange(
3997 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003998
Dan Gohman0bba49c2009-07-07 17:06:11 +00003999 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004000 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004001 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004002
Chris Lattner53e677a2004-04-02 20:23:17 +00004003 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004004 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004005 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004006 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4007 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004008 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004009 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004010 case ICmpInst::ICMP_EQ: { // while (X == Y)
4011 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004012 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4013 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004014 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004015 }
4016 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004017 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4018 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004019 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004020 }
4021 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004022 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4023 getNotSCEV(RHS), L, true);
4024 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004025 break;
4026 }
4027 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004028 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4029 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004030 break;
4031 }
4032 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004033 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4034 getNotSCEV(RHS), L, false);
4035 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004036 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004037 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004038 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004039#if 0
David Greene25e0e872009-12-23 22:18:14 +00004040 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004041 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004042 dbgs() << "[unsigned] ";
4043 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004044 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004045 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004046#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004047 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004048 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004049 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004050 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004051}
4052
Chris Lattner673e02b2004-10-12 01:49:27 +00004053static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004054EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4055 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004056 const SCEV *InVal = SE.getConstant(C);
4057 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004058 assert(isa<SCEVConstant>(Val) &&
4059 "Evaluation of SCEV at constant didn't fold correctly?");
4060 return cast<SCEVConstant>(Val)->getValue();
4061}
4062
4063/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4064/// and a GEP expression (missing the pointer index) indexing into it, return
4065/// the addressed element of the initializer or null if the index expression is
4066/// invalid.
4067static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004068GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004069 const std::vector<ConstantInt*> &Indices) {
4070 Constant *Init = GV->getInitializer();
4071 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004072 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004073 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4074 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4075 Init = cast<Constant>(CS->getOperand(Idx));
4076 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4077 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4078 Init = cast<Constant>(CA->getOperand(Idx));
4079 } else if (isa<ConstantAggregateZero>(Init)) {
4080 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4081 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004082 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004083 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4084 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004085 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004086 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004087 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004088 }
4089 return 0;
4090 } else {
4091 return 0; // Unknown initializer type
4092 }
4093 }
4094 return Init;
4095}
4096
Dan Gohman46bdfb02009-02-24 18:55:53 +00004097/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4098/// 'icmp op load X, cst', try to see if we can compute the backedge
4099/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004100ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004101ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4102 LoadInst *LI,
4103 Constant *RHS,
4104 const Loop *L,
4105 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004106 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004107
4108 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004109 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004110 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004111 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004112
4113 // Make sure that it is really a constant global we are gepping, with an
4114 // initializer, and make sure the first IDX is really 0.
4115 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004116 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004117 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4118 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004119 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004120
4121 // Okay, we allow one non-constant index into the GEP instruction.
4122 Value *VarIdx = 0;
4123 std::vector<ConstantInt*> Indexes;
4124 unsigned VarIdxNum = 0;
4125 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4126 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4127 Indexes.push_back(CI);
4128 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004129 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004130 VarIdx = GEP->getOperand(i);
4131 VarIdxNum = i-2;
4132 Indexes.push_back(0);
4133 }
4134
4135 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4136 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004137 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004138 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004139
4140 // We can only recognize very limited forms of loop index expressions, in
4141 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004142 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00004143 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4144 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4145 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004146 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004147
4148 unsigned MaxSteps = MaxBruteForceIterations;
4149 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004150 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004151 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004152 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004153
4154 // Form the GEP offset.
4155 Indexes[VarIdxNum] = Val;
4156
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004157 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004158 if (Result == 0) break; // Cannot compute!
4159
4160 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004161 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004162 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004163 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004164#if 0
David Greene25e0e872009-12-23 22:18:14 +00004165 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004166 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4167 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004168#endif
4169 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004170 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004171 }
4172 }
Dan Gohman1c343752009-06-27 21:21:31 +00004173 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004174}
4175
4176
Chris Lattner3221ad02004-04-17 22:58:41 +00004177/// CanConstantFold - Return true if we can constant fold an instruction of the
4178/// specified type, assuming that all operands were constants.
4179static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004180 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004181 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4182 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004183
Chris Lattner3221ad02004-04-17 22:58:41 +00004184 if (const CallInst *CI = dyn_cast<CallInst>(I))
4185 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004186 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004187 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004188}
4189
Chris Lattner3221ad02004-04-17 22:58:41 +00004190/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4191/// in the loop that V is derived from. We allow arbitrary operations along the
4192/// way, but the operands of an operation must either be constants or a value
4193/// derived from a constant PHI. If this expression does not fit with these
4194/// constraints, return null.
4195static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4196 // If this is not an instruction, or if this is an instruction outside of the
4197 // loop, it can't be derived from a loop PHI.
4198 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004199 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004200
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004201 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004202 if (L->getHeader() == I->getParent())
4203 return PN;
4204 else
4205 // We don't currently keep track of the control flow needed to evaluate
4206 // PHIs, so we cannot handle PHIs inside of loops.
4207 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004208 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004209
4210 // If we won't be able to constant fold this expression even if the operands
4211 // are constants, return early.
4212 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004213
Chris Lattner3221ad02004-04-17 22:58:41 +00004214 // Otherwise, we can evaluate this instruction if all of its operands are
4215 // constant or derived from a PHI node themselves.
4216 PHINode *PHI = 0;
4217 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004218 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004219 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4220 if (P == 0) return 0; // Not evolving from PHI
4221 if (PHI == 0)
4222 PHI = P;
4223 else if (PHI != P)
4224 return 0; // Evolving from multiple different PHIs.
4225 }
4226
4227 // This is a expression evolving from a constant PHI!
4228 return PHI;
4229}
4230
4231/// EvaluateExpression - Given an expression that passes the
4232/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4233/// in the loop has the value PHIVal. If we can't fold this expression for some
4234/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004235static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4236 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004237 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004238 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004239 Instruction *I = cast<Instruction>(V);
4240
Dan Gohman9d4588f2010-06-22 13:15:46 +00004241 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004242
4243 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004244 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004245 if (Operands[i] == 0) return 0;
4246 }
4247
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004248 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004249 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004250 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004251 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004252 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004253}
4254
4255/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4256/// in the header of its containing loop, we know the loop executes a
4257/// constant number of times, and the PHI node is just a recurrence
4258/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004259Constant *
4260ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004261 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004262 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004263 std::map<PHINode*, Constant*>::iterator I =
4264 ConstantEvolutionLoopExitValue.find(PN);
4265 if (I != ConstantEvolutionLoopExitValue.end())
4266 return I->second;
4267
Dan Gohmane0567812010-04-08 23:03:40 +00004268 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004269 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4270
4271 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4272
4273 // Since the loop is canonicalized, the PHI node must have two entries. One
4274 // entry must be a constant (coming in from outside of the loop), and the
4275 // second must be derived from the same PHI.
4276 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4277 Constant *StartCST =
4278 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4279 if (StartCST == 0)
4280 return RetVal = 0; // Must be a constant.
4281
4282 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004283 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4284 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004285 return RetVal = 0; // Not derived from same PHI.
4286
4287 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004288 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004289 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004290
Dan Gohman46bdfb02009-02-24 18:55:53 +00004291 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004292 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004293 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4294 if (IterationNum == NumIterations)
4295 return RetVal = PHIVal; // Got exit value!
4296
4297 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004298 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004299 if (NextPHI == PHIVal)
4300 return RetVal = NextPHI; // Stopped evolving!
4301 if (NextPHI == 0)
4302 return 0; // Couldn't evaluate!
4303 PHIVal = NextPHI;
4304 }
4305}
4306
Dan Gohman07ad19b2009-07-27 16:09:48 +00004307/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004308/// constant number of times (the condition evolves only from constants),
4309/// try to evaluate a few iterations of the loop until we get the exit
4310/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004311/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004312const SCEV *
4313ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4314 Value *Cond,
4315 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004316 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004317 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004318
Dan Gohmanb92654d2010-06-19 14:17:24 +00004319 // If the loop is canonicalized, the PHI will have exactly two entries.
4320 // That's the only form we support here.
4321 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4322
4323 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004324 // second must be derived from the same PHI.
4325 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4326 Constant *StartCST =
4327 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004328 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004329
4330 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004331 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4332 !isa<Constant>(BEValue))
4333 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004334
4335 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4336 // the loop symbolically to determine when the condition gets a value of
4337 // "ExitWhen".
4338 unsigned IterationNum = 0;
4339 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4340 for (Constant *PHIVal = StartCST;
4341 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004342 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004343 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004344
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004345 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004346 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004347
Reid Spencere8019bb2007-03-01 07:25:48 +00004348 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004349 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004350 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004351 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004352
Chris Lattner3221ad02004-04-17 22:58:41 +00004353 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004354 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004355 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004356 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004357 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004358 }
4359
4360 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004361 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004362}
4363
Dan Gohmane7125f42009-09-03 15:00:26 +00004364/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004365/// at the specified scope in the program. The L value specifies a loop
4366/// nest to evaluate the expression at, where null is the top-level or a
4367/// specified loop is immediately inside of the loop.
4368///
4369/// This method can be used to compute the exit value for a variable defined
4370/// in a loop by querying what the value will hold in the parent loop.
4371///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004372/// In the case that a relevant loop exit value cannot be computed, the
4373/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004374const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004375 // Check to see if we've folded this expression at this loop before.
4376 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4377 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4378 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4379 if (!Pair.second)
4380 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004381
Dan Gohman42214892009-08-31 21:15:23 +00004382 // Otherwise compute it.
4383 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004384 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004385 return C;
4386}
4387
4388const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004389 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004390
Nick Lewycky3e630762008-02-20 06:48:22 +00004391 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004392 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004393 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004394 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004395 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004396 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4397 if (PHINode *PN = dyn_cast<PHINode>(I))
4398 if (PN->getParent() == LI->getHeader()) {
4399 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004400 // to see if the loop that contains it has a known backedge-taken
4401 // count. If so, we may be able to force computation of the exit
4402 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004403 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004404 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004405 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004406 // Okay, we know how many times the containing loop executes. If
4407 // this is a constant evolving PHI node, get the final value at
4408 // the specified iteration number.
4409 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004410 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004411 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004412 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004413 }
4414 }
4415
Reid Spencer09906f32006-12-04 21:33:23 +00004416 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004417 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004418 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004419 // result. This is particularly useful for computing loop exit values.
4420 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004421 SmallVector<Constant *, 4> Operands;
4422 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004423 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4424 Value *Op = I->getOperand(i);
4425 if (Constant *C = dyn_cast<Constant>(Op)) {
4426 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004427 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004428 }
Dan Gohman11046452010-06-29 23:43:06 +00004429
4430 // If any of the operands is non-constant and if they are
4431 // non-integer and non-pointer, don't even try to analyze them
4432 // with scev techniques.
4433 if (!isSCEVable(Op->getType()))
4434 return V;
4435
4436 const SCEV *OrigV = getSCEV(Op);
4437 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4438 MadeImprovement |= OrigV != OpV;
4439
4440 Constant *C = 0;
4441 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4442 C = SC->getValue();
4443 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4444 C = dyn_cast<Constant>(SU->getValue());
4445 if (!C) return V;
4446 if (C->getType() != Op->getType())
4447 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4448 Op->getType(),
4449 false),
4450 C, Op->getType());
4451 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004452 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004453
Dan Gohman11046452010-06-29 23:43:06 +00004454 // Check to see if getSCEVAtScope actually made an improvement.
4455 if (MadeImprovement) {
4456 Constant *C = 0;
4457 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4458 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4459 Operands[0], Operands[1], TD);
4460 else
4461 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4462 &Operands[0], Operands.size(), TD);
4463 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004464 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004465 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004466 }
4467 }
4468
4469 // This is some other type of SCEVUnknown, just return it.
4470 return V;
4471 }
4472
Dan Gohman622ed672009-05-04 22:02:23 +00004473 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004474 // Avoid performing the look-up in the common case where the specified
4475 // expression has no loop-variant portions.
4476 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004477 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004478 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004479 // Okay, at least one of these operands is loop variant but might be
4480 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004481 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4482 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004483 NewOps.push_back(OpAtScope);
4484
4485 for (++i; i != e; ++i) {
4486 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004487 NewOps.push_back(OpAtScope);
4488 }
4489 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004490 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004491 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004492 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004493 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004494 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004495 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004496 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004497 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004498 }
4499 }
4500 // If we got here, all operands are loop invariant.
4501 return Comm;
4502 }
4503
Dan Gohman622ed672009-05-04 22:02:23 +00004504 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004505 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4506 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004507 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4508 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004509 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004510 }
4511
4512 // If this is a loop recurrence for a loop that does not contain L, then we
4513 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004514 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004515 // First, attempt to evaluate each operand.
4516 // Avoid performing the look-up in the common case where the specified
4517 // expression has no loop-variant portions.
4518 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4519 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4520 if (OpAtScope == AddRec->getOperand(i))
4521 continue;
4522
4523 // Okay, at least one of these operands is loop variant but might be
4524 // foldable. Build a new instance of the folded commutative expression.
4525 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4526 AddRec->op_begin()+i);
4527 NewOps.push_back(OpAtScope);
4528 for (++i; i != e; ++i)
4529 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4530
4531 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4532 break;
4533 }
4534
4535 // If the scope is outside the addrec's loop, evaluate it by using the
4536 // loop exit value of the addrec.
4537 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004538 // To evaluate this recurrence, we need to know how many times the AddRec
4539 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004540 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004541 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004542
Eli Friedmanb42a6262008-08-04 23:49:06 +00004543 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004544 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004545 }
Dan Gohman11046452010-06-29 23:43:06 +00004546
Dan Gohmand594e6f2009-05-24 23:25:42 +00004547 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004548 }
4549
Dan Gohman622ed672009-05-04 22:02:23 +00004550 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004551 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004552 if (Op == Cast->getOperand())
4553 return Cast; // must be loop invariant
4554 return getZeroExtendExpr(Op, Cast->getType());
4555 }
4556
Dan Gohman622ed672009-05-04 22:02:23 +00004557 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004558 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004559 if (Op == Cast->getOperand())
4560 return Cast; // must be loop invariant
4561 return getSignExtendExpr(Op, Cast->getType());
4562 }
4563
Dan Gohman622ed672009-05-04 22:02:23 +00004564 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004565 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004566 if (Op == Cast->getOperand())
4567 return Cast; // must be loop invariant
4568 return getTruncateExpr(Op, Cast->getType());
4569 }
4570
Torok Edwinc23197a2009-07-14 16:55:14 +00004571 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004572 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004573}
4574
Dan Gohman66a7e852009-05-08 20:38:54 +00004575/// getSCEVAtScope - This is a convenience function which does
4576/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004577const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004578 return getSCEVAtScope(getSCEV(V), L);
4579}
4580
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004581/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4582/// following equation:
4583///
4584/// A * X = B (mod N)
4585///
4586/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4587/// A and B isn't important.
4588///
4589/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004590static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004591 ScalarEvolution &SE) {
4592 uint32_t BW = A.getBitWidth();
4593 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4594 assert(A != 0 && "A must be non-zero.");
4595
4596 // 1. D = gcd(A, N)
4597 //
4598 // The gcd of A and N may have only one prime factor: 2. The number of
4599 // trailing zeros in A is its multiplicity
4600 uint32_t Mult2 = A.countTrailingZeros();
4601 // D = 2^Mult2
4602
4603 // 2. Check if B is divisible by D.
4604 //
4605 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4606 // is not less than multiplicity of this prime factor for D.
4607 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004608 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004609
4610 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4611 // modulo (N / D).
4612 //
4613 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4614 // bit width during computations.
4615 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4616 APInt Mod(BW + 1, 0);
4617 Mod.set(BW - Mult2); // Mod = N / D
4618 APInt I = AD.multiplicativeInverse(Mod);
4619
4620 // 4. Compute the minimum unsigned root of the equation:
4621 // I * (B / D) mod (N / D)
4622 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4623
4624 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4625 // bits.
4626 return SE.getConstant(Result.trunc(BW));
4627}
Chris Lattner53e677a2004-04-02 20:23:17 +00004628
4629/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4630/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4631/// might be the same) or two SCEVCouldNotCompute objects.
4632///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004633static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004634SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004635 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004636 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4637 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4638 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004639
Chris Lattner53e677a2004-04-02 20:23:17 +00004640 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004641 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004642 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004643 return std::make_pair(CNC, CNC);
4644 }
4645
Reid Spencere8019bb2007-03-01 07:25:48 +00004646 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004647 const APInt &L = LC->getValue()->getValue();
4648 const APInt &M = MC->getValue()->getValue();
4649 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004650 APInt Two(BitWidth, 2);
4651 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004652
Dan Gohman64a845e2009-06-24 04:48:43 +00004653 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004654 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004655 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004656 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4657 // The B coefficient is M-N/2
4658 APInt B(M);
4659 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004660
Reid Spencere8019bb2007-03-01 07:25:48 +00004661 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004662 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004663
Reid Spencere8019bb2007-03-01 07:25:48 +00004664 // Compute the B^2-4ac term.
4665 APInt SqrtTerm(B);
4666 SqrtTerm *= B;
4667 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004668
Reid Spencere8019bb2007-03-01 07:25:48 +00004669 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4670 // integer value or else APInt::sqrt() will assert.
4671 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004672
Dan Gohman64a845e2009-06-24 04:48:43 +00004673 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004674 // The divisions must be performed as signed divisions.
4675 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004676 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004677 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004678 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004679 return std::make_pair(CNC, CNC);
4680 }
4681
Owen Andersone922c022009-07-22 00:24:57 +00004682 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004683
4684 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004685 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004686 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004687 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004688
Dan Gohman64a845e2009-06-24 04:48:43 +00004689 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004690 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004691 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004692}
4693
4694/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004695/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004696ScalarEvolution::BackedgeTakenInfo
4697ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004698 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004699 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004700 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004701 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004702 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004703 }
4704
Dan Gohman35738ac2009-05-04 22:30:44 +00004705 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004706 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004707 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004708
4709 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004710 // If this is an affine expression, the execution count of this branch is
4711 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004712 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004713 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004714 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004715 // equivalent to:
4716 //
4717 // Step*N = -Start (mod 2^BW)
4718 //
4719 // where BW is the common bit width of Start and Step.
4720
Chris Lattner53e677a2004-04-02 20:23:17 +00004721 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004722 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4723 L->getParentLoop());
4724 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4725 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004726
Dan Gohman622ed672009-05-04 22:02:23 +00004727 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004728 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004729
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004730 // First, handle unitary steps.
4731 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004732 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004733 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4734 return Start; // N = Start (as unsigned)
4735
4736 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004737 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004738 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004739 -StartC->getValue()->getValue(),
4740 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004741 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004742 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004743 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4744 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004745 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004746 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004747 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4748 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004749 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004750#if 0
David Greene25e0e872009-12-23 22:18:14 +00004751 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004752 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004753#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004754 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004755 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004756 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004758 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004759 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004760
Chris Lattner53e677a2004-04-02 20:23:17 +00004761 // We can only use this value if the chrec ends up with an exact zero
4762 // value at this index. When solving for "X*X != 5", for example, we
4763 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004764 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004765 if (Val->isZero())
4766 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004767 }
4768 }
4769 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004770
Dan Gohman1c343752009-06-27 21:21:31 +00004771 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004772}
4773
4774/// HowFarToNonZero - Return the number of times a backedge checking the
4775/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004776/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004777ScalarEvolution::BackedgeTakenInfo
4778ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004779 // Loops that look like: while (X == 0) are very strange indeed. We don't
4780 // handle them yet except for the trivial case. This could be expanded in the
4781 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004782
Chris Lattner53e677a2004-04-02 20:23:17 +00004783 // If the value is a constant, check to see if it is known to be non-zero
4784 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004785 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004786 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004787 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004788 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004789 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004790
Chris Lattner53e677a2004-04-02 20:23:17 +00004791 // We could implement others, but I really doubt anyone writes loops like
4792 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004793 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004794}
4795
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004796/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4797/// (which may not be an immediate predecessor) which has exactly one
4798/// successor from which BB is reachable, or null if no such block is
4799/// found.
4800///
Dan Gohman005752b2010-04-15 16:19:08 +00004801std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004802ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004803 // If the block has a unique predecessor, then there is no path from the
4804 // predecessor to the block that does not go through the direct edge
4805 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004806 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004807 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004808
4809 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004810 // If the header has a unique predecessor outside the loop, it must be
4811 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004812 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004813 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004814
Dan Gohman005752b2010-04-15 16:19:08 +00004815 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004816}
4817
Dan Gohman763bad12009-06-20 00:35:32 +00004818/// HasSameValue - SCEV structural equivalence is usually sufficient for
4819/// testing whether two expressions are equal, however for the purposes of
4820/// looking for a condition guarding a loop, it can be useful to be a little
4821/// more general, since a front-end may have replicated the controlling
4822/// expression.
4823///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004824static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004825 // Quick check to see if they are the same SCEV.
4826 if (A == B) return true;
4827
4828 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4829 // two different instructions with the same value. Check for this case.
4830 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4831 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4832 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4833 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004834 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004835 return true;
4836
4837 // Otherwise assume they may have a different value.
4838 return false;
4839}
4840
Dan Gohmane9796502010-04-24 01:28:42 +00004841/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4842/// predicate Pred. Return true iff any changes were made.
4843///
4844bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4845 const SCEV *&LHS, const SCEV *&RHS) {
4846 bool Changed = false;
4847
4848 // Canonicalize a constant to the right side.
4849 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4850 // Check for both operands constant.
4851 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4852 if (ConstantExpr::getICmp(Pred,
4853 LHSC->getValue(),
4854 RHSC->getValue())->isNullValue())
4855 goto trivially_false;
4856 else
4857 goto trivially_true;
4858 }
4859 // Otherwise swap the operands to put the constant on the right.
4860 std::swap(LHS, RHS);
4861 Pred = ICmpInst::getSwappedPredicate(Pred);
4862 Changed = true;
4863 }
4864
4865 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004866 // addrec's loop, put the addrec on the left. Also make a dominance check,
4867 // as both operands could be addrecs loop-invariant in each other's loop.
4868 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4869 const Loop *L = AR->getLoop();
4870 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004871 std::swap(LHS, RHS);
4872 Pred = ICmpInst::getSwappedPredicate(Pred);
4873 Changed = true;
4874 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004875 }
Dan Gohmane9796502010-04-24 01:28:42 +00004876
4877 // If there's a constant operand, canonicalize comparisons with boundary
4878 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4879 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4880 const APInt &RA = RC->getValue()->getValue();
4881 switch (Pred) {
4882 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4883 case ICmpInst::ICMP_EQ:
4884 case ICmpInst::ICMP_NE:
4885 break;
4886 case ICmpInst::ICMP_UGE:
4887 if ((RA - 1).isMinValue()) {
4888 Pred = ICmpInst::ICMP_NE;
4889 RHS = getConstant(RA - 1);
4890 Changed = true;
4891 break;
4892 }
4893 if (RA.isMaxValue()) {
4894 Pred = ICmpInst::ICMP_EQ;
4895 Changed = true;
4896 break;
4897 }
4898 if (RA.isMinValue()) goto trivially_true;
4899
4900 Pred = ICmpInst::ICMP_UGT;
4901 RHS = getConstant(RA - 1);
4902 Changed = true;
4903 break;
4904 case ICmpInst::ICMP_ULE:
4905 if ((RA + 1).isMaxValue()) {
4906 Pred = ICmpInst::ICMP_NE;
4907 RHS = getConstant(RA + 1);
4908 Changed = true;
4909 break;
4910 }
4911 if (RA.isMinValue()) {
4912 Pred = ICmpInst::ICMP_EQ;
4913 Changed = true;
4914 break;
4915 }
4916 if (RA.isMaxValue()) goto trivially_true;
4917
4918 Pred = ICmpInst::ICMP_ULT;
4919 RHS = getConstant(RA + 1);
4920 Changed = true;
4921 break;
4922 case ICmpInst::ICMP_SGE:
4923 if ((RA - 1).isMinSignedValue()) {
4924 Pred = ICmpInst::ICMP_NE;
4925 RHS = getConstant(RA - 1);
4926 Changed = true;
4927 break;
4928 }
4929 if (RA.isMaxSignedValue()) {
4930 Pred = ICmpInst::ICMP_EQ;
4931 Changed = true;
4932 break;
4933 }
4934 if (RA.isMinSignedValue()) goto trivially_true;
4935
4936 Pred = ICmpInst::ICMP_SGT;
4937 RHS = getConstant(RA - 1);
4938 Changed = true;
4939 break;
4940 case ICmpInst::ICMP_SLE:
4941 if ((RA + 1).isMaxSignedValue()) {
4942 Pred = ICmpInst::ICMP_NE;
4943 RHS = getConstant(RA + 1);
4944 Changed = true;
4945 break;
4946 }
4947 if (RA.isMinSignedValue()) {
4948 Pred = ICmpInst::ICMP_EQ;
4949 Changed = true;
4950 break;
4951 }
4952 if (RA.isMaxSignedValue()) goto trivially_true;
4953
4954 Pred = ICmpInst::ICMP_SLT;
4955 RHS = getConstant(RA + 1);
4956 Changed = true;
4957 break;
4958 case ICmpInst::ICMP_UGT:
4959 if (RA.isMinValue()) {
4960 Pred = ICmpInst::ICMP_NE;
4961 Changed = true;
4962 break;
4963 }
4964 if ((RA + 1).isMaxValue()) {
4965 Pred = ICmpInst::ICMP_EQ;
4966 RHS = getConstant(RA + 1);
4967 Changed = true;
4968 break;
4969 }
4970 if (RA.isMaxValue()) goto trivially_false;
4971 break;
4972 case ICmpInst::ICMP_ULT:
4973 if (RA.isMaxValue()) {
4974 Pred = ICmpInst::ICMP_NE;
4975 Changed = true;
4976 break;
4977 }
4978 if ((RA - 1).isMinValue()) {
4979 Pred = ICmpInst::ICMP_EQ;
4980 RHS = getConstant(RA - 1);
4981 Changed = true;
4982 break;
4983 }
4984 if (RA.isMinValue()) goto trivially_false;
4985 break;
4986 case ICmpInst::ICMP_SGT:
4987 if (RA.isMinSignedValue()) {
4988 Pred = ICmpInst::ICMP_NE;
4989 Changed = true;
4990 break;
4991 }
4992 if ((RA + 1).isMaxSignedValue()) {
4993 Pred = ICmpInst::ICMP_EQ;
4994 RHS = getConstant(RA + 1);
4995 Changed = true;
4996 break;
4997 }
4998 if (RA.isMaxSignedValue()) goto trivially_false;
4999 break;
5000 case ICmpInst::ICMP_SLT:
5001 if (RA.isMaxSignedValue()) {
5002 Pred = ICmpInst::ICMP_NE;
5003 Changed = true;
5004 break;
5005 }
5006 if ((RA - 1).isMinSignedValue()) {
5007 Pred = ICmpInst::ICMP_EQ;
5008 RHS = getConstant(RA - 1);
5009 Changed = true;
5010 break;
5011 }
5012 if (RA.isMinSignedValue()) goto trivially_false;
5013 break;
5014 }
5015 }
5016
5017 // Check for obvious equality.
5018 if (HasSameValue(LHS, RHS)) {
5019 if (ICmpInst::isTrueWhenEqual(Pred))
5020 goto trivially_true;
5021 if (ICmpInst::isFalseWhenEqual(Pred))
5022 goto trivially_false;
5023 }
5024
Dan Gohman03557dc2010-05-03 16:35:17 +00005025 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5026 // adding or subtracting 1 from one of the operands.
5027 switch (Pred) {
5028 case ICmpInst::ICMP_SLE:
5029 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5030 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5031 /*HasNUW=*/false, /*HasNSW=*/true);
5032 Pred = ICmpInst::ICMP_SLT;
5033 Changed = true;
5034 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005035 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005036 /*HasNUW=*/false, /*HasNSW=*/true);
5037 Pred = ICmpInst::ICMP_SLT;
5038 Changed = true;
5039 }
5040 break;
5041 case ICmpInst::ICMP_SGE:
5042 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005043 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005044 /*HasNUW=*/false, /*HasNSW=*/true);
5045 Pred = ICmpInst::ICMP_SGT;
5046 Changed = true;
5047 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5048 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5049 /*HasNUW=*/false, /*HasNSW=*/true);
5050 Pred = ICmpInst::ICMP_SGT;
5051 Changed = true;
5052 }
5053 break;
5054 case ICmpInst::ICMP_ULE:
5055 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005056 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005057 /*HasNUW=*/true, /*HasNSW=*/false);
5058 Pred = ICmpInst::ICMP_ULT;
5059 Changed = true;
5060 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005061 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005062 /*HasNUW=*/true, /*HasNSW=*/false);
5063 Pred = ICmpInst::ICMP_ULT;
5064 Changed = true;
5065 }
5066 break;
5067 case ICmpInst::ICMP_UGE:
5068 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005069 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005070 /*HasNUW=*/true, /*HasNSW=*/false);
5071 Pred = ICmpInst::ICMP_UGT;
5072 Changed = true;
5073 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005074 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005075 /*HasNUW=*/true, /*HasNSW=*/false);
5076 Pred = ICmpInst::ICMP_UGT;
5077 Changed = true;
5078 }
5079 break;
5080 default:
5081 break;
5082 }
5083
Dan Gohmane9796502010-04-24 01:28:42 +00005084 // TODO: More simplifications are possible here.
5085
5086 return Changed;
5087
5088trivially_true:
5089 // Return 0 == 0.
5090 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5091 Pred = ICmpInst::ICMP_EQ;
5092 return true;
5093
5094trivially_false:
5095 // Return 0 != 0.
5096 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5097 Pred = ICmpInst::ICMP_NE;
5098 return true;
5099}
5100
Dan Gohman85b05a22009-07-13 21:35:55 +00005101bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5102 return getSignedRange(S).getSignedMax().isNegative();
5103}
5104
5105bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5106 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5107}
5108
5109bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5110 return !getSignedRange(S).getSignedMin().isNegative();
5111}
5112
5113bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5114 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5115}
5116
5117bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5118 return isKnownNegative(S) || isKnownPositive(S);
5119}
5120
5121bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5122 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005123 // Canonicalize the inputs first.
5124 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5125
Dan Gohman53c66ea2010-04-11 22:16:48 +00005126 // If LHS or RHS is an addrec, check to see if the condition is true in
5127 // every iteration of the loop.
5128 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5129 if (isLoopEntryGuardedByCond(
5130 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5131 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005132 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005133 return true;
5134 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5135 if (isLoopEntryGuardedByCond(
5136 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5137 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005138 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005139 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005140
Dan Gohman53c66ea2010-04-11 22:16:48 +00005141 // Otherwise see what can be done with known constant ranges.
5142 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5143}
5144
5145bool
5146ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5147 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005148 if (HasSameValue(LHS, RHS))
5149 return ICmpInst::isTrueWhenEqual(Pred);
5150
Dan Gohman53c66ea2010-04-11 22:16:48 +00005151 // This code is split out from isKnownPredicate because it is called from
5152 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005153 switch (Pred) {
5154 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005155 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005156 break;
5157 case ICmpInst::ICMP_SGT:
5158 Pred = ICmpInst::ICMP_SLT;
5159 std::swap(LHS, RHS);
5160 case ICmpInst::ICMP_SLT: {
5161 ConstantRange LHSRange = getSignedRange(LHS);
5162 ConstantRange RHSRange = getSignedRange(RHS);
5163 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5164 return true;
5165 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5166 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005167 break;
5168 }
5169 case ICmpInst::ICMP_SGE:
5170 Pred = ICmpInst::ICMP_SLE;
5171 std::swap(LHS, RHS);
5172 case ICmpInst::ICMP_SLE: {
5173 ConstantRange LHSRange = getSignedRange(LHS);
5174 ConstantRange RHSRange = getSignedRange(RHS);
5175 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5176 return true;
5177 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5178 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005179 break;
5180 }
5181 case ICmpInst::ICMP_UGT:
5182 Pred = ICmpInst::ICMP_ULT;
5183 std::swap(LHS, RHS);
5184 case ICmpInst::ICMP_ULT: {
5185 ConstantRange LHSRange = getUnsignedRange(LHS);
5186 ConstantRange RHSRange = getUnsignedRange(RHS);
5187 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5188 return true;
5189 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5190 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005191 break;
5192 }
5193 case ICmpInst::ICMP_UGE:
5194 Pred = ICmpInst::ICMP_ULE;
5195 std::swap(LHS, RHS);
5196 case ICmpInst::ICMP_ULE: {
5197 ConstantRange LHSRange = getUnsignedRange(LHS);
5198 ConstantRange RHSRange = getUnsignedRange(RHS);
5199 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5200 return true;
5201 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5202 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005203 break;
5204 }
5205 case ICmpInst::ICMP_NE: {
5206 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5207 return true;
5208 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5209 return true;
5210
5211 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5212 if (isKnownNonZero(Diff))
5213 return true;
5214 break;
5215 }
5216 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005217 // The check at the top of the function catches the case where
5218 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005219 break;
5220 }
5221 return false;
5222}
5223
5224/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5225/// protected by a conditional between LHS and RHS. This is used to
5226/// to eliminate casts.
5227bool
5228ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5229 ICmpInst::Predicate Pred,
5230 const SCEV *LHS, const SCEV *RHS) {
5231 // Interpret a null as meaning no loop, where there is obviously no guard
5232 // (interprocedural conditions notwithstanding).
5233 if (!L) return true;
5234
5235 BasicBlock *Latch = L->getLoopLatch();
5236 if (!Latch)
5237 return false;
5238
5239 BranchInst *LoopContinuePredicate =
5240 dyn_cast<BranchInst>(Latch->getTerminator());
5241 if (!LoopContinuePredicate ||
5242 LoopContinuePredicate->isUnconditional())
5243 return false;
5244
Dan Gohmanaf08a362010-08-10 23:46:30 +00005245 return isImpliedCond(Pred, LHS, RHS,
5246 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005247 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005248}
5249
Dan Gohman3948d0b2010-04-11 19:27:13 +00005250/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005251/// by a conditional between LHS and RHS. This is used to help avoid max
5252/// expressions in loop trip counts, and to eliminate casts.
5253bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005254ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5255 ICmpInst::Predicate Pred,
5256 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005257 // Interpret a null as meaning no loop, where there is obviously no guard
5258 // (interprocedural conditions notwithstanding).
5259 if (!L) return false;
5260
Dan Gohman859b4822009-05-18 15:36:09 +00005261 // Starting at the loop predecessor, climb up the predecessor chain, as long
5262 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005263 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005264 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005265 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005266 Pair.first;
5267 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005268
5269 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005270 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005271 if (!LoopEntryPredicate ||
5272 LoopEntryPredicate->isUnconditional())
5273 continue;
5274
Dan Gohmanaf08a362010-08-10 23:46:30 +00005275 if (isImpliedCond(Pred, LHS, RHS,
5276 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005277 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005278 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005279 }
5280
Dan Gohman38372182008-08-12 20:17:31 +00005281 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005282}
5283
Dan Gohman0f4b2852009-07-21 23:03:19 +00005284/// isImpliedCond - Test whether the condition described by Pred, LHS,
5285/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005286bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005287 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005288 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005289 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005290 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005292 if (BO->getOpcode() == Instruction::And) {
5293 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005294 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5295 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005296 } else if (BO->getOpcode() == Instruction::Or) {
5297 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005298 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5299 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005300 }
5301 }
5302
Dan Gohmanaf08a362010-08-10 23:46:30 +00005303 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005304 if (!ICI) return false;
5305
Dan Gohman85b05a22009-07-13 21:35:55 +00005306 // Bail if the ICmp's operands' types are wider than the needed type
5307 // before attempting to call getSCEV on them. This avoids infinite
5308 // recursion, since the analysis of widening casts can require loop
5309 // exit condition information for overflow checking, which would
5310 // lead back here.
5311 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005312 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005313 return false;
5314
Dan Gohman0f4b2852009-07-21 23:03:19 +00005315 // Now that we found a conditional branch that dominates the loop, check to
5316 // see if it is the comparison we are looking for.
5317 ICmpInst::Predicate FoundPred;
5318 if (Inverse)
5319 FoundPred = ICI->getInversePredicate();
5320 else
5321 FoundPred = ICI->getPredicate();
5322
5323 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5324 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005325
5326 // Balance the types. The case where FoundLHS' type is wider than
5327 // LHS' type is checked for above.
5328 if (getTypeSizeInBits(LHS->getType()) >
5329 getTypeSizeInBits(FoundLHS->getType())) {
5330 if (CmpInst::isSigned(Pred)) {
5331 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5332 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5333 } else {
5334 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5335 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5336 }
5337 }
5338
Dan Gohman0f4b2852009-07-21 23:03:19 +00005339 // Canonicalize the query to match the way instcombine will have
5340 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005341 if (SimplifyICmpOperands(Pred, LHS, RHS))
5342 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005343 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005344 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5345 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005346 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005347
5348 // Check to see if we can make the LHS or RHS match.
5349 if (LHS == FoundRHS || RHS == FoundLHS) {
5350 if (isa<SCEVConstant>(RHS)) {
5351 std::swap(FoundLHS, FoundRHS);
5352 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5353 } else {
5354 std::swap(LHS, RHS);
5355 Pred = ICmpInst::getSwappedPredicate(Pred);
5356 }
5357 }
5358
5359 // Check whether the found predicate is the same as the desired predicate.
5360 if (FoundPred == Pred)
5361 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5362
5363 // Check whether swapping the found predicate makes it the same as the
5364 // desired predicate.
5365 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5366 if (isa<SCEVConstant>(RHS))
5367 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5368 else
5369 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5370 RHS, LHS, FoundLHS, FoundRHS);
5371 }
5372
5373 // Check whether the actual condition is beyond sufficient.
5374 if (FoundPred == ICmpInst::ICMP_EQ)
5375 if (ICmpInst::isTrueWhenEqual(Pred))
5376 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5377 return true;
5378 if (Pred == ICmpInst::ICMP_NE)
5379 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5380 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5381 return true;
5382
5383 // Otherwise assume the worst.
5384 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005385}
5386
Dan Gohman0f4b2852009-07-21 23:03:19 +00005387/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005388/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005389/// and FoundRHS is true.
5390bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5391 const SCEV *LHS, const SCEV *RHS,
5392 const SCEV *FoundLHS,
5393 const SCEV *FoundRHS) {
5394 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5395 FoundLHS, FoundRHS) ||
5396 // ~x < ~y --> x > y
5397 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5398 getNotSCEV(FoundRHS),
5399 getNotSCEV(FoundLHS));
5400}
5401
5402/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005403/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005404/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005405bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005406ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5407 const SCEV *LHS, const SCEV *RHS,
5408 const SCEV *FoundLHS,
5409 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005410 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005411 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5412 case ICmpInst::ICMP_EQ:
5413 case ICmpInst::ICMP_NE:
5414 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5415 return true;
5416 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005417 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005418 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005419 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5420 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005421 return true;
5422 break;
5423 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005424 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005425 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5426 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005427 return true;
5428 break;
5429 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005430 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005431 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5432 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005433 return true;
5434 break;
5435 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005436 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005437 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5438 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005439 return true;
5440 break;
5441 }
5442
5443 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005444}
5445
Dan Gohman51f53b72009-06-21 23:46:38 +00005446/// getBECount - Subtract the end and start values and divide by the step,
5447/// rounding up, to get the number of times the backedge is executed. Return
5448/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005449const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005450 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005451 const SCEV *Step,
5452 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005453 assert(!isKnownNegative(Step) &&
5454 "This code doesn't handle negative strides yet!");
5455
Dan Gohman51f53b72009-06-21 23:46:38 +00005456 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005457 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005458 const SCEV *Diff = getMinusSCEV(End, Start);
5459 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005460
5461 // Add an adjustment to the difference between End and Start so that
5462 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005463 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005464
Dan Gohman1f96e672009-09-17 18:05:20 +00005465 if (!NoWrap) {
5466 // Check Add for unsigned overflow.
5467 // TODO: More sophisticated things could be done here.
5468 const Type *WideTy = IntegerType::get(getContext(),
5469 getTypeSizeInBits(Ty) + 1);
5470 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5471 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5472 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5473 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5474 return getCouldNotCompute();
5475 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005476
5477 return getUDivExpr(Add, Step);
5478}
5479
Chris Lattnerdb25de42005-08-15 23:33:51 +00005480/// HowManyLessThans - Return the number of times a backedge containing the
5481/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005482/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005483ScalarEvolution::BackedgeTakenInfo
5484ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5485 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005486 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005487 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005488
Dan Gohman35738ac2009-05-04 22:30:44 +00005489 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005490 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005491 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005492
Dan Gohman1f96e672009-09-17 18:05:20 +00005493 // Check to see if we have a flag which makes analysis easy.
5494 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5495 AddRec->hasNoUnsignedWrap();
5496
Chris Lattnerdb25de42005-08-15 23:33:51 +00005497 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005498 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005499 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005500
Dan Gohman52fddd32010-01-26 04:40:18 +00005501 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005502 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005503 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005504 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005505 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005506 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005507 // value and past the maximum value for its type in a single step.
5508 // Note that it's not sufficient to check NoWrap here, because even
5509 // though the value after a wrap is undefined, it's not undefined
5510 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005511 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005512 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005513 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005514 if (isSigned) {
5515 APInt Max = APInt::getSignedMaxValue(BitWidth);
5516 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5517 .slt(getSignedRange(RHS).getSignedMax()))
5518 return getCouldNotCompute();
5519 } else {
5520 APInt Max = APInt::getMaxValue(BitWidth);
5521 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5522 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5523 return getCouldNotCompute();
5524 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005525 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005526 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005527 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005528
Dan Gohmana1af7572009-04-30 20:47:05 +00005529 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5530 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5531 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005532 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005533
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005534 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005535 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005536
Dan Gohmana1af7572009-04-30 20:47:05 +00005537 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005538 const SCEV *MinStart = getConstant(isSigned ?
5539 getSignedRange(Start).getSignedMin() :
5540 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005541
Dan Gohmana1af7572009-04-30 20:47:05 +00005542 // If we know that the condition is true in order to enter the loop,
5543 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005544 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5545 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005546 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005547 if (!isLoopEntryGuardedByCond(L,
5548 isSigned ? ICmpInst::ICMP_SLT :
5549 ICmpInst::ICMP_ULT,
5550 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005551 End = isSigned ? getSMaxExpr(RHS, Start)
5552 : getUMaxExpr(RHS, Start);
5553
5554 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005555 const SCEV *MaxEnd = getConstant(isSigned ?
5556 getSignedRange(End).getSignedMax() :
5557 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005558
Dan Gohman52fddd32010-01-26 04:40:18 +00005559 // If MaxEnd is within a step of the maximum integer value in its type,
5560 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005561 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005562 // compute the correct value.
5563 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005564 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005565 MaxEnd = isSigned ?
5566 getSMinExpr(MaxEnd,
5567 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5568 StepMinusOne)) :
5569 getUMinExpr(MaxEnd,
5570 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5571 StepMinusOne));
5572
Dan Gohmana1af7572009-04-30 20:47:05 +00005573 // Finally, we subtract these two values and divide, rounding up, to get
5574 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005575 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005576
5577 // The maximum backedge count is similar, except using the minimum start
5578 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005579 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005580
5581 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005582 }
5583
Dan Gohman1c343752009-06-27 21:21:31 +00005584 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005585}
5586
Chris Lattner53e677a2004-04-02 20:23:17 +00005587/// getNumIterationsInRange - Return the number of iterations of this loop that
5588/// produce values in the specified constant range. Another way of looking at
5589/// this is that it returns the first iteration number where the value is not in
5590/// the condition, thus computing the exit count. If the iteration count can't
5591/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005592const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005593 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005594 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005595 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005596
5597 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005598 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005599 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005600 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005601 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005602 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005603 if (const SCEVAddRecExpr *ShiftedAddRec =
5604 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005605 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005606 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005607 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005608 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005609 }
5610
5611 // The only time we can solve this is when we have all constant indices.
5612 // Otherwise, we cannot determine the overflow conditions.
5613 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5614 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005615 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005616
5617
5618 // Okay at this point we know that all elements of the chrec are constants and
5619 // that the start element is zero.
5620
5621 // First check to see if the range contains zero. If not, the first
5622 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005623 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005624 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005625 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005626
Chris Lattner53e677a2004-04-02 20:23:17 +00005627 if (isAffine()) {
5628 // If this is an affine expression then we have this situation:
5629 // Solve {0,+,A} in Range === Ax in Range
5630
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005631 // We know that zero is in the range. If A is positive then we know that
5632 // the upper value of the range must be the first possible exit value.
5633 // If A is negative then the lower of the range is the last possible loop
5634 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005635 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005636 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5637 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005638
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005639 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005640 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005641 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005642
5643 // Evaluate at the exit value. If we really did fall out of the valid
5644 // range, then we computed our trip count, otherwise wrap around or other
5645 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005646 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005647 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005648 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005649
5650 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005651 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005652 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005653 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005654 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005655 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005656 } else if (isQuadratic()) {
5657 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5658 // quadratic equation to solve it. To do this, we must frame our problem in
5659 // terms of figuring out when zero is crossed, instead of when
5660 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005661 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005662 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005663 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005664
5665 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005666 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005667 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005668 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5669 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005670 if (R1) {
5671 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005672 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005673 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005674 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005675 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005676 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005677
Chris Lattner53e677a2004-04-02 20:23:17 +00005678 // Make sure the root is not off by one. The returned iteration should
5679 // not be in the range, but the previous one should be. When solving
5680 // for "X*X < 5", for example, we should not return a root of 2.
5681 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005682 R1->getValue(),
5683 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005684 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005685 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005686 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005687 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005688
Dan Gohman246b2562007-10-22 18:31:58 +00005689 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005690 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005691 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005692 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005693 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005694
Chris Lattner53e677a2004-04-02 20:23:17 +00005695 // If R1 was not in the range, then it is a good return value. Make
5696 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005697 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005698 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005699 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005700 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005701 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005702 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005703 }
5704 }
5705 }
5706
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005707 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005708}
5709
5710
5711
5712//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005713// SCEVCallbackVH Class Implementation
5714//===----------------------------------------------------------------------===//
5715
Dan Gohman1959b752009-05-19 19:22:47 +00005716void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005717 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005718 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5719 SE->ConstantEvolutionLoopExitValue.erase(PN);
5720 SE->Scalars.erase(getValPtr());
5721 // this now dangles!
5722}
5723
Dan Gohman81f91212010-07-28 01:09:07 +00005724void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005725 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005726
Dan Gohman35738ac2009-05-04 22:30:44 +00005727 // Forget all the expressions associated with users of the old value,
5728 // so that future queries will recompute the expressions using the new
5729 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005730 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005731 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005732 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005733 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5734 UI != UE; ++UI)
5735 Worklist.push_back(*UI);
5736 while (!Worklist.empty()) {
5737 User *U = Worklist.pop_back_val();
5738 // Deleting the Old value will cause this to dangle. Postpone
5739 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005740 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005741 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005742 if (!Visited.insert(U))
5743 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005744 if (PHINode *PN = dyn_cast<PHINode>(U))
5745 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005746 SE->Scalars.erase(U);
5747 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5748 UI != UE; ++UI)
5749 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005750 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005751 // Delete the Old value.
5752 if (PHINode *PN = dyn_cast<PHINode>(Old))
5753 SE->ConstantEvolutionLoopExitValue.erase(PN);
5754 SE->Scalars.erase(Old);
5755 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005756}
5757
Dan Gohman1959b752009-05-19 19:22:47 +00005758ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005759 : CallbackVH(V), SE(se) {}
5760
5761//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005762// ScalarEvolution Class Implementation
5763//===----------------------------------------------------------------------===//
5764
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005765ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005766 : FunctionPass(ID), FirstUnknown(0) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005767}
5768
Chris Lattner53e677a2004-04-02 20:23:17 +00005769bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005770 this->F = &F;
5771 LI = &getAnalysis<LoopInfo>();
5772 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005773 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005774 return false;
5775}
5776
5777void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005778 // Iterate through all the SCEVUnknown instances and call their
5779 // destructors, so that they release their references to their values.
5780 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5781 U->~SCEVUnknown();
5782 FirstUnknown = 0;
5783
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005784 Scalars.clear();
5785 BackedgeTakenCounts.clear();
5786 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005787 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005788 UniqueSCEVs.clear();
5789 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005790}
5791
5792void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5793 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005794 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005795 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005796}
5797
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005798bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005799 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005800}
5801
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005802static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005803 const Loop *L) {
5804 // Print all inner loops first
5805 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5806 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005807
Dan Gohman30733292010-01-09 18:17:45 +00005808 OS << "Loop ";
5809 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5810 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005811
Dan Gohman5d984912009-12-18 01:14:11 +00005812 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005813 L->getExitBlocks(ExitBlocks);
5814 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005815 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005816
Dan Gohman46bdfb02009-02-24 18:55:53 +00005817 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5818 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005819 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005820 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005821 }
5822
Dan Gohman30733292010-01-09 18:17:45 +00005823 OS << "\n"
5824 "Loop ";
5825 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5826 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005827
5828 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5829 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5830 } else {
5831 OS << "Unpredictable max backedge-taken count. ";
5832 }
5833
5834 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005835}
5836
Dan Gohman5d984912009-12-18 01:14:11 +00005837void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005838 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005839 // out SCEV values of all instructions that are interesting. Doing
5840 // this potentially causes it to create new SCEV objects though,
5841 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005842 // observable from outside the class though, so casting away the
5843 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005844 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005845
Dan Gohman30733292010-01-09 18:17:45 +00005846 OS << "Classifying expressions for: ";
5847 WriteAsOperand(OS, F, /*PrintType=*/false);
5848 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005849 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005850 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005851 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005852 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005853 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005854 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005855
Dan Gohman0c689c52009-06-19 17:49:54 +00005856 const Loop *L = LI->getLoopFor((*I).getParent());
5857
Dan Gohman0bba49c2009-07-07 17:06:11 +00005858 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005859 if (AtUse != SV) {
5860 OS << " --> ";
5861 AtUse->print(OS);
5862 }
5863
5864 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005865 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005866 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005867 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005868 OS << "<<Unknown>>";
5869 } else {
5870 OS << *ExitValue;
5871 }
5872 }
5873
Chris Lattner53e677a2004-04-02 20:23:17 +00005874 OS << "\n";
5875 }
5876
Dan Gohman30733292010-01-09 18:17:45 +00005877 OS << "Determining loop execution counts for: ";
5878 WriteAsOperand(OS, F, /*PrintType=*/false);
5879 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005880 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5881 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005882}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005883