blob: 47ec3046e57defa1af8ae0487c37e2248ce034f4 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Owen Andersond13db2c2010-07-21 22:09:45 +0000106INITIALIZE_PASS(ScalarEvolution, "scalar-evolution",
107 "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000144 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000180 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000181 UniqueSCEVs.InsertNode(S, IP);
182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000186 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Dan Gohman0bba49c2009-07-07 17:06:11 +0000189const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000191 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
192 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000193}
194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Dan Gohman3bf63762010-06-18 19:54:20 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000204
Dan Gohman84923602009-04-21 01:25:57 +0000205bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
207}
208
Dan Gohman6e70e312009-09-27 15:26:03 +0000209bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
211}
212
Dan Gohman3bf63762010-06-18 19:54:20 +0000213SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000215 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000216 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
217 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
Dan Gohman3bf63762010-06-18 19:54:20 +0000225SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000228 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
229 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000233void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
236
Dan Gohman3bf63762010-06-18 19:54:20 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000240 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
241 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000242 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000243}
244
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000245void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000247}
248
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000249void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250 const char *OpStr = getOperationStr();
Dan Gohmana5145c82010-04-16 15:03:25 +0000251 OS << "(";
252 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
253 OS << **I;
Oscar Fuentesee56c422010-08-02 06:00:15 +0000254 if (llvm::next(I) != E)
Dan Gohmana5145c82010-04-16 15:03:25 +0000255 OS << OpStr;
256 }
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000257 OS << ")";
258}
259
Dan Gohmanecb403a2009-05-07 14:00:19 +0000260bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
263 return false;
264 }
265 return true;
266}
267
Dan Gohman6e70e312009-09-27 15:26:03 +0000268bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
270 if (!getOperand(i)->properlyDominates(BB, DT))
271 return false;
272 }
273 return true;
274}
275
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000276bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
277 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
278}
279
Dan Gohman6e70e312009-09-27 15:26:03 +0000280bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
281 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
282}
283
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000284void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000285 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000286}
287
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000288const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000289 // In most cases the types of LHS and RHS will be the same, but in some
290 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
291 // depend on the type for correctness, but handling types carefully can
292 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
293 // a pointer type than the RHS, so use the RHS' type here.
294 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000295}
296
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000298 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000299 if (!QueryLoop)
300 return false;
301
302 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000303 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000304 return false;
305
Dan Gohman71c41442010-08-13 20:11:39 +0000306 // This recurrence is invariant w.r.t. QueryLoop if L contains QueryLoop.
307 if (L->contains(QueryLoop))
308 return true;
309
Dan Gohmane890eea2009-06-26 22:17:21 +0000310 // This recurrence is variant w.r.t. QueryLoop if any of its operands
311 // are variant.
312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
313 if (!getOperand(i)->isLoopInvariant(QueryLoop))
314 return false;
315
316 // Otherwise it's loop-invariant.
317 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000318}
319
Dan Gohman39125d82010-02-13 00:19:39 +0000320bool
321SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
322 return DT->dominates(L->getHeader(), BB) &&
323 SCEVNAryExpr::dominates(BB, DT);
324}
325
326bool
327SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
328 // This uses a "dominates" query instead of "properly dominates" query because
329 // the instruction which produces the addrec's value is a PHI, and a PHI
330 // effectively properly dominates its entire containing block.
331 return DT->dominates(L->getHeader(), BB) &&
332 SCEVNAryExpr::properlyDominates(BB, DT);
333}
334
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000335void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000337 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000339 OS << "}<";
340 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
341 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000342}
Chris Lattner53e677a2004-04-02 20:23:17 +0000343
Dan Gohmanab37f502010-08-02 23:49:30 +0000344void SCEVUnknown::deleted() {
345 // Clear this SCEVUnknown from ValuesAtScopes.
346 SE->ValuesAtScopes.erase(this);
347
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
350
351 // Release the value.
352 setValPtr(0);
353}
354
355void SCEVUnknown::allUsesReplacedWith(Value *New) {
356 // Clear this SCEVUnknown from ValuesAtScopes.
357 SE->ValuesAtScopes.erase(this);
358
359 // Remove this SCEVUnknown from the uniquing map.
360 SE->UniqueSCEVs.RemoveNode(this);
361
362 // Update this SCEVUnknown to point to the new value. This is needed
363 // because there may still be outstanding SCEVs which still point to
364 // this SCEVUnknown.
365 setValPtr(New);
366}
367
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000368bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
369 // All non-instruction values are loop invariant. All instructions are loop
370 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000371 // Instructions are never considered invariant in the function body
372 // (null loop) because they are defined within the "loop".
Dan Gohmanab37f502010-08-02 23:49:30 +0000373 if (Instruction *I = dyn_cast<Instruction>(getValue()))
Dan Gohman92329c72009-12-18 01:24:09 +0000374 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375 return true;
376}
Chris Lattner53e677a2004-04-02 20:23:17 +0000377
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000378bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
379 if (Instruction *I = dyn_cast<Instruction>(getValue()))
380 return DT->dominates(I->getParent(), BB);
381 return true;
382}
383
Dan Gohman6e70e312009-09-27 15:26:03 +0000384bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
385 if (Instruction *I = dyn_cast<Instruction>(getValue()))
386 return DT->properlyDominates(I->getParent(), BB);
387 return true;
388}
389
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000390const Type *SCEVUnknown::getType() const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000391 return getValue()->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000392}
Chris Lattner53e677a2004-04-02 20:23:17 +0000393
Dan Gohman0f5efe52010-01-28 02:15:55 +0000394bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000396 if (VCE->getOpcode() == Instruction::PtrToInt)
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000398 if (CE->getOpcode() == Instruction::GetElementPtr &&
399 CE->getOperand(0)->isNullValue() &&
400 CE->getNumOperands() == 2)
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
402 if (CI->isOne()) {
403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
404 ->getElementType();
405 return true;
406 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000407
408 return false;
409}
410
411bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000413 if (VCE->getOpcode() == Instruction::PtrToInt)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000415 if (CE->getOpcode() == Instruction::GetElementPtr &&
416 CE->getOperand(0)->isNullValue()) {
417 const Type *Ty =
418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
419 if (const StructType *STy = dyn_cast<StructType>(Ty))
420 if (!STy->isPacked() &&
421 CE->getNumOperands() == 3 &&
422 CE->getOperand(1)->isNullValue()) {
423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
424 if (CI->isOne() &&
425 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000426 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000427 AllocTy = STy->getElementType(1);
428 return true;
429 }
430 }
431 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000432
433 return false;
434}
435
Dan Gohman4f8eea82010-02-01 18:27:38 +0000436bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(0)->isNullValue() &&
443 CE->getOperand(1)->isNullValue()) {
444 const Type *Ty =
445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
446 // Ignore vector types here so that ScalarEvolutionExpander doesn't
447 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000448 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000449 CTy = Ty;
450 FieldNo = CE->getOperand(2);
451 return true;
452 }
453 }
454
455 return false;
456}
457
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000458void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000459 const Type *AllocTy;
460 if (isSizeOf(AllocTy)) {
461 OS << "sizeof(" << *AllocTy << ")";
462 return;
463 }
464 if (isAlignOf(AllocTy)) {
465 OS << "alignof(" << *AllocTy << ")";
466 return;
467 }
468
Dan Gohman4f8eea82010-02-01 18:27:38 +0000469 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000470 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000471 if (isOffsetOf(CTy, FieldNo)) {
472 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000473 WriteAsOperand(OS, FieldNo, false);
474 OS << ")";
475 return;
476 }
477
478 // Otherwise just print it normally.
Dan Gohmanab37f502010-08-02 23:49:30 +0000479 WriteAsOperand(OS, getValue(), false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000480}
481
Chris Lattner8d741b82004-06-20 06:23:15 +0000482//===----------------------------------------------------------------------===//
483// SCEV Utilities
484//===----------------------------------------------------------------------===//
485
486namespace {
487 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
488 /// than the complexity of the RHS. This comparator is used to canonicalize
489 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000490 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000491 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000492 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000493 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000494
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000495 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000496 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
497 if (LHS == RHS)
498 return false;
499
Dan Gohman72861302009-05-07 14:39:04 +0000500 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000501 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
502 if (LType != RType)
503 return LType < RType;
Dan Gohman72861302009-05-07 14:39:04 +0000504
Dan Gohman3bf63762010-06-18 19:54:20 +0000505 // Aside from the getSCEVType() ordering, the particular ordering
506 // isn't very important except that it's beneficial to be consistent,
507 // so that (a + b) and (b + a) don't end up as different expressions.
508
509 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
510 // not as complete as it could be.
511 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
512 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000513 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000514
515 // Order pointer values after integer values. This helps SCEVExpander
516 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000517 bool LIsPointer = LV->getType()->isPointerTy(),
518 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000519 if (LIsPointer != RIsPointer)
520 return RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000521
522 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000523 unsigned LID = LV->getValueID(),
524 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000525 if (LID != RID)
526 return LID < RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000527
528 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000529 if (const Argument *LA = dyn_cast<Argument>(LV)) {
530 const Argument *RA = cast<Argument>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000531 return LA->getArgNo() < RA->getArgNo();
532 }
533
534 // For instructions, compare their loop depth, and their opcode.
535 // This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000536 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
537 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000538
539 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000540 const BasicBlock *LParent = LInst->getParent(),
541 *RParent = RInst->getParent();
542 if (LParent != RParent) {
543 unsigned LDepth = LI->getLoopDepth(LParent),
544 RDepth = LI->getLoopDepth(RParent);
545 if (LDepth != RDepth)
546 return LDepth < RDepth;
547 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000548
549 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000550 unsigned LNumOps = LInst->getNumOperands(),
551 RNumOps = RInst->getNumOperands();
Dan Gohman304a7a62010-07-23 21:20:52 +0000552 if (LNumOps != RNumOps)
553 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000554 }
555
556 return false;
557 }
558
559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000562 const ConstantInt *LCC = LC->getValue();
563 const ConstantInt *RCC = RC->getValue();
564 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
565 if (LBitWidth != RBitWidth)
566 return LBitWidth < RBitWidth;
567 return LCC->getValue().ult(RCC->getValue());
Dan Gohman3bf63762010-06-18 19:54:20 +0000568 }
569
570 // Compare addrec loop depths.
571 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
572 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000573 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
574 if (LLoop != RLoop) {
575 unsigned LDepth = LLoop->getLoopDepth(),
576 RDepth = RLoop->getLoopDepth();
577 if (LDepth != RDepth)
578 return LDepth < RDepth;
579 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000580 }
581
582 // Lexicographically compare n-ary expressions.
583 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
584 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000585 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
586 for (unsigned i = 0; i != LNumOps; ++i) {
587 if (i >= RNumOps)
Dan Gohman3bf63762010-06-18 19:54:20 +0000588 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000589 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
590 if (operator()(LOp, ROp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000591 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000592 if (operator()(ROp, LOp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000593 return false;
594 }
Dan Gohman304a7a62010-07-23 21:20:52 +0000595 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000596 }
597
598 // Lexicographically compare udiv expressions.
599 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000601 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
602 *RL = RC->getLHS(), *RR = RC->getRHS();
603 if (operator()(LL, RL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000604 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000605 if (operator()(RL, LL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000606 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000607 if (operator()(LR, RR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000608 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000609 if (operator()(RR, LR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000610 return false;
611 return false;
612 }
613
614 // Compare cast expressions by operand.
615 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
616 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
617 return operator()(LC->getOperand(), RC->getOperand());
618 }
619
620 llvm_unreachable("Unknown SCEV kind!");
621 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000622 }
623 };
624}
625
626/// GroupByComplexity - Given a list of SCEV objects, order them by their
627/// complexity, and group objects of the same complexity together by value.
628/// When this routine is finished, we know that any duplicates in the vector are
629/// consecutive and that complexity is monotonically increasing.
630///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000631/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000632/// results from this routine. In other words, we don't want the results of
633/// this to depend on where the addresses of various SCEV objects happened to
634/// land in memory.
635///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000636static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000637 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000638 if (Ops.size() < 2) return; // Noop
639 if (Ops.size() == 2) {
640 // This is the common case, which also happens to be trivially simple.
641 // Special case it.
Dan Gohman3bf63762010-06-18 19:54:20 +0000642 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000643 std::swap(Ops[0], Ops[1]);
644 return;
645 }
646
Dan Gohman3bf63762010-06-18 19:54:20 +0000647 // Do the rough sort by complexity.
648 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
649
650 // Now that we are sorted by complexity, group elements of the same
651 // complexity. Note that this is, at worst, N^2, but the vector is likely to
652 // be extremely short in practice. Note that we take this approach because we
653 // do not want to depend on the addresses of the objects we are grouping.
654 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
655 const SCEV *S = Ops[i];
656 unsigned Complexity = S->getSCEVType();
657
658 // If there are any objects of the same complexity and same value as this
659 // one, group them.
660 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
661 if (Ops[j] == S) { // Found a duplicate.
662 // Move it to immediately after i'th element.
663 std::swap(Ops[i+1], Ops[j]);
664 ++i; // no need to rescan it.
665 if (i == e-2) return; // Done!
666 }
667 }
668 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000669}
670
Chris Lattner53e677a2004-04-02 20:23:17 +0000671
Chris Lattner53e677a2004-04-02 20:23:17 +0000672
673//===----------------------------------------------------------------------===//
674// Simple SCEV method implementations
675//===----------------------------------------------------------------------===//
676
Eli Friedmanb42a6262008-08-04 23:49:06 +0000677/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000678/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000679static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000680 ScalarEvolution &SE,
681 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000682 // Handle the simplest case efficiently.
683 if (K == 1)
684 return SE.getTruncateOrZeroExtend(It, ResultTy);
685
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000686 // We are using the following formula for BC(It, K):
687 //
688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
689 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000690 // Suppose, W is the bitwidth of the return value. We must be prepared for
691 // overflow. Hence, we must assure that the result of our computation is
692 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
693 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000694 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000695 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000696 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000697 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
698 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000699 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000700 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000701 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000702 // This formula is trivially equivalent to the previous formula. However,
703 // this formula can be implemented much more efficiently. The trick is that
704 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
705 // arithmetic. To do exact division in modular arithmetic, all we have
706 // to do is multiply by the inverse. Therefore, this step can be done at
707 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000708 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000709 // The next issue is how to safely do the division by 2^T. The way this
710 // is done is by doing the multiplication step at a width of at least W + T
711 // bits. This way, the bottom W+T bits of the product are accurate. Then,
712 // when we perform the division by 2^T (which is equivalent to a right shift
713 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
714 // truncated out after the division by 2^T.
715 //
716 // In comparison to just directly using the first formula, this technique
717 // is much more efficient; using the first formula requires W * K bits,
718 // but this formula less than W + K bits. Also, the first formula requires
719 // a division step, whereas this formula only requires multiplies and shifts.
720 //
721 // It doesn't matter whether the subtraction step is done in the calculation
722 // width or the input iteration count's width; if the subtraction overflows,
723 // the result must be zero anyway. We prefer here to do it in the width of
724 // the induction variable because it helps a lot for certain cases; CodeGen
725 // isn't smart enough to ignore the overflow, which leads to much less
726 // efficient code if the width of the subtraction is wider than the native
727 // register width.
728 //
729 // (It's possible to not widen at all by pulling out factors of 2 before
730 // the multiplication; for example, K=2 can be calculated as
731 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
732 // extra arithmetic, so it's not an obvious win, and it gets
733 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000734
Eli Friedmanb42a6262008-08-04 23:49:06 +0000735 // Protection from insane SCEVs; this bound is conservative,
736 // but it probably doesn't matter.
737 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000738 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000739
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000740 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000741
Eli Friedmanb42a6262008-08-04 23:49:06 +0000742 // Calculate K! / 2^T and T; we divide out the factors of two before
743 // multiplying for calculating K! / 2^T to avoid overflow.
744 // Other overflow doesn't matter because we only care about the bottom
745 // W bits of the result.
746 APInt OddFactorial(W, 1);
747 unsigned T = 1;
748 for (unsigned i = 3; i <= K; ++i) {
749 APInt Mult(W, i);
750 unsigned TwoFactors = Mult.countTrailingZeros();
751 T += TwoFactors;
752 Mult = Mult.lshr(TwoFactors);
753 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000754 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000755
Eli Friedmanb42a6262008-08-04 23:49:06 +0000756 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000757 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000758
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000759 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000760 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
761
762 // Calculate the multiplicative inverse of K! / 2^T;
763 // this multiplication factor will perform the exact division by
764 // K! / 2^T.
765 APInt Mod = APInt::getSignedMinValue(W+1);
766 APInt MultiplyFactor = OddFactorial.zext(W+1);
767 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
768 MultiplyFactor = MultiplyFactor.trunc(W);
769
770 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000771 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
772 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000773 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000774 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000775 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000776 Dividend = SE.getMulExpr(Dividend,
777 SE.getTruncateOrZeroExtend(S, CalculationTy));
778 }
779
780 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000781 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000782
783 // Truncate the result, and divide by K! / 2^T.
784
785 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
786 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000787}
788
Chris Lattner53e677a2004-04-02 20:23:17 +0000789/// evaluateAtIteration - Return the value of this chain of recurrences at
790/// the specified iteration number. We can evaluate this recurrence by
791/// multiplying each element in the chain by the binomial coefficient
792/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
793///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000794/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000795///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000796/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000797///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000798const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000799 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000800 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000801 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000802 // The computation is correct in the face of overflow provided that the
803 // multiplication is performed _after_ the evaluation of the binomial
804 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000805 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000806 if (isa<SCEVCouldNotCompute>(Coeff))
807 return Coeff;
808
809 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 }
811 return Result;
812}
813
Chris Lattner53e677a2004-04-02 20:23:17 +0000814//===----------------------------------------------------------------------===//
815// SCEV Expression folder implementations
816//===----------------------------------------------------------------------===//
817
Dan Gohman0bba49c2009-07-07 17:06:11 +0000818const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000819 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000820 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000821 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000822 assert(isSCEVable(Ty) &&
823 "This is not a conversion to a SCEVable type!");
824 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000825
Dan Gohmanc050fd92009-07-13 20:50:19 +0000826 FoldingSetNodeID ID;
827 ID.AddInteger(scTruncate);
828 ID.AddPointer(Op);
829 ID.AddPointer(Ty);
830 void *IP = 0;
831 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
832
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000833 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000834 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000835 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000836 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
837 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000838
Dan Gohman20900ca2009-04-22 16:20:48 +0000839 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000840 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000841 return getTruncateExpr(ST->getOperand(), Ty);
842
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000843 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000844 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000845 return getTruncateOrSignExtend(SS->getOperand(), Ty);
846
847 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000848 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000849 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
850
Dan Gohman6864db62009-06-18 16:24:47 +0000851 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000852 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000853 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000855 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
856 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000857 }
858
Dan Gohmanf53462d2010-07-15 20:02:11 +0000859 // As a special case, fold trunc(undef) to undef. We don't want to
860 // know too much about SCEVUnknowns, but this special case is handy
861 // and harmless.
862 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
863 if (isa<UndefValue>(U->getValue()))
864 return getSCEV(UndefValue::get(Ty));
865
Dan Gohman420ab912010-06-25 18:47:08 +0000866 // The cast wasn't folded; create an explicit cast node. We can reuse
867 // the existing insert position since if we get here, we won't have
868 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000869 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
870 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000871 UniqueSCEVs.InsertNode(S, IP);
872 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000873}
874
Dan Gohman0bba49c2009-07-07 17:06:11 +0000875const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000876 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000877 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000878 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000879 assert(isSCEVable(Ty) &&
880 "This is not a conversion to a SCEVable type!");
881 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000882
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000883 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000884 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
885 return getConstant(
886 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
887 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000888
Dan Gohman20900ca2009-04-22 16:20:48 +0000889 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000890 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000891 return getZeroExtendExpr(SZ->getOperand(), Ty);
892
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000893 // Before doing any expensive analysis, check to see if we've already
894 // computed a SCEV for this Op and Ty.
895 FoldingSetNodeID ID;
896 ID.AddInteger(scZeroExtend);
897 ID.AddPointer(Op);
898 ID.AddPointer(Ty);
899 void *IP = 0;
900 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
901
Dan Gohman01ecca22009-04-27 20:16:15 +0000902 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000903 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000904 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000905 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000906 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000907 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000908 const SCEV *Start = AR->getStart();
909 const SCEV *Step = AR->getStepRecurrence(*this);
910 unsigned BitWidth = getTypeSizeInBits(AR->getType());
911 const Loop *L = AR->getLoop();
912
Dan Gohmaneb490a72009-07-25 01:22:26 +0000913 // If we have special knowledge that this addrec won't overflow,
914 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000915 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000916 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
917 getZeroExtendExpr(Step, Ty),
918 L);
919
Dan Gohman01ecca22009-04-27 20:16:15 +0000920 // Check whether the backedge-taken count is SCEVCouldNotCompute.
921 // Note that this serves two purposes: It filters out loops that are
922 // simply not analyzable, and it covers the case where this code is
923 // being called from within backedge-taken count analysis, such that
924 // attempting to ask for the backedge-taken count would likely result
925 // in infinite recursion. In the later case, the analysis code will
926 // cope with a conservative value, and it will take care to purge
927 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000928 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000929 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000930 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000931 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000932
933 // Check whether the backedge-taken count can be losslessly casted to
934 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000935 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000936 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000937 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000938 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
939 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000940 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000941 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000942 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000943 const SCEV *Add = getAddExpr(Start, ZMul);
944 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000945 getAddExpr(getZeroExtendExpr(Start, WideTy),
946 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
947 getZeroExtendExpr(Step, WideTy)));
948 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000949 // Return the expression with the addrec on the outside.
950 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
951 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000952 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000953
954 // Similar to above, only this time treat the step value as signed.
955 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000956 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000957 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000958 OperandExtendedAdd =
959 getAddExpr(getZeroExtendExpr(Start, WideTy),
960 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
961 getSignExtendExpr(Step, WideTy)));
962 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000963 // Return the expression with the addrec on the outside.
964 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
965 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000966 L);
967 }
968
969 // If the backedge is guarded by a comparison with the pre-inc value
970 // the addrec is safe. Also, if the entry is guarded by a comparison
971 // with the start value and the backedge is guarded by a comparison
972 // with the post-inc value, the addrec is safe.
973 if (isKnownPositive(Step)) {
974 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
975 getUnsignedRange(Step).getUnsignedMax());
976 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000977 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000978 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
979 AR->getPostIncExpr(*this), N)))
980 // Return the expression with the addrec on the outside.
981 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
982 getZeroExtendExpr(Step, Ty),
983 L);
984 } else if (isKnownNegative(Step)) {
985 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
986 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000987 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
988 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000989 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
990 AR->getPostIncExpr(*this), N)))
991 // Return the expression with the addrec on the outside.
992 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
993 getSignExtendExpr(Step, Ty),
994 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000995 }
996 }
997 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000998
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000999 // The cast wasn't folded; create an explicit cast node.
1000 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001001 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001002 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1003 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001004 UniqueSCEVs.InsertNode(S, IP);
1005 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001006}
1007
Dan Gohman0bba49c2009-07-07 17:06:11 +00001008const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001009 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001010 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001011 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001012 assert(isSCEVable(Ty) &&
1013 "This is not a conversion to a SCEVable type!");
1014 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001015
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001016 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001017 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1018 return getConstant(
1019 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1020 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001021
Dan Gohman20900ca2009-04-22 16:20:48 +00001022 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001023 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001024 return getSignExtendExpr(SS->getOperand(), Ty);
1025
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001026 // Before doing any expensive analysis, check to see if we've already
1027 // computed a SCEV for this Op and Ty.
1028 FoldingSetNodeID ID;
1029 ID.AddInteger(scSignExtend);
1030 ID.AddPointer(Op);
1031 ID.AddPointer(Ty);
1032 void *IP = 0;
1033 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1034
Dan Gohman01ecca22009-04-27 20:16:15 +00001035 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001036 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001037 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001038 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001039 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001040 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001041 const SCEV *Start = AR->getStart();
1042 const SCEV *Step = AR->getStepRecurrence(*this);
1043 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1044 const Loop *L = AR->getLoop();
1045
Dan Gohmaneb490a72009-07-25 01:22:26 +00001046 // If we have special knowledge that this addrec won't overflow,
1047 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001048 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001049 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1050 getSignExtendExpr(Step, Ty),
1051 L);
1052
Dan Gohman01ecca22009-04-27 20:16:15 +00001053 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1054 // Note that this serves two purposes: It filters out loops that are
1055 // simply not analyzable, and it covers the case where this code is
1056 // being called from within backedge-taken count analysis, such that
1057 // attempting to ask for the backedge-taken count would likely result
1058 // in infinite recursion. In the later case, the analysis code will
1059 // cope with a conservative value, and it will take care to purge
1060 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001061 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001062 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001063 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001064 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001065
1066 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001067 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001068 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001069 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001070 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001071 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1072 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001073 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001074 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001075 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001076 const SCEV *Add = getAddExpr(Start, SMul);
1077 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001078 getAddExpr(getSignExtendExpr(Start, WideTy),
1079 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1080 getSignExtendExpr(Step, WideTy)));
1081 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001082 // Return the expression with the addrec on the outside.
1083 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1084 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001085 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001086
1087 // Similar to above, only this time treat the step value as unsigned.
1088 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001089 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001090 Add = getAddExpr(Start, UMul);
1091 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001092 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001093 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1094 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001095 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001096 // Return the expression with the addrec on the outside.
1097 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1098 getZeroExtendExpr(Step, Ty),
1099 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001100 }
1101
1102 // If the backedge is guarded by a comparison with the pre-inc value
1103 // the addrec is safe. Also, if the entry is guarded by a comparison
1104 // with the start value and the backedge is guarded by a comparison
1105 // with the post-inc value, the addrec is safe.
1106 if (isKnownPositive(Step)) {
1107 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1108 getSignedRange(Step).getSignedMax());
1109 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001110 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001111 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1112 AR->getPostIncExpr(*this), N)))
1113 // Return the expression with the addrec on the outside.
1114 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1115 getSignExtendExpr(Step, Ty),
1116 L);
1117 } else if (isKnownNegative(Step)) {
1118 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1119 getSignedRange(Step).getSignedMin());
1120 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001121 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001122 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1123 AR->getPostIncExpr(*this), N)))
1124 // Return the expression with the addrec on the outside.
1125 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1126 getSignExtendExpr(Step, Ty),
1127 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001128 }
1129 }
1130 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001131
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001132 // The cast wasn't folded; create an explicit cast node.
1133 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001134 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001135 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1136 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001137 UniqueSCEVs.InsertNode(S, IP);
1138 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001139}
1140
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001141/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1142/// unspecified bits out to the given type.
1143///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001144const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001145 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001146 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1147 "This is not an extending conversion!");
1148 assert(isSCEVable(Ty) &&
1149 "This is not a conversion to a SCEVable type!");
1150 Ty = getEffectiveSCEVType(Ty);
1151
1152 // Sign-extend negative constants.
1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1154 if (SC->getValue()->getValue().isNegative())
1155 return getSignExtendExpr(Op, Ty);
1156
1157 // Peel off a truncate cast.
1158 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001159 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001160 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1161 return getAnyExtendExpr(NewOp, Ty);
1162 return getTruncateOrNoop(NewOp, Ty);
1163 }
1164
1165 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001166 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001167 if (!isa<SCEVZeroExtendExpr>(ZExt))
1168 return ZExt;
1169
1170 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001171 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001172 if (!isa<SCEVSignExtendExpr>(SExt))
1173 return SExt;
1174
Dan Gohmana10756e2010-01-21 02:09:26 +00001175 // Force the cast to be folded into the operands of an addrec.
1176 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1177 SmallVector<const SCEV *, 4> Ops;
1178 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1179 I != E; ++I)
1180 Ops.push_back(getAnyExtendExpr(*I, Ty));
1181 return getAddRecExpr(Ops, AR->getLoop());
1182 }
1183
Dan Gohmanf53462d2010-07-15 20:02:11 +00001184 // As a special case, fold anyext(undef) to undef. We don't want to
1185 // know too much about SCEVUnknowns, but this special case is handy
1186 // and harmless.
1187 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1188 if (isa<UndefValue>(U->getValue()))
1189 return getSCEV(UndefValue::get(Ty));
1190
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001191 // If the expression is obviously signed, use the sext cast value.
1192 if (isa<SCEVSMaxExpr>(Op))
1193 return SExt;
1194
1195 // Absent any other information, use the zext cast value.
1196 return ZExt;
1197}
1198
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001199/// CollectAddOperandsWithScales - Process the given Ops list, which is
1200/// a list of operands to be added under the given scale, update the given
1201/// map. This is a helper function for getAddRecExpr. As an example of
1202/// what it does, given a sequence of operands that would form an add
1203/// expression like this:
1204///
1205/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1206///
1207/// where A and B are constants, update the map with these values:
1208///
1209/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1210///
1211/// and add 13 + A*B*29 to AccumulatedConstant.
1212/// This will allow getAddRecExpr to produce this:
1213///
1214/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1215///
1216/// This form often exposes folding opportunities that are hidden in
1217/// the original operand list.
1218///
1219/// Return true iff it appears that any interesting folding opportunities
1220/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1221/// the common case where no interesting opportunities are present, and
1222/// is also used as a check to avoid infinite recursion.
1223///
1224static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001225CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1226 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001227 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001228 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001229 const APInt &Scale,
1230 ScalarEvolution &SE) {
1231 bool Interesting = false;
1232
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001233 // Iterate over the add operands. They are sorted, with constants first.
1234 unsigned i = 0;
1235 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1236 ++i;
1237 // Pull a buried constant out to the outside.
1238 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1239 Interesting = true;
1240 AccumulatedConstant += Scale * C->getValue()->getValue();
1241 }
1242
1243 // Next comes everything else. We're especially interested in multiplies
1244 // here, but they're in the middle, so just visit the rest with one loop.
1245 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001246 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1247 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1248 APInt NewScale =
1249 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1250 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1251 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001252 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001253 Interesting |=
1254 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001255 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001256 NewScale, SE);
1257 } else {
1258 // A multiplication of a constant with some other value. Update
1259 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001260 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1261 const SCEV *Key = SE.getMulExpr(MulOps);
1262 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001263 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001264 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001265 NewOps.push_back(Pair.first->first);
1266 } else {
1267 Pair.first->second += NewScale;
1268 // The map already had an entry for this value, which may indicate
1269 // a folding opportunity.
1270 Interesting = true;
1271 }
1272 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001273 } else {
1274 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001275 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001276 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001277 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001278 NewOps.push_back(Pair.first->first);
1279 } else {
1280 Pair.first->second += Scale;
1281 // The map already had an entry for this value, which may indicate
1282 // a folding opportunity.
1283 Interesting = true;
1284 }
1285 }
1286 }
1287
1288 return Interesting;
1289}
1290
1291namespace {
1292 struct APIntCompare {
1293 bool operator()(const APInt &LHS, const APInt &RHS) const {
1294 return LHS.ult(RHS);
1295 }
1296 };
1297}
1298
Dan Gohman6c0866c2009-05-24 23:45:28 +00001299/// getAddExpr - Get a canonical add expression, or something simpler if
1300/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001301const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1302 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001304 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001305#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001306 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001307 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001309 "SCEVAddExpr operand types don't match!");
1310#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001311
Dan Gohmana10756e2010-01-21 02:09:26 +00001312 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1313 if (!HasNUW && HasNSW) {
1314 bool All = true;
1315 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1316 if (!isKnownNonNegative(Ops[i])) {
1317 All = false;
1318 break;
1319 }
1320 if (All) HasNUW = true;
1321 }
1322
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001324 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001325
1326 // If there are any constants, fold them together.
1327 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001328 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001330 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001331 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001332 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001333 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1334 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001335 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001336 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001337 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 }
1339
1340 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001341 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001342 Ops.erase(Ops.begin());
1343 --Idx;
1344 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001345
Dan Gohmanbca091d2010-04-12 23:08:18 +00001346 if (Ops.size() == 1) return Ops[0];
1347 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001348
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 // Okay, check to see if the same value occurs in the operand list twice. If
1350 // so, merge them together into an multiply expression. Since we sorted the
1351 // list, these values are required to be adjacent.
1352 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001353 bool FoundMatch = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001354 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1355 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1356 // Found a match, merge the two values into a multiply, and add any
1357 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001358 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman58a85b92010-08-13 20:17:14 +00001359 const SCEV *Mul = getMulExpr(Two, Ops[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 if (Ops.size() == 2)
1361 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001362 Ops[i] = Mul;
1363 Ops.erase(Ops.begin()+i+1);
1364 --i; --e;
1365 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001366 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001367 if (FoundMatch)
1368 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001369
Dan Gohman728c7f32009-05-08 21:03:19 +00001370 // Check for truncates. If all the operands are truncated from the same
1371 // type, see if factoring out the truncate would permit the result to be
1372 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1373 // if the contents of the resulting outer trunc fold to something simple.
1374 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1375 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1376 const Type *DstType = Trunc->getType();
1377 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001378 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001379 bool Ok = true;
1380 // Check all the operands to see if they can be represented in the
1381 // source type of the truncate.
1382 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1383 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1384 if (T->getOperand()->getType() != SrcType) {
1385 Ok = false;
1386 break;
1387 }
1388 LargeOps.push_back(T->getOperand());
1389 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001390 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001391 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001392 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001393 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1394 if (const SCEVTruncateExpr *T =
1395 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1396 if (T->getOperand()->getType() != SrcType) {
1397 Ok = false;
1398 break;
1399 }
1400 LargeMulOps.push_back(T->getOperand());
1401 } else if (const SCEVConstant *C =
1402 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001403 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001404 } else {
1405 Ok = false;
1406 break;
1407 }
1408 }
1409 if (Ok)
1410 LargeOps.push_back(getMulExpr(LargeMulOps));
1411 } else {
1412 Ok = false;
1413 break;
1414 }
1415 }
1416 if (Ok) {
1417 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001418 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001419 // If it folds to something simple, use it. Otherwise, don't.
1420 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1421 return getTruncateExpr(Fold, DstType);
1422 }
1423 }
1424
1425 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001426 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1427 ++Idx;
1428
1429 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 if (Idx < Ops.size()) {
1431 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001432 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001433 // If we have an add, expand the add operands onto the end of the operands
1434 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001435 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001436 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 DeletedAdd = true;
1438 }
1439
1440 // If we deleted at least one add, we added operands to the end of the list,
1441 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001442 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001443 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001444 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001445 }
1446
1447 // Skip over the add expression until we get to a multiply.
1448 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1449 ++Idx;
1450
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001451 // Check to see if there are any folding opportunities present with
1452 // operands multiplied by constant values.
1453 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1454 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001455 DenseMap<const SCEV *, APInt> M;
1456 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001457 APInt AccumulatedConstant(BitWidth, 0);
1458 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001459 Ops.data(), Ops.size(),
1460 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001461 // Some interesting folding opportunity is present, so its worthwhile to
1462 // re-generate the operands list. Group the operands by constant scale,
1463 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001464 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1465 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001466 E = NewOps.end(); I != E; ++I)
1467 MulOpLists[M.find(*I)->second].push_back(*I);
1468 // Re-generate the operands list.
1469 Ops.clear();
1470 if (AccumulatedConstant != 0)
1471 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001472 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1473 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001474 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001475 Ops.push_back(getMulExpr(getConstant(I->first),
1476 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001477 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001478 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001479 if (Ops.size() == 1)
1480 return Ops[0];
1481 return getAddExpr(Ops);
1482 }
1483 }
1484
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 // If we are adding something to a multiply expression, make sure the
1486 // something is not already an operand of the multiply. If so, merge it into
1487 // the multiply.
1488 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001489 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001490 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001491 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001492 if (isa<SCEVConstant>(MulOpSCEV))
1493 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001495 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001497 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001498 if (Mul->getNumOperands() != 2) {
1499 // If the multiply has more than two operands, we must get the
1500 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001501 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001502 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001503 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001505 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001506 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001507 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 if (Ops.size() == 2) return OuterMul;
1509 if (AddOp < Idx) {
1510 Ops.erase(Ops.begin()+AddOp);
1511 Ops.erase(Ops.begin()+Idx-1);
1512 } else {
1513 Ops.erase(Ops.begin()+Idx);
1514 Ops.erase(Ops.begin()+AddOp-1);
1515 }
1516 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001517 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001519
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 // Check this multiply against other multiplies being added together.
Dan Gohman727356f2010-08-12 15:00:23 +00001521 bool AnyFold = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001522 for (unsigned OtherMulIdx = Idx+1;
1523 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1524 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001525 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 // If MulOp occurs in OtherMul, we can fold the two multiplies
1527 // together.
1528 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1529 OMulOp != e; ++OMulOp)
1530 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1531 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001532 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001534 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1535 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001537 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001539 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001541 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1542 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001544 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001545 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001546 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1547 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 if (Ops.size() == 2) return OuterMul;
Dan Gohman727356f2010-08-12 15:00:23 +00001549 Ops[Idx] = OuterMul;
1550 Ops.erase(Ops.begin()+OtherMulIdx);
1551 OtherMulIdx = Idx;
1552 AnyFold = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001553 }
1554 }
Dan Gohman727356f2010-08-12 15:00:23 +00001555 if (AnyFold)
1556 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 }
1558 }
1559
1560 // If there are any add recurrences in the operands list, see if any other
1561 // added values are loop invariant. If so, we can fold them into the
1562 // recurrence.
1563 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1564 ++Idx;
1565
1566 // Scan over all recurrences, trying to fold loop invariants into them.
1567 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1568 // Scan all of the other operands to this add and add them to the vector if
1569 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001570 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001571 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001572 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001573 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001574 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 LIOps.push_back(Ops[i]);
1576 Ops.erase(Ops.begin()+i);
1577 --i; --e;
1578 }
1579
1580 // If we found some loop invariants, fold them into the recurrence.
1581 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001582 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001583 LIOps.push_back(AddRec->getStart());
1584
Dan Gohman0bba49c2009-07-07 17:06:11 +00001585 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001586 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001587 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001588
Dan Gohmanb9f96512010-06-30 07:16:37 +00001589 // Build the new addrec. Propagate the NUW and NSW flags if both the
1590 // outer add and the inner addrec are guaranteed to have no overflow.
1591 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1592 HasNUW && AddRec->hasNoUnsignedWrap(),
1593 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001594
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 // If all of the other operands were loop invariant, we are done.
1596 if (Ops.size() == 1) return NewRec;
1597
1598 // Otherwise, add the folded AddRec by the non-liv parts.
1599 for (unsigned i = 0;; ++i)
1600 if (Ops[i] == AddRec) {
1601 Ops[i] = NewRec;
1602 break;
1603 }
Dan Gohman246b2562007-10-22 18:31:58 +00001604 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 }
1606
1607 // Okay, if there weren't any loop invariants to be folded, check to see if
1608 // there are multiple AddRec's with the same loop induction variable being
1609 // added together. If so, we can fold them.
1610 for (unsigned OtherIdx = Idx+1;
1611 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1612 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001613 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001614 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001616 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1617 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001618 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1619 if (i >= NewOps.size()) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001620 NewOps.append(OtherAddRec->op_begin()+i,
Chris Lattner53e677a2004-04-02 20:23:17 +00001621 OtherAddRec->op_end());
1622 break;
1623 }
Dan Gohman246b2562007-10-22 18:31:58 +00001624 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001625 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001626 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001627
1628 if (Ops.size() == 2) return NewAddRec;
1629
1630 Ops.erase(Ops.begin()+Idx);
1631 Ops.erase(Ops.begin()+OtherIdx-1);
1632 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001633 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001634 }
1635 }
1636
1637 // Otherwise couldn't fold anything into this recurrence. Move onto the
1638 // next one.
1639 }
1640
1641 // Okay, it looks like we really DO need an add expr. Check to see if we
1642 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001643 FoldingSetNodeID ID;
1644 ID.AddInteger(scAddExpr);
1645 ID.AddInteger(Ops.size());
1646 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1647 ID.AddPointer(Ops[i]);
1648 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001649 SCEVAddExpr *S =
1650 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1651 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001652 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1653 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001654 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1655 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001656 UniqueSCEVs.InsertNode(S, IP);
1657 }
Dan Gohman3645b012009-10-09 00:10:36 +00001658 if (HasNUW) S->setHasNoUnsignedWrap(true);
1659 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001660 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001661}
1662
Dan Gohman6c0866c2009-05-24 23:45:28 +00001663/// getMulExpr - Get a canonical multiply expression, or something simpler if
1664/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001665const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1666 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001667 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001668 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001669#ifndef NDEBUG
1670 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1671 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1672 getEffectiveSCEVType(Ops[0]->getType()) &&
1673 "SCEVMulExpr operand types don't match!");
1674#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001675
Dan Gohmana10756e2010-01-21 02:09:26 +00001676 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1677 if (!HasNUW && HasNSW) {
1678 bool All = true;
1679 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1680 if (!isKnownNonNegative(Ops[i])) {
1681 All = false;
1682 break;
1683 }
1684 if (All) HasNUW = true;
1685 }
1686
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001688 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001689
1690 // If there are any constants, fold them together.
1691 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001692 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001693
1694 // C1*(C2+V) -> C1*C2 + C1*V
1695 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001696 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001697 if (Add->getNumOperands() == 2 &&
1698 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001699 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1700 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001701
Chris Lattner53e677a2004-04-02 20:23:17 +00001702 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001703 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001704 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001705 ConstantInt *Fold = ConstantInt::get(getContext(),
1706 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001707 RHSC->getValue()->getValue());
1708 Ops[0] = getConstant(Fold);
1709 Ops.erase(Ops.begin()+1); // Erase the folded element
1710 if (Ops.size() == 1) return Ops[0];
1711 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001712 }
1713
1714 // If we are left with a constant one being multiplied, strip it off.
1715 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1716 Ops.erase(Ops.begin());
1717 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001718 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001719 // If we have a multiply of zero, it will always be zero.
1720 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001721 } else if (Ops[0]->isAllOnesValue()) {
1722 // If we have a mul by -1 of an add, try distributing the -1 among the
1723 // add operands.
1724 if (Ops.size() == 2)
1725 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1726 SmallVector<const SCEV *, 4> NewOps;
1727 bool AnyFolded = false;
1728 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1729 I != E; ++I) {
1730 const SCEV *Mul = getMulExpr(Ops[0], *I);
1731 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1732 NewOps.push_back(Mul);
1733 }
1734 if (AnyFolded)
1735 return getAddExpr(NewOps);
1736 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001738
1739 if (Ops.size() == 1)
1740 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001741 }
1742
1743 // Skip over the add expression until we get to a multiply.
1744 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1745 ++Idx;
1746
Chris Lattner53e677a2004-04-02 20:23:17 +00001747 // If there are mul operands inline them all into this expression.
1748 if (Idx < Ops.size()) {
1749 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001750 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 // If we have an mul, expand the mul operands onto the end of the operands
1752 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001753 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001754 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001755 DeletedMul = true;
1756 }
1757
1758 // If we deleted at least one mul, we added operands to the end of the list,
1759 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001760 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001761 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001762 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001763 }
1764
1765 // If there are any add recurrences in the operands list, see if any other
1766 // added values are loop invariant. If so, we can fold them into the
1767 // recurrence.
1768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1769 ++Idx;
1770
1771 // Scan over all recurrences, trying to fold loop invariants into them.
1772 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1773 // Scan all of the other operands to this mul and add them to the vector if
1774 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001775 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001776 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1778 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1779 LIOps.push_back(Ops[i]);
1780 Ops.erase(Ops.begin()+i);
1781 --i; --e;
1782 }
1783
1784 // If we found some loop invariants, fold them into the recurrence.
1785 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001786 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001787 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001788 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001789 const SCEV *Scale = getMulExpr(LIOps);
1790 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1791 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001792
Dan Gohmanb9f96512010-06-30 07:16:37 +00001793 // Build the new addrec. Propagate the NUW and NSW flags if both the
1794 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00001795 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1796 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001797 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001798
1799 // If all of the other operands were loop invariant, we are done.
1800 if (Ops.size() == 1) return NewRec;
1801
1802 // Otherwise, multiply the folded AddRec by the non-liv parts.
1803 for (unsigned i = 0;; ++i)
1804 if (Ops[i] == AddRec) {
1805 Ops[i] = NewRec;
1806 break;
1807 }
Dan Gohman246b2562007-10-22 18:31:58 +00001808 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001809 }
1810
1811 // Okay, if there weren't any loop invariants to be folded, check to see if
1812 // there are multiple AddRec's with the same loop induction variable being
1813 // multiplied together. If so, we can fold them.
1814 for (unsigned OtherIdx = Idx+1;
1815 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1816 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001817 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001818 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1819 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001820 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001821 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001822 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001823 const SCEV *B = F->getStepRecurrence(*this);
1824 const SCEV *D = G->getStepRecurrence(*this);
1825 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001826 getMulExpr(G, B),
1827 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001828 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001829 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001830 if (Ops.size() == 2) return NewAddRec;
1831
1832 Ops.erase(Ops.begin()+Idx);
1833 Ops.erase(Ops.begin()+OtherIdx-1);
1834 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001835 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001836 }
1837 }
1838
1839 // Otherwise couldn't fold anything into this recurrence. Move onto the
1840 // next one.
1841 }
1842
1843 // Okay, it looks like we really DO need an mul expr. Check to see if we
1844 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001845 FoldingSetNodeID ID;
1846 ID.AddInteger(scMulExpr);
1847 ID.AddInteger(Ops.size());
1848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1849 ID.AddPointer(Ops[i]);
1850 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001851 SCEVMulExpr *S =
1852 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1853 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001854 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1855 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001856 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1857 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001858 UniqueSCEVs.InsertNode(S, IP);
1859 }
Dan Gohman3645b012009-10-09 00:10:36 +00001860 if (HasNUW) S->setHasNoUnsignedWrap(true);
1861 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001862 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001863}
1864
Andreas Bolka8a11c982009-08-07 22:55:26 +00001865/// getUDivExpr - Get a canonical unsigned division expression, or something
1866/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001867const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1868 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001869 assert(getEffectiveSCEVType(LHS->getType()) ==
1870 getEffectiveSCEVType(RHS->getType()) &&
1871 "SCEVUDivExpr operand types don't match!");
1872
Dan Gohman622ed672009-05-04 22:02:23 +00001873 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001874 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001875 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001876 // If the denominator is zero, the result of the udiv is undefined. Don't
1877 // try to analyze it, because the resolution chosen here may differ from
1878 // the resolution chosen in other parts of the compiler.
1879 if (!RHSC->getValue()->isZero()) {
1880 // Determine if the division can be folded into the operands of
1881 // its operands.
1882 // TODO: Generalize this to non-constants by using known-bits information.
1883 const Type *Ty = LHS->getType();
1884 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001885 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001886 // For non-power-of-two values, effectively round the value up to the
1887 // nearest power of two.
1888 if (!RHSC->getValue()->getValue().isPowerOf2())
1889 ++MaxShiftAmt;
1890 const IntegerType *ExtTy =
1891 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1892 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1893 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1894 if (const SCEVConstant *Step =
1895 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1896 if (!Step->getValue()->getValue()
1897 .urem(RHSC->getValue()->getValue()) &&
1898 getZeroExtendExpr(AR, ExtTy) ==
1899 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1900 getZeroExtendExpr(Step, ExtTy),
1901 AR->getLoop())) {
1902 SmallVector<const SCEV *, 4> Operands;
1903 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1904 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1905 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001906 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001907 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1908 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1909 SmallVector<const SCEV *, 4> Operands;
1910 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1911 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1912 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1913 // Find an operand that's safely divisible.
1914 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1915 const SCEV *Op = M->getOperand(i);
1916 const SCEV *Div = getUDivExpr(Op, RHSC);
1917 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1918 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1919 M->op_end());
1920 Operands[i] = Div;
1921 return getMulExpr(Operands);
1922 }
1923 }
Dan Gohman185cf032009-05-08 20:18:49 +00001924 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001925 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1926 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1927 SmallVector<const SCEV *, 4> Operands;
1928 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1929 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1930 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1931 Operands.clear();
1932 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1933 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1934 if (isa<SCEVUDivExpr>(Op) ||
1935 getMulExpr(Op, RHS) != A->getOperand(i))
1936 break;
1937 Operands.push_back(Op);
1938 }
1939 if (Operands.size() == A->getNumOperands())
1940 return getAddExpr(Operands);
1941 }
1942 }
Dan Gohman185cf032009-05-08 20:18:49 +00001943
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001944 // Fold if both operands are constant.
1945 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1946 Constant *LHSCV = LHSC->getValue();
1947 Constant *RHSCV = RHSC->getValue();
1948 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1949 RHSCV)));
1950 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001951 }
1952 }
1953
Dan Gohman1c343752009-06-27 21:21:31 +00001954 FoldingSetNodeID ID;
1955 ID.AddInteger(scUDivExpr);
1956 ID.AddPointer(LHS);
1957 ID.AddPointer(RHS);
1958 void *IP = 0;
1959 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001960 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1961 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001962 UniqueSCEVs.InsertNode(S, IP);
1963 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001964}
1965
1966
Dan Gohman6c0866c2009-05-24 23:45:28 +00001967/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1968/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001969const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001970 const SCEV *Step, const Loop *L,
1971 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001972 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001973 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001974 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001975 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001976 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001977 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001978 }
1979
1980 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001981 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001982}
1983
Dan Gohman6c0866c2009-05-24 23:45:28 +00001984/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1985/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001986const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001987ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001988 const Loop *L,
1989 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001990 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001991#ifndef NDEBUG
1992 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1993 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1994 getEffectiveSCEVType(Operands[0]->getType()) &&
1995 "SCEVAddRecExpr operand types don't match!");
1996#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001997
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001998 if (Operands.back()->isZero()) {
1999 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00002000 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002001 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002002
Dan Gohmanbc028532010-02-19 18:49:22 +00002003 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2004 // use that information to infer NUW and NSW flags. However, computing a
2005 // BE count requires calling getAddRecExpr, so we may not yet have a
2006 // meaningful BE count at this point (and if we don't, we'd be stuck
2007 // with a SCEVCouldNotCompute as the cached BE count).
2008
Dan Gohmana10756e2010-01-21 02:09:26 +00002009 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2010 if (!HasNUW && HasNSW) {
2011 bool All = true;
2012 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2013 if (!isKnownNonNegative(Operands[i])) {
2014 All = false;
2015 break;
2016 }
2017 if (All) HasNUW = true;
2018 }
2019
Dan Gohmand9cc7492008-08-08 18:33:12 +00002020 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002021 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002022 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002023 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002024 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002025 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002026 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002027 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002028 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002029 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002030 // AddRecs require their operands be loop-invariant with respect to their
2031 // loops. Don't perform this transformation if it would break this
2032 // requirement.
2033 bool AllInvariant = true;
2034 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2035 if (!Operands[i]->isLoopInvariant(L)) {
2036 AllInvariant = false;
2037 break;
2038 }
2039 if (AllInvariant) {
2040 NestedOperands[0] = getAddRecExpr(Operands, L);
2041 AllInvariant = true;
2042 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2043 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2044 AllInvariant = false;
2045 break;
2046 }
2047 if (AllInvariant)
2048 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002049 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002050 }
2051 // Reset Operands to its original state.
2052 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002053 }
2054 }
2055
Dan Gohman67847532010-01-19 22:27:22 +00002056 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2057 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002058 FoldingSetNodeID ID;
2059 ID.AddInteger(scAddRecExpr);
2060 ID.AddInteger(Operands.size());
2061 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2062 ID.AddPointer(Operands[i]);
2063 ID.AddPointer(L);
2064 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002065 SCEVAddRecExpr *S =
2066 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2067 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002068 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2069 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002070 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2071 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002072 UniqueSCEVs.InsertNode(S, IP);
2073 }
Dan Gohman3645b012009-10-09 00:10:36 +00002074 if (HasNUW) S->setHasNoUnsignedWrap(true);
2075 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002076 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002077}
2078
Dan Gohman9311ef62009-06-24 14:49:00 +00002079const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2080 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002081 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002082 Ops.push_back(LHS);
2083 Ops.push_back(RHS);
2084 return getSMaxExpr(Ops);
2085}
2086
Dan Gohman0bba49c2009-07-07 17:06:11 +00002087const SCEV *
2088ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002089 assert(!Ops.empty() && "Cannot get empty smax!");
2090 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002091#ifndef NDEBUG
2092 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2093 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2094 getEffectiveSCEVType(Ops[0]->getType()) &&
2095 "SCEVSMaxExpr operand types don't match!");
2096#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002097
2098 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002099 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002100
2101 // If there are any constants, fold them together.
2102 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002103 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002104 ++Idx;
2105 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002106 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002107 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002108 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002109 APIntOps::smax(LHSC->getValue()->getValue(),
2110 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002111 Ops[0] = getConstant(Fold);
2112 Ops.erase(Ops.begin()+1); // Erase the folded element
2113 if (Ops.size() == 1) return Ops[0];
2114 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002115 }
2116
Dan Gohmane5aceed2009-06-24 14:46:22 +00002117 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002118 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2119 Ops.erase(Ops.begin());
2120 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002121 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2122 // If we have an smax with a constant maximum-int, it will always be
2123 // maximum-int.
2124 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002125 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002126
Dan Gohman3ab13122010-04-13 16:49:23 +00002127 if (Ops.size() == 1) return Ops[0];
2128 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002129
2130 // Find the first SMax
2131 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2132 ++Idx;
2133
2134 // Check to see if one of the operands is an SMax. If so, expand its operands
2135 // onto our operand list, and recurse to simplify.
2136 if (Idx < Ops.size()) {
2137 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002138 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002139 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002140 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002141 DeletedSMax = true;
2142 }
2143
2144 if (DeletedSMax)
2145 return getSMaxExpr(Ops);
2146 }
2147
2148 // Okay, check to see if the same value occurs in the operand list twice. If
2149 // so, delete one. Since we sorted the list, these values are required to
2150 // be adjacent.
2151 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002152 // X smax Y smax Y --> X smax Y
2153 // X smax Y --> X, if X is always greater than Y
2154 if (Ops[i] == Ops[i+1] ||
2155 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2156 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2157 --i; --e;
2158 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002159 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2160 --i; --e;
2161 }
2162
2163 if (Ops.size() == 1) return Ops[0];
2164
2165 assert(!Ops.empty() && "Reduced smax down to nothing!");
2166
Nick Lewycky3e630762008-02-20 06:48:22 +00002167 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002168 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002169 FoldingSetNodeID ID;
2170 ID.AddInteger(scSMaxExpr);
2171 ID.AddInteger(Ops.size());
2172 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2173 ID.AddPointer(Ops[i]);
2174 void *IP = 0;
2175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002176 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2177 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002178 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2179 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002180 UniqueSCEVs.InsertNode(S, IP);
2181 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002182}
2183
Dan Gohman9311ef62009-06-24 14:49:00 +00002184const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2185 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002186 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002187 Ops.push_back(LHS);
2188 Ops.push_back(RHS);
2189 return getUMaxExpr(Ops);
2190}
2191
Dan Gohman0bba49c2009-07-07 17:06:11 +00002192const SCEV *
2193ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002194 assert(!Ops.empty() && "Cannot get empty umax!");
2195 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002196#ifndef NDEBUG
2197 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2198 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2199 getEffectiveSCEVType(Ops[0]->getType()) &&
2200 "SCEVUMaxExpr operand types don't match!");
2201#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002202
2203 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002204 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002205
2206 // If there are any constants, fold them together.
2207 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002208 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002209 ++Idx;
2210 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002211 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002212 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002213 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002214 APIntOps::umax(LHSC->getValue()->getValue(),
2215 RHSC->getValue()->getValue()));
2216 Ops[0] = getConstant(Fold);
2217 Ops.erase(Ops.begin()+1); // Erase the folded element
2218 if (Ops.size() == 1) return Ops[0];
2219 LHSC = cast<SCEVConstant>(Ops[0]);
2220 }
2221
Dan Gohmane5aceed2009-06-24 14:46:22 +00002222 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002223 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2224 Ops.erase(Ops.begin());
2225 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002226 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2227 // If we have an umax with a constant maximum-int, it will always be
2228 // maximum-int.
2229 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002230 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002231
Dan Gohman3ab13122010-04-13 16:49:23 +00002232 if (Ops.size() == 1) return Ops[0];
2233 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002234
2235 // Find the first UMax
2236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2237 ++Idx;
2238
2239 // Check to see if one of the operands is a UMax. If so, expand its operands
2240 // onto our operand list, and recurse to simplify.
2241 if (Idx < Ops.size()) {
2242 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002243 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002244 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002245 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002246 DeletedUMax = true;
2247 }
2248
2249 if (DeletedUMax)
2250 return getUMaxExpr(Ops);
2251 }
2252
2253 // Okay, check to see if the same value occurs in the operand list twice. If
2254 // so, delete one. Since we sorted the list, these values are required to
2255 // be adjacent.
2256 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002257 // X umax Y umax Y --> X umax Y
2258 // X umax Y --> X, if X is always greater than Y
2259 if (Ops[i] == Ops[i+1] ||
2260 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2261 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2262 --i; --e;
2263 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002264 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2265 --i; --e;
2266 }
2267
2268 if (Ops.size() == 1) return Ops[0];
2269
2270 assert(!Ops.empty() && "Reduced umax down to nothing!");
2271
2272 // Okay, it looks like we really DO need a umax expr. Check to see if we
2273 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002274 FoldingSetNodeID ID;
2275 ID.AddInteger(scUMaxExpr);
2276 ID.AddInteger(Ops.size());
2277 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2278 ID.AddPointer(Ops[i]);
2279 void *IP = 0;
2280 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002281 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2282 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002283 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2284 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002285 UniqueSCEVs.InsertNode(S, IP);
2286 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002287}
2288
Dan Gohman9311ef62009-06-24 14:49:00 +00002289const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2290 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002291 // ~smax(~x, ~y) == smin(x, y).
2292 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2293}
2294
Dan Gohman9311ef62009-06-24 14:49:00 +00002295const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2296 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002297 // ~umax(~x, ~y) == umin(x, y)
2298 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2299}
2300
Dan Gohman4f8eea82010-02-01 18:27:38 +00002301const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002302 // If we have TargetData, we can bypass creating a target-independent
2303 // constant expression and then folding it back into a ConstantInt.
2304 // This is just a compile-time optimization.
2305 if (TD)
2306 return getConstant(TD->getIntPtrType(getContext()),
2307 TD->getTypeAllocSize(AllocTy));
2308
Dan Gohman4f8eea82010-02-01 18:27:38 +00002309 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2310 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002311 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2312 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002313 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2314 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2315}
2316
2317const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2318 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2319 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002320 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2321 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002322 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2323 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2324}
2325
2326const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2327 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002328 // If we have TargetData, we can bypass creating a target-independent
2329 // constant expression and then folding it back into a ConstantInt.
2330 // This is just a compile-time optimization.
2331 if (TD)
2332 return getConstant(TD->getIntPtrType(getContext()),
2333 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2334
Dan Gohman0f5efe52010-01-28 02:15:55 +00002335 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002337 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2338 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002339 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002340 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002341}
2342
Dan Gohman4f8eea82010-02-01 18:27:38 +00002343const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2344 Constant *FieldNo) {
2345 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002346 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002347 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2348 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002349 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002350 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002351}
2352
Dan Gohman0bba49c2009-07-07 17:06:11 +00002353const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002354 // Don't attempt to do anything other than create a SCEVUnknown object
2355 // here. createSCEV only calls getUnknown after checking for all other
2356 // interesting possibilities, and any other code that calls getUnknown
2357 // is doing so in order to hide a value from SCEV canonicalization.
2358
Dan Gohman1c343752009-06-27 21:21:31 +00002359 FoldingSetNodeID ID;
2360 ID.AddInteger(scUnknown);
2361 ID.AddPointer(V);
2362 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002363 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2364 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2365 "Stale SCEVUnknown in uniquing map!");
2366 return S;
2367 }
2368 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2369 FirstUnknown);
2370 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002371 UniqueSCEVs.InsertNode(S, IP);
2372 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002373}
2374
Chris Lattner53e677a2004-04-02 20:23:17 +00002375//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002376// Basic SCEV Analysis and PHI Idiom Recognition Code
2377//
2378
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002379/// isSCEVable - Test if values of the given type are analyzable within
2380/// the SCEV framework. This primarily includes integer types, and it
2381/// can optionally include pointer types if the ScalarEvolution class
2382/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002383bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002384 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002385 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002386}
2387
2388/// getTypeSizeInBits - Return the size in bits of the specified type,
2389/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002390uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002391 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2392
2393 // If we have a TargetData, use it!
2394 if (TD)
2395 return TD->getTypeSizeInBits(Ty);
2396
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002397 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002398 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002399 return Ty->getPrimitiveSizeInBits();
2400
2401 // The only other support type is pointer. Without TargetData, conservatively
2402 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002403 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002404 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002405}
2406
2407/// getEffectiveSCEVType - Return a type with the same bitwidth as
2408/// the given type and which represents how SCEV will treat the given
2409/// type, for which isSCEVable must return true. For pointer types,
2410/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002411const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002412 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2413
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002414 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002415 return Ty;
2416
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002417 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002418 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002419 if (TD) return TD->getIntPtrType(getContext());
2420
2421 // Without TargetData, conservatively assume pointers are 64-bit.
2422 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002423}
Chris Lattner53e677a2004-04-02 20:23:17 +00002424
Dan Gohman0bba49c2009-07-07 17:06:11 +00002425const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002426 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002427}
2428
Chris Lattner53e677a2004-04-02 20:23:17 +00002429/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2430/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002431const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002432 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002433
Dan Gohman0bba49c2009-07-07 17:06:11 +00002434 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002435 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002436 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002437 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002438 return S;
2439}
2440
Dan Gohman2d1be872009-04-16 03:18:22 +00002441/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2442///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002443const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002444 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002445 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002446 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002447
2448 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002449 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002450 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002451 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002452}
2453
2454/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002455const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002456 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002457 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002458 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002459
2460 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002461 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002462 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002463 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002464 return getMinusSCEV(AllOnes, V);
2465}
2466
2467/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2468///
Dan Gohman9311ef62009-06-24 14:49:00 +00002469const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2470 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002471 // Fast path: X - X --> 0.
2472 if (LHS == RHS)
2473 return getConstant(LHS->getType(), 0);
2474
Dan Gohman2d1be872009-04-16 03:18:22 +00002475 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002476 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002477}
2478
2479/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2480/// input value to the specified type. If the type must be extended, it is zero
2481/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002482const SCEV *
2483ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002484 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002485 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002486 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2487 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002488 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002489 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002490 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002491 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002492 return getTruncateExpr(V, Ty);
2493 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002494}
2495
2496/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2497/// input value to the specified type. If the type must be extended, it is sign
2498/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002499const SCEV *
2500ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002501 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002502 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002505 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002506 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002507 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002508 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002509 return getTruncateExpr(V, Ty);
2510 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002511}
2512
Dan Gohman467c4302009-05-13 03:46:30 +00002513/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2514/// input value to the specified type. If the type must be extended, it is zero
2515/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002516const SCEV *
2517ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002518 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002519 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2520 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002521 "Cannot noop or zero extend with non-integer arguments!");
2522 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2523 "getNoopOrZeroExtend cannot truncate!");
2524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2525 return V; // No conversion
2526 return getZeroExtendExpr(V, Ty);
2527}
2528
2529/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2530/// input value to the specified type. If the type must be extended, it is sign
2531/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002532const SCEV *
2533ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002534 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002535 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2536 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002537 "Cannot noop or sign extend with non-integer arguments!");
2538 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2539 "getNoopOrSignExtend cannot truncate!");
2540 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2541 return V; // No conversion
2542 return getSignExtendExpr(V, Ty);
2543}
2544
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002545/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2546/// the input value to the specified type. If the type must be extended,
2547/// it is extended with unspecified bits. The conversion must not be
2548/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002549const SCEV *
2550ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002551 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002552 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2553 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002554 "Cannot noop or any extend with non-integer arguments!");
2555 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2556 "getNoopOrAnyExtend cannot truncate!");
2557 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2558 return V; // No conversion
2559 return getAnyExtendExpr(V, Ty);
2560}
2561
Dan Gohman467c4302009-05-13 03:46:30 +00002562/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2563/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002564const SCEV *
2565ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002566 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002567 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2568 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002569 "Cannot truncate or noop with non-integer arguments!");
2570 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2571 "getTruncateOrNoop cannot extend!");
2572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2573 return V; // No conversion
2574 return getTruncateExpr(V, Ty);
2575}
2576
Dan Gohmana334aa72009-06-22 00:31:57 +00002577/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2578/// the types using zero-extension, and then perform a umax operation
2579/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002580const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2581 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002582 const SCEV *PromotedLHS = LHS;
2583 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002584
2585 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2586 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2587 else
2588 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2589
2590 return getUMaxExpr(PromotedLHS, PromotedRHS);
2591}
2592
Dan Gohmanc9759e82009-06-22 15:03:27 +00002593/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2594/// the types using zero-extension, and then perform a umin operation
2595/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002596const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2597 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002598 const SCEV *PromotedLHS = LHS;
2599 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002600
2601 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2602 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2603 else
2604 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2605
2606 return getUMinExpr(PromotedLHS, PromotedRHS);
2607}
2608
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002609/// PushDefUseChildren - Push users of the given Instruction
2610/// onto the given Worklist.
2611static void
2612PushDefUseChildren(Instruction *I,
2613 SmallVectorImpl<Instruction *> &Worklist) {
2614 // Push the def-use children onto the Worklist stack.
2615 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2616 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002617 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002618}
2619
2620/// ForgetSymbolicValue - This looks up computed SCEV values for all
2621/// instructions that depend on the given instruction and removes them from
2622/// the Scalars map if they reference SymName. This is used during PHI
2623/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002624void
Dan Gohman85669632010-02-25 06:57:05 +00002625ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002626 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002627 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002628
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002629 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002630 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002631 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002632 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002633 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002634
Dan Gohman5d984912009-12-18 01:14:11 +00002635 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002636 Scalars.find(static_cast<Value *>(I));
2637 if (It != Scalars.end()) {
2638 // Short-circuit the def-use traversal if the symbolic name
2639 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002640 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002641 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002642
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002643 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002644 // structure, it's a PHI that's in the progress of being computed
2645 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2646 // additional loop trip count information isn't going to change anything.
2647 // In the second case, createNodeForPHI will perform the necessary
2648 // updates on its own when it gets to that point. In the third, we do
2649 // want to forget the SCEVUnknown.
2650 if (!isa<PHINode>(I) ||
2651 !isa<SCEVUnknown>(It->second) ||
2652 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002653 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002654 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002655 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002656 }
2657
2658 PushDefUseChildren(I, Worklist);
2659 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002660}
Chris Lattner53e677a2004-04-02 20:23:17 +00002661
2662/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2663/// a loop header, making it a potential recurrence, or it doesn't.
2664///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002665const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002666 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2667 if (L->getHeader() == PN->getParent()) {
2668 // The loop may have multiple entrances or multiple exits; we can analyze
2669 // this phi as an addrec if it has a unique entry value and a unique
2670 // backedge value.
2671 Value *BEValueV = 0, *StartValueV = 0;
2672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2673 Value *V = PN->getIncomingValue(i);
2674 if (L->contains(PN->getIncomingBlock(i))) {
2675 if (!BEValueV) {
2676 BEValueV = V;
2677 } else if (BEValueV != V) {
2678 BEValueV = 0;
2679 break;
2680 }
2681 } else if (!StartValueV) {
2682 StartValueV = V;
2683 } else if (StartValueV != V) {
2684 StartValueV = 0;
2685 break;
2686 }
2687 }
2688 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002689 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002690 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002691 assert(Scalars.find(PN) == Scalars.end() &&
2692 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002693 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002694
2695 // Using this symbolic name for the PHI, analyze the value coming around
2696 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002697 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002698
2699 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2700 // has a special value for the first iteration of the loop.
2701
2702 // If the value coming around the backedge is an add with the symbolic
2703 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002704 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002705 // If there is a single occurrence of the symbolic value, replace it
2706 // with a recurrence.
2707 unsigned FoundIndex = Add->getNumOperands();
2708 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2709 if (Add->getOperand(i) == SymbolicName)
2710 if (FoundIndex == e) {
2711 FoundIndex = i;
2712 break;
2713 }
2714
2715 if (FoundIndex != Add->getNumOperands()) {
2716 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002717 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002718 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2719 if (i != FoundIndex)
2720 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002721 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002722
2723 // This is not a valid addrec if the step amount is varying each
2724 // loop iteration, but is not itself an addrec in this loop.
2725 if (Accum->isLoopInvariant(L) ||
2726 (isa<SCEVAddRecExpr>(Accum) &&
2727 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002728 bool HasNUW = false;
2729 bool HasNSW = false;
2730
2731 // If the increment doesn't overflow, then neither the addrec nor
2732 // the post-increment will overflow.
2733 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2734 if (OBO->hasNoUnsignedWrap())
2735 HasNUW = true;
2736 if (OBO->hasNoSignedWrap())
2737 HasNSW = true;
2738 }
2739
Dan Gohman27dead42010-04-12 07:49:36 +00002740 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002741 const SCEV *PHISCEV =
2742 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002743
Dan Gohmana10756e2010-01-21 02:09:26 +00002744 // Since the no-wrap flags are on the increment, they apply to the
2745 // post-incremented value as well.
2746 if (Accum->isLoopInvariant(L))
2747 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2748 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002749
2750 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002751 // to be symbolic. We now need to go back and purge all of the
2752 // entries for the scalars that use the symbolic expression.
2753 ForgetSymbolicName(PN, SymbolicName);
2754 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002755 return PHISCEV;
2756 }
2757 }
Dan Gohman622ed672009-05-04 22:02:23 +00002758 } else if (const SCEVAddRecExpr *AddRec =
2759 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002760 // Otherwise, this could be a loop like this:
2761 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2762 // In this case, j = {1,+,1} and BEValue is j.
2763 // Because the other in-value of i (0) fits the evolution of BEValue
2764 // i really is an addrec evolution.
2765 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002766 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002767
2768 // If StartVal = j.start - j.stride, we can use StartVal as the
2769 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002770 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002771 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002772 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002773 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002774
2775 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002776 // to be symbolic. We now need to go back and purge all of the
2777 // entries for the scalars that use the symbolic expression.
2778 ForgetSymbolicName(PN, SymbolicName);
2779 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002780 return PHISCEV;
2781 }
2782 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002783 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002784 }
Dan Gohman27dead42010-04-12 07:49:36 +00002785 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002786
Dan Gohman85669632010-02-25 06:57:05 +00002787 // If the PHI has a single incoming value, follow that value, unless the
2788 // PHI's incoming blocks are in a different loop, in which case doing so
2789 // risks breaking LCSSA form. Instcombine would normally zap these, but
2790 // it doesn't have DominatorTree information, so it may miss cases.
2791 if (Value *V = PN->hasConstantValue(DT)) {
2792 bool AllSameLoop = true;
2793 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2794 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2795 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2796 AllSameLoop = false;
2797 break;
2798 }
2799 if (AllSameLoop)
2800 return getSCEV(V);
2801 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002802
Chris Lattner53e677a2004-04-02 20:23:17 +00002803 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002804 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002805}
2806
Dan Gohman26466c02009-05-08 20:26:55 +00002807/// createNodeForGEP - Expand GEP instructions into add and multiply
2808/// operations. This allows them to be analyzed by regular SCEV code.
2809///
Dan Gohmand281ed22009-12-18 02:09:29 +00002810const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002811
Dan Gohmanb9f96512010-06-30 07:16:37 +00002812 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2813 // Add expression, because the Instruction may be guarded by control flow
2814 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002815 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002816
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002817 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002818 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002819 // Don't attempt to analyze GEPs over unsized objects.
2820 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2821 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002822 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002823 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002824 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002825 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002826 I != E; ++I) {
2827 Value *Index = *I;
2828 // Compute the (potentially symbolic) offset in bytes for this index.
2829 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2830 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002831 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002832 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2833
Dan Gohmanb9f96512010-06-30 07:16:37 +00002834 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002835 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002836 } else {
2837 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002838 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2839 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002840 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002841 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2842
Dan Gohmanb9f96512010-06-30 07:16:37 +00002843 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002844 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002845
2846 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002847 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002848 }
2849 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002850
2851 // Get the SCEV for the GEP base.
2852 const SCEV *BaseS = getSCEV(Base);
2853
Dan Gohmanb9f96512010-06-30 07:16:37 +00002854 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002855 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002856}
2857
Nick Lewycky83bb0052007-11-22 07:59:40 +00002858/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2859/// guaranteed to end in (at every loop iteration). It is, at the same time,
2860/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2861/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002862uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002863ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002864 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002865 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002866
Dan Gohman622ed672009-05-04 22:02:23 +00002867 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002868 return std::min(GetMinTrailingZeros(T->getOperand()),
2869 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002870
Dan Gohman622ed672009-05-04 22:02:23 +00002871 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002872 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2873 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2874 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002875 }
2876
Dan Gohman622ed672009-05-04 22:02:23 +00002877 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002878 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2879 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2880 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002881 }
2882
Dan Gohman622ed672009-05-04 22:02:23 +00002883 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002884 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002885 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002886 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002887 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002888 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002889 }
2890
Dan Gohman622ed672009-05-04 22:02:23 +00002891 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002892 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002893 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2894 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002895 for (unsigned i = 1, e = M->getNumOperands();
2896 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002897 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002898 BitWidth);
2899 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002900 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002901
Dan Gohman622ed672009-05-04 22:02:23 +00002902 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002903 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002904 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002905 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002906 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002907 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002908 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002909
Dan Gohman622ed672009-05-04 22:02:23 +00002910 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002911 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002912 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002913 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002914 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002915 return MinOpRes;
2916 }
2917
Dan Gohman622ed672009-05-04 22:02:23 +00002918 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002919 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002920 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002921 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002922 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002923 return MinOpRes;
2924 }
2925
Dan Gohman2c364ad2009-06-19 23:29:04 +00002926 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2927 // For a SCEVUnknown, ask ValueTracking.
2928 unsigned BitWidth = getTypeSizeInBits(U->getType());
2929 APInt Mask = APInt::getAllOnesValue(BitWidth);
2930 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2931 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2932 return Zeros.countTrailingOnes();
2933 }
2934
2935 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002936 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002937}
Chris Lattner53e677a2004-04-02 20:23:17 +00002938
Dan Gohman85b05a22009-07-13 21:35:55 +00002939/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2940///
2941ConstantRange
2942ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002943
2944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002945 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002947 unsigned BitWidth = getTypeSizeInBits(S->getType());
2948 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2949
2950 // If the value has known zeros, the maximum unsigned value will have those
2951 // known zeros as well.
2952 uint32_t TZ = GetMinTrailingZeros(S);
2953 if (TZ != 0)
2954 ConservativeResult =
2955 ConstantRange(APInt::getMinValue(BitWidth),
2956 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2957
Dan Gohman85b05a22009-07-13 21:35:55 +00002958 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2959 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2960 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2961 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002962 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002963 }
2964
2965 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2966 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2967 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2968 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002969 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002970 }
2971
2972 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2973 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2974 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2975 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002976 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002977 }
2978
2979 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2980 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2981 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2982 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002983 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002984 }
2985
2986 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2987 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2988 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002989 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002990 }
2991
2992 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002994 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002995 }
2996
2997 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2998 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002999 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003000 }
3001
3002 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3003 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003004 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003005 }
3006
Dan Gohman85b05a22009-07-13 21:35:55 +00003007 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003008 // If there's no unsigned wrap, the value will never be less than its
3009 // initial value.
3010 if (AddRec->hasNoUnsignedWrap())
3011 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003012 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003013 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003014 ConservativeResult.intersectWith(
3015 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003016
3017 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003018 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003019 const Type *Ty = AddRec->getType();
3020 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003021 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3022 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003023 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3024
3025 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003026 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003027
3028 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003029 ConstantRange StepRange = getSignedRange(Step);
3030 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3031 ConstantRange EndRange =
3032 StartRange.add(MaxBECountRange.multiply(StepRange));
3033
3034 // Check for overflow. This must be done with ConstantRange arithmetic
3035 // because we could be called from within the ScalarEvolution overflow
3036 // checking code.
3037 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3038 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3039 ConstantRange ExtMaxBECountRange =
3040 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3041 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3042 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3043 ExtEndRange)
3044 return ConservativeResult;
3045
Dan Gohman85b05a22009-07-13 21:35:55 +00003046 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3047 EndRange.getUnsignedMin());
3048 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3049 EndRange.getUnsignedMax());
3050 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003051 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003052 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00003053 }
3054 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003055
3056 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003057 }
3058
3059 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3060 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003061 APInt Mask = APInt::getAllOnesValue(BitWidth);
3062 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3063 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003064 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003065 return ConservativeResult;
3066 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003067 }
3068
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003069 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003070}
3071
Dan Gohman85b05a22009-07-13 21:35:55 +00003072/// getSignedRange - Determine the signed range for a particular SCEV.
3073///
3074ConstantRange
3075ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003076
Dan Gohman85b05a22009-07-13 21:35:55 +00003077 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3078 return ConstantRange(C->getValue()->getValue());
3079
Dan Gohman52fddd32010-01-26 04:40:18 +00003080 unsigned BitWidth = getTypeSizeInBits(S->getType());
3081 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3082
3083 // If the value has known zeros, the maximum signed value will have those
3084 // known zeros as well.
3085 uint32_t TZ = GetMinTrailingZeros(S);
3086 if (TZ != 0)
3087 ConservativeResult =
3088 ConstantRange(APInt::getSignedMinValue(BitWidth),
3089 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3090
Dan Gohman85b05a22009-07-13 21:35:55 +00003091 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3092 ConstantRange X = getSignedRange(Add->getOperand(0));
3093 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3094 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003095 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003096 }
3097
Dan Gohman85b05a22009-07-13 21:35:55 +00003098 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3099 ConstantRange X = getSignedRange(Mul->getOperand(0));
3100 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3101 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003102 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003103 }
3104
Dan Gohman85b05a22009-07-13 21:35:55 +00003105 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3106 ConstantRange X = getSignedRange(SMax->getOperand(0));
3107 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3108 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003109 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003110 }
Dan Gohman62849c02009-06-24 01:05:09 +00003111
Dan Gohman85b05a22009-07-13 21:35:55 +00003112 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3113 ConstantRange X = getSignedRange(UMax->getOperand(0));
3114 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3115 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003116 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003117 }
Dan Gohman62849c02009-06-24 01:05:09 +00003118
Dan Gohman85b05a22009-07-13 21:35:55 +00003119 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3120 ConstantRange X = getSignedRange(UDiv->getLHS());
3121 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003122 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003123 }
Dan Gohman62849c02009-06-24 01:05:09 +00003124
Dan Gohman85b05a22009-07-13 21:35:55 +00003125 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3126 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003127 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003128 }
3129
3130 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3131 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003132 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003133 }
3134
3135 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3136 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003137 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003138 }
3139
Dan Gohman85b05a22009-07-13 21:35:55 +00003140 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003141 // If there's no signed wrap, and all the operands have the same sign or
3142 // zero, the value won't ever change sign.
3143 if (AddRec->hasNoSignedWrap()) {
3144 bool AllNonNeg = true;
3145 bool AllNonPos = true;
3146 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3147 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3148 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3149 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003150 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003151 ConservativeResult = ConservativeResult.intersectWith(
3152 ConstantRange(APInt(BitWidth, 0),
3153 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003154 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003155 ConservativeResult = ConservativeResult.intersectWith(
3156 ConstantRange(APInt::getSignedMinValue(BitWidth),
3157 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003158 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003159
3160 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003161 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003162 const Type *Ty = AddRec->getType();
3163 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003164 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3165 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003166 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3167
3168 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003169 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003170
3171 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003172 ConstantRange StepRange = getSignedRange(Step);
3173 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3174 ConstantRange EndRange =
3175 StartRange.add(MaxBECountRange.multiply(StepRange));
3176
3177 // Check for overflow. This must be done with ConstantRange arithmetic
3178 // because we could be called from within the ScalarEvolution overflow
3179 // checking code.
3180 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3181 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3182 ConstantRange ExtMaxBECountRange =
3183 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3184 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3185 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3186 ExtEndRange)
3187 return ConservativeResult;
3188
Dan Gohman85b05a22009-07-13 21:35:55 +00003189 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3190 EndRange.getSignedMin());
3191 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3192 EndRange.getSignedMax());
3193 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003194 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003195 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003196 }
Dan Gohman62849c02009-06-24 01:05:09 +00003197 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003198
3199 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003200 }
3201
Dan Gohman2c364ad2009-06-19 23:29:04 +00003202 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3203 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003204 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003205 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003206 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3207 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003208 return ConservativeResult;
3209 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003210 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003211 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003212 }
3213
Dan Gohman52fddd32010-01-26 04:40:18 +00003214 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003215}
3216
Chris Lattner53e677a2004-04-02 20:23:17 +00003217/// createSCEV - We know that there is no SCEV for the specified value.
3218/// Analyze the expression.
3219///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003220const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003221 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003222 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003223
Dan Gohman6c459a22008-06-22 19:56:46 +00003224 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003225 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003226 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003227
3228 // Don't attempt to analyze instructions in blocks that aren't
3229 // reachable. Such instructions don't matter, and they aren't required
3230 // to obey basic rules for definitions dominating uses which this
3231 // analysis depends on.
3232 if (!DT->isReachableFromEntry(I->getParent()))
3233 return getUnknown(V);
3234 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003235 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003236 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3237 return getConstant(CI);
3238 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003239 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003240 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3241 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003242 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003243 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003244
Dan Gohmanca178902009-07-17 20:47:02 +00003245 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003246 switch (Opcode) {
Dan Gohman70eff632010-06-30 17:27:11 +00003247 case Instruction::Add:
3248 return getAddExpr(getSCEV(U->getOperand(0)),
3249 getSCEV(U->getOperand(1)));
3250 case Instruction::Mul:
3251 return getMulExpr(getSCEV(U->getOperand(0)),
3252 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003253 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003254 return getUDivExpr(getSCEV(U->getOperand(0)),
3255 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003256 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003257 return getMinusSCEV(getSCEV(U->getOperand(0)),
3258 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003259 case Instruction::And:
3260 // For an expression like x&255 that merely masks off the high bits,
3261 // use zext(trunc(x)) as the SCEV expression.
3262 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003263 if (CI->isNullValue())
3264 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003265 if (CI->isAllOnesValue())
3266 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003267 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003268
3269 // Instcombine's ShrinkDemandedConstant may strip bits out of
3270 // constants, obscuring what would otherwise be a low-bits mask.
3271 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3272 // knew about to reconstruct a low-bits mask value.
3273 unsigned LZ = A.countLeadingZeros();
3274 unsigned BitWidth = A.getBitWidth();
3275 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3276 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3277 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3278
3279 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3280
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003281 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003282 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003283 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003284 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003285 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003286 }
3287 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003288
Dan Gohman6c459a22008-06-22 19:56:46 +00003289 case Instruction::Or:
3290 // If the RHS of the Or is a constant, we may have something like:
3291 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3292 // optimizations will transparently handle this case.
3293 //
3294 // In order for this transformation to be safe, the LHS must be of the
3295 // form X*(2^n) and the Or constant must be less than 2^n.
3296 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003297 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003298 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003299 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003300 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3301 // Build a plain add SCEV.
3302 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3303 // If the LHS of the add was an addrec and it has no-wrap flags,
3304 // transfer the no-wrap flags, since an or won't introduce a wrap.
3305 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3306 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3307 if (OldAR->hasNoUnsignedWrap())
3308 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3309 if (OldAR->hasNoSignedWrap())
3310 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3311 }
3312 return S;
3313 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003314 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003315 break;
3316 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003317 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003318 // If the RHS of the xor is a signbit, then this is just an add.
3319 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003320 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003321 return getAddExpr(getSCEV(U->getOperand(0)),
3322 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003323
3324 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003325 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003326 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003327
3328 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3329 // This is a variant of the check for xor with -1, and it handles
3330 // the case where instcombine has trimmed non-demanded bits out
3331 // of an xor with -1.
3332 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3333 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3334 if (BO->getOpcode() == Instruction::And &&
3335 LCI->getValue() == CI->getValue())
3336 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003337 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003338 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003339 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003340 const Type *Z0Ty = Z0->getType();
3341 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3342
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003343 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003344 // mask off the high bits. Complement the operand and
3345 // re-apply the zext.
3346 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3347 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3348
3349 // If C is a single bit, it may be in the sign-bit position
3350 // before the zero-extend. In this case, represent the xor
3351 // using an add, which is equivalent, and re-apply the zext.
3352 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3353 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3354 Trunc.isSignBit())
3355 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3356 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003357 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003358 }
3359 break;
3360
3361 case Instruction::Shl:
3362 // Turn shift left of a constant amount into a multiply.
3363 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003364 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003365
3366 // If the shift count is not less than the bitwidth, the result of
3367 // the shift is undefined. Don't try to analyze it, because the
3368 // resolution chosen here may differ from the resolution chosen in
3369 // other parts of the compiler.
3370 if (SA->getValue().uge(BitWidth))
3371 break;
3372
Owen Andersoneed707b2009-07-24 23:12:02 +00003373 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003374 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003375 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003376 }
3377 break;
3378
Nick Lewycky01eaf802008-07-07 06:15:49 +00003379 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003380 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003381 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003382 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003383
3384 // If the shift count is not less than the bitwidth, the result of
3385 // the shift is undefined. Don't try to analyze it, because the
3386 // resolution chosen here may differ from the resolution chosen in
3387 // other parts of the compiler.
3388 if (SA->getValue().uge(BitWidth))
3389 break;
3390
Owen Andersoneed707b2009-07-24 23:12:02 +00003391 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003392 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003393 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003394 }
3395 break;
3396
Dan Gohman4ee29af2009-04-21 02:26:00 +00003397 case Instruction::AShr:
3398 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3399 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003400 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003401 if (L->getOpcode() == Instruction::Shl &&
3402 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003403 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3404
3405 // If the shift count is not less than the bitwidth, the result of
3406 // the shift is undefined. Don't try to analyze it, because the
3407 // resolution chosen here may differ from the resolution chosen in
3408 // other parts of the compiler.
3409 if (CI->getValue().uge(BitWidth))
3410 break;
3411
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003412 uint64_t Amt = BitWidth - CI->getZExtValue();
3413 if (Amt == BitWidth)
3414 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003415 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003416 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003417 IntegerType::get(getContext(),
3418 Amt)),
3419 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003420 }
3421 break;
3422
Dan Gohman6c459a22008-06-22 19:56:46 +00003423 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003424 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003425
3426 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003427 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003428
3429 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003430 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003431
3432 case Instruction::BitCast:
3433 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003434 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003435 return getSCEV(U->getOperand(0));
3436 break;
3437
Dan Gohman4f8eea82010-02-01 18:27:38 +00003438 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3439 // lead to pointer expressions which cannot safely be expanded to GEPs,
3440 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3441 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003442
Dan Gohman26466c02009-05-08 20:26:55 +00003443 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003444 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003445
Dan Gohman6c459a22008-06-22 19:56:46 +00003446 case Instruction::PHI:
3447 return createNodeForPHI(cast<PHINode>(U));
3448
3449 case Instruction::Select:
3450 // This could be a smax or umax that was lowered earlier.
3451 // Try to recover it.
3452 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3453 Value *LHS = ICI->getOperand(0);
3454 Value *RHS = ICI->getOperand(1);
3455 switch (ICI->getPredicate()) {
3456 case ICmpInst::ICMP_SLT:
3457 case ICmpInst::ICMP_SLE:
3458 std::swap(LHS, RHS);
3459 // fall through
3460 case ICmpInst::ICMP_SGT:
3461 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003462 // a >s b ? a+x : b+x -> smax(a, b)+x
3463 // a >s b ? b+x : a+x -> smin(a, b)+x
3464 if (LHS->getType() == U->getType()) {
3465 const SCEV *LS = getSCEV(LHS);
3466 const SCEV *RS = getSCEV(RHS);
3467 const SCEV *LA = getSCEV(U->getOperand(1));
3468 const SCEV *RA = getSCEV(U->getOperand(2));
3469 const SCEV *LDiff = getMinusSCEV(LA, LS);
3470 const SCEV *RDiff = getMinusSCEV(RA, RS);
3471 if (LDiff == RDiff)
3472 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3473 LDiff = getMinusSCEV(LA, RS);
3474 RDiff = getMinusSCEV(RA, LS);
3475 if (LDiff == RDiff)
3476 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3477 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003478 break;
3479 case ICmpInst::ICMP_ULT:
3480 case ICmpInst::ICMP_ULE:
3481 std::swap(LHS, RHS);
3482 // fall through
3483 case ICmpInst::ICMP_UGT:
3484 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003485 // a >u b ? a+x : b+x -> umax(a, b)+x
3486 // a >u b ? b+x : a+x -> umin(a, b)+x
3487 if (LHS->getType() == U->getType()) {
3488 const SCEV *LS = getSCEV(LHS);
3489 const SCEV *RS = getSCEV(RHS);
3490 const SCEV *LA = getSCEV(U->getOperand(1));
3491 const SCEV *RA = getSCEV(U->getOperand(2));
3492 const SCEV *LDiff = getMinusSCEV(LA, LS);
3493 const SCEV *RDiff = getMinusSCEV(RA, RS);
3494 if (LDiff == RDiff)
3495 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3496 LDiff = getMinusSCEV(LA, RS);
3497 RDiff = getMinusSCEV(RA, LS);
3498 if (LDiff == RDiff)
3499 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3500 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003501 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003502 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003503 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3504 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003505 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003506 cast<ConstantInt>(RHS)->isZero()) {
3507 const SCEV *One = getConstant(LHS->getType(), 1);
3508 const SCEV *LS = getSCEV(LHS);
3509 const SCEV *LA = getSCEV(U->getOperand(1));
3510 const SCEV *RA = getSCEV(U->getOperand(2));
3511 const SCEV *LDiff = getMinusSCEV(LA, LS);
3512 const SCEV *RDiff = getMinusSCEV(RA, One);
3513 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003514 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003515 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003516 break;
3517 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003518 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3519 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003520 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003521 cast<ConstantInt>(RHS)->isZero()) {
3522 const SCEV *One = getConstant(LHS->getType(), 1);
3523 const SCEV *LS = getSCEV(LHS);
3524 const SCEV *LA = getSCEV(U->getOperand(1));
3525 const SCEV *RA = getSCEV(U->getOperand(2));
3526 const SCEV *LDiff = getMinusSCEV(LA, One);
3527 const SCEV *RDiff = getMinusSCEV(RA, LS);
3528 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003529 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003530 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003531 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003532 default:
3533 break;
3534 }
3535 }
3536
3537 default: // We cannot analyze this expression.
3538 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003539 }
3540
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003541 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003542}
3543
3544
3545
3546//===----------------------------------------------------------------------===//
3547// Iteration Count Computation Code
3548//
3549
Dan Gohman46bdfb02009-02-24 18:55:53 +00003550/// getBackedgeTakenCount - If the specified loop has a predictable
3551/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3552/// object. The backedge-taken count is the number of times the loop header
3553/// will be branched to from within the loop. This is one less than the
3554/// trip count of the loop, since it doesn't count the first iteration,
3555/// when the header is branched to from outside the loop.
3556///
3557/// Note that it is not valid to call this method on a loop without a
3558/// loop-invariant backedge-taken count (see
3559/// hasLoopInvariantBackedgeTakenCount).
3560///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003561const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003562 return getBackedgeTakenInfo(L).Exact;
3563}
3564
3565/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3566/// return the least SCEV value that is known never to be less than the
3567/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003568const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003569 return getBackedgeTakenInfo(L).Max;
3570}
3571
Dan Gohman59ae6b92009-07-08 19:23:34 +00003572/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3573/// onto the given Worklist.
3574static void
3575PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3576 BasicBlock *Header = L->getHeader();
3577
3578 // Push all Loop-header PHIs onto the Worklist stack.
3579 for (BasicBlock::iterator I = Header->begin();
3580 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3581 Worklist.push_back(PN);
3582}
3583
Dan Gohmana1af7572009-04-30 20:47:05 +00003584const ScalarEvolution::BackedgeTakenInfo &
3585ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003586 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003587 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003588 // update the value. The temporary CouldNotCompute value tells SCEV
3589 // code elsewhere that it shouldn't attempt to request a new
3590 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003591 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003592 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3593 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003594 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3595 if (BECount.Exact != getCouldNotCompute()) {
3596 assert(BECount.Exact->isLoopInvariant(L) &&
3597 BECount.Max->isLoopInvariant(L) &&
3598 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003599 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003600
Dan Gohman01ecca22009-04-27 20:16:15 +00003601 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003602 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003603 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003604 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003605 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003606 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003607 if (isa<PHINode>(L->getHeader()->begin()))
3608 // Only count loops that have phi nodes as not being computable.
3609 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003610 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003611
3612 // Now that we know more about the trip count for this loop, forget any
3613 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003614 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003615 // information. This is similar to the code in forgetLoop, except that
3616 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003617 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003618 SmallVector<Instruction *, 16> Worklist;
3619 PushLoopPHIs(L, Worklist);
3620
3621 SmallPtrSet<Instruction *, 8> Visited;
3622 while (!Worklist.empty()) {
3623 Instruction *I = Worklist.pop_back_val();
3624 if (!Visited.insert(I)) continue;
3625
Dan Gohman5d984912009-12-18 01:14:11 +00003626 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003627 Scalars.find(static_cast<Value *>(I));
3628 if (It != Scalars.end()) {
3629 // SCEVUnknown for a PHI either means that it has an unrecognized
3630 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003631 // by createNodeForPHI. In the former case, additional loop trip
3632 // count information isn't going to change anything. In the later
3633 // case, createNodeForPHI will perform the necessary updates on its
3634 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003635 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3636 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003637 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003638 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003639 if (PHINode *PN = dyn_cast<PHINode>(I))
3640 ConstantEvolutionLoopExitValue.erase(PN);
3641 }
3642
3643 PushDefUseChildren(I, Worklist);
3644 }
3645 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003646 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003647 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003648}
3649
Dan Gohman4c7279a2009-10-31 15:04:55 +00003650/// forgetLoop - This method should be called by the client when it has
3651/// changed a loop in a way that may effect ScalarEvolution's ability to
3652/// compute a trip count, or if the loop is deleted.
3653void ScalarEvolution::forgetLoop(const Loop *L) {
3654 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003655 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003656
Dan Gohman4c7279a2009-10-31 15:04:55 +00003657 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003658 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003659 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003660
Dan Gohman59ae6b92009-07-08 19:23:34 +00003661 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003662 while (!Worklist.empty()) {
3663 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003664 if (!Visited.insert(I)) continue;
3665
Dan Gohman5d984912009-12-18 01:14:11 +00003666 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003667 Scalars.find(static_cast<Value *>(I));
3668 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003669 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003670 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003671 if (PHINode *PN = dyn_cast<PHINode>(I))
3672 ConstantEvolutionLoopExitValue.erase(PN);
3673 }
3674
3675 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003676 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003677}
3678
Eric Christophere6cbfa62010-07-29 01:25:38 +00003679/// forgetValue - This method should be called by the client when it has
3680/// changed a value in a way that may effect its value, or which may
3681/// disconnect it from a def-use chain linking it to a loop.
3682void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003683 Instruction *I = dyn_cast<Instruction>(V);
3684 if (!I) return;
3685
3686 // Drop information about expressions based on loop-header PHIs.
3687 SmallVector<Instruction *, 16> Worklist;
3688 Worklist.push_back(I);
3689
3690 SmallPtrSet<Instruction *, 8> Visited;
3691 while (!Worklist.empty()) {
3692 I = Worklist.pop_back_val();
3693 if (!Visited.insert(I)) continue;
3694
3695 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3696 Scalars.find(static_cast<Value *>(I));
3697 if (It != Scalars.end()) {
3698 ValuesAtScopes.erase(It->second);
3699 Scalars.erase(It);
3700 if (PHINode *PN = dyn_cast<PHINode>(I))
3701 ConstantEvolutionLoopExitValue.erase(PN);
3702 }
3703
3704 PushDefUseChildren(I, Worklist);
3705 }
3706}
3707
Dan Gohman46bdfb02009-02-24 18:55:53 +00003708/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3709/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003710ScalarEvolution::BackedgeTakenInfo
3711ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003712 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003713 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003714
Dan Gohmana334aa72009-06-22 00:31:57 +00003715 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003716 const SCEV *BECount = getCouldNotCompute();
3717 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003718 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003719 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3720 BackedgeTakenInfo NewBTI =
3721 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003722
Dan Gohman1c343752009-06-27 21:21:31 +00003723 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003724 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003725 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003726 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003727 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003728 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003729 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003730 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003731 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003732 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003733 }
Dan Gohman1c343752009-06-27 21:21:31 +00003734 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003735 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003736 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003737 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003738 }
3739
3740 return BackedgeTakenInfo(BECount, MaxBECount);
3741}
3742
3743/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3744/// of the specified loop will execute if it exits via the specified block.
3745ScalarEvolution::BackedgeTakenInfo
3746ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3747 BasicBlock *ExitingBlock) {
3748
3749 // Okay, we've chosen an exiting block. See what condition causes us to
3750 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003751 //
3752 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003753 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003754 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003755 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003756
Chris Lattner8b0e3602007-01-07 02:24:26 +00003757 // At this point, we know we have a conditional branch that determines whether
3758 // the loop is exited. However, we don't know if the branch is executed each
3759 // time through the loop. If not, then the execution count of the branch will
3760 // not be equal to the trip count of the loop.
3761 //
3762 // Currently we check for this by checking to see if the Exit branch goes to
3763 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003764 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003765 // loop header. This is common for un-rotated loops.
3766 //
3767 // If both of those tests fail, walk up the unique predecessor chain to the
3768 // header, stopping if there is an edge that doesn't exit the loop. If the
3769 // header is reached, the execution count of the branch will be equal to the
3770 // trip count of the loop.
3771 //
3772 // More extensive analysis could be done to handle more cases here.
3773 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003774 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003775 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003776 ExitBr->getParent() != L->getHeader()) {
3777 // The simple checks failed, try climbing the unique predecessor chain
3778 // up to the header.
3779 bool Ok = false;
3780 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3781 BasicBlock *Pred = BB->getUniquePredecessor();
3782 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003783 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003784 TerminatorInst *PredTerm = Pred->getTerminator();
3785 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3786 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3787 if (PredSucc == BB)
3788 continue;
3789 // If the predecessor has a successor that isn't BB and isn't
3790 // outside the loop, assume the worst.
3791 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003792 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003793 }
3794 if (Pred == L->getHeader()) {
3795 Ok = true;
3796 break;
3797 }
3798 BB = Pred;
3799 }
3800 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003801 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003802 }
3803
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003804 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003805 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3806 ExitBr->getSuccessor(0),
3807 ExitBr->getSuccessor(1));
3808}
3809
3810/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3811/// backedge of the specified loop will execute if its exit condition
3812/// were a conditional branch of ExitCond, TBB, and FBB.
3813ScalarEvolution::BackedgeTakenInfo
3814ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3815 Value *ExitCond,
3816 BasicBlock *TBB,
3817 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003818 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003819 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3820 if (BO->getOpcode() == Instruction::And) {
3821 // Recurse on the operands of the and.
3822 BackedgeTakenInfo BTI0 =
3823 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3824 BackedgeTakenInfo BTI1 =
3825 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003826 const SCEV *BECount = getCouldNotCompute();
3827 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003828 if (L->contains(TBB)) {
3829 // Both conditions must be true for the loop to continue executing.
3830 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003831 if (BTI0.Exact == getCouldNotCompute() ||
3832 BTI1.Exact == getCouldNotCompute())
3833 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003834 else
3835 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003836 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003837 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003838 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003839 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003840 else
3841 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003842 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003843 // Both conditions must be true at the same time for the loop to exit.
3844 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003845 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003846 if (BTI0.Max == BTI1.Max)
3847 MaxBECount = BTI0.Max;
3848 if (BTI0.Exact == BTI1.Exact)
3849 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003850 }
3851
3852 return BackedgeTakenInfo(BECount, MaxBECount);
3853 }
3854 if (BO->getOpcode() == Instruction::Or) {
3855 // Recurse on the operands of the or.
3856 BackedgeTakenInfo BTI0 =
3857 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3858 BackedgeTakenInfo BTI1 =
3859 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003860 const SCEV *BECount = getCouldNotCompute();
3861 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003862 if (L->contains(FBB)) {
3863 // Both conditions must be false for the loop to continue executing.
3864 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003865 if (BTI0.Exact == getCouldNotCompute() ||
3866 BTI1.Exact == getCouldNotCompute())
3867 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003868 else
3869 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003870 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003871 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003872 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003873 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003874 else
3875 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003876 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003877 // Both conditions must be false at the same time for the loop to exit.
3878 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003879 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003880 if (BTI0.Max == BTI1.Max)
3881 MaxBECount = BTI0.Max;
3882 if (BTI0.Exact == BTI1.Exact)
3883 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003884 }
3885
3886 return BackedgeTakenInfo(BECount, MaxBECount);
3887 }
3888 }
3889
3890 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003891 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003892 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3893 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003894
Dan Gohman00cb5b72010-02-19 18:12:07 +00003895 // Check for a constant condition. These are normally stripped out by
3896 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3897 // preserve the CFG and is temporarily leaving constant conditions
3898 // in place.
3899 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3900 if (L->contains(FBB) == !CI->getZExtValue())
3901 // The backedge is always taken.
3902 return getCouldNotCompute();
3903 else
3904 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003905 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003906 }
3907
Eli Friedman361e54d2009-05-09 12:32:42 +00003908 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003909 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3910}
3911
3912/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3913/// backedge of the specified loop will execute if its exit condition
3914/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3915ScalarEvolution::BackedgeTakenInfo
3916ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3917 ICmpInst *ExitCond,
3918 BasicBlock *TBB,
3919 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003920
Reid Spencere4d87aa2006-12-23 06:05:41 +00003921 // If the condition was exit on true, convert the condition to exit on false
3922 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003923 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003924 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003925 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003926 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003927
3928 // Handle common loops like: for (X = "string"; *X; ++X)
3929 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3930 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003931 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003932 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003933 if (ItCnt.hasAnyInfo())
3934 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003935 }
3936
Dan Gohman0bba49c2009-07-07 17:06:11 +00003937 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3938 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003939
3940 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003941 LHS = getSCEVAtScope(LHS, L);
3942 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003943
Dan Gohman64a845e2009-06-24 04:48:43 +00003944 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003945 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003946 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3947 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003948 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003949 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003950 }
3951
Dan Gohman03557dc2010-05-03 16:35:17 +00003952 // Simplify the operands before analyzing them.
3953 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3954
Chris Lattner53e677a2004-04-02 20:23:17 +00003955 // If we have a comparison of a chrec against a constant, try to use value
3956 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003957 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3958 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003959 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003960 // Form the constant range.
3961 ConstantRange CompRange(
3962 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003963
Dan Gohman0bba49c2009-07-07 17:06:11 +00003964 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003965 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003966 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003967
Chris Lattner53e677a2004-04-02 20:23:17 +00003968 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003969 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003970 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003971 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3972 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003973 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003975 case ICmpInst::ICMP_EQ: { // while (X == Y)
3976 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003977 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3978 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003979 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003980 }
3981 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003982 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3983 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003984 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 }
3986 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003987 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3988 getNotSCEV(RHS), L, true);
3989 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003990 break;
3991 }
3992 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003993 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3994 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003995 break;
3996 }
3997 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003998 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3999 getNotSCEV(RHS), L, false);
4000 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004001 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004002 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004003 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004004#if 0
David Greene25e0e872009-12-23 22:18:14 +00004005 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004006 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004007 dbgs() << "[unsigned] ";
4008 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004009 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004010 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004011#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004012 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004013 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004014 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004015 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004016}
4017
Chris Lattner673e02b2004-10-12 01:49:27 +00004018static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004019EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4020 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004021 const SCEV *InVal = SE.getConstant(C);
4022 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004023 assert(isa<SCEVConstant>(Val) &&
4024 "Evaluation of SCEV at constant didn't fold correctly?");
4025 return cast<SCEVConstant>(Val)->getValue();
4026}
4027
4028/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4029/// and a GEP expression (missing the pointer index) indexing into it, return
4030/// the addressed element of the initializer or null if the index expression is
4031/// invalid.
4032static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004033GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004034 const std::vector<ConstantInt*> &Indices) {
4035 Constant *Init = GV->getInitializer();
4036 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004037 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004038 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4039 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4040 Init = cast<Constant>(CS->getOperand(Idx));
4041 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4042 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4043 Init = cast<Constant>(CA->getOperand(Idx));
4044 } else if (isa<ConstantAggregateZero>(Init)) {
4045 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4046 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004047 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004048 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4049 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004050 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004051 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004052 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004053 }
4054 return 0;
4055 } else {
4056 return 0; // Unknown initializer type
4057 }
4058 }
4059 return Init;
4060}
4061
Dan Gohman46bdfb02009-02-24 18:55:53 +00004062/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4063/// 'icmp op load X, cst', try to see if we can compute the backedge
4064/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004065ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004066ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4067 LoadInst *LI,
4068 Constant *RHS,
4069 const Loop *L,
4070 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004071 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004072
4073 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004074 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004075 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004076 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004077
4078 // Make sure that it is really a constant global we are gepping, with an
4079 // initializer, and make sure the first IDX is really 0.
4080 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004081 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004082 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4083 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004084 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004085
4086 // Okay, we allow one non-constant index into the GEP instruction.
4087 Value *VarIdx = 0;
4088 std::vector<ConstantInt*> Indexes;
4089 unsigned VarIdxNum = 0;
4090 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4091 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4092 Indexes.push_back(CI);
4093 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004094 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004095 VarIdx = GEP->getOperand(i);
4096 VarIdxNum = i-2;
4097 Indexes.push_back(0);
4098 }
4099
4100 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4101 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004102 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004103 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004104
4105 // We can only recognize very limited forms of loop index expressions, in
4106 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004107 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00004108 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4109 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4110 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004111 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004112
4113 unsigned MaxSteps = MaxBruteForceIterations;
4114 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004115 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004116 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004117 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004118
4119 // Form the GEP offset.
4120 Indexes[VarIdxNum] = Val;
4121
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004122 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004123 if (Result == 0) break; // Cannot compute!
4124
4125 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004126 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004127 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004128 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004129#if 0
David Greene25e0e872009-12-23 22:18:14 +00004130 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004131 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4132 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004133#endif
4134 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004135 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004136 }
4137 }
Dan Gohman1c343752009-06-27 21:21:31 +00004138 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004139}
4140
4141
Chris Lattner3221ad02004-04-17 22:58:41 +00004142/// CanConstantFold - Return true if we can constant fold an instruction of the
4143/// specified type, assuming that all operands were constants.
4144static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004145 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004146 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4147 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004148
Chris Lattner3221ad02004-04-17 22:58:41 +00004149 if (const CallInst *CI = dyn_cast<CallInst>(I))
4150 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004151 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004152 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004153}
4154
Chris Lattner3221ad02004-04-17 22:58:41 +00004155/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4156/// in the loop that V is derived from. We allow arbitrary operations along the
4157/// way, but the operands of an operation must either be constants or a value
4158/// derived from a constant PHI. If this expression does not fit with these
4159/// constraints, return null.
4160static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4161 // If this is not an instruction, or if this is an instruction outside of the
4162 // loop, it can't be derived from a loop PHI.
4163 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004164 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004165
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004166 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004167 if (L->getHeader() == I->getParent())
4168 return PN;
4169 else
4170 // We don't currently keep track of the control flow needed to evaluate
4171 // PHIs, so we cannot handle PHIs inside of loops.
4172 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004173 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004174
4175 // If we won't be able to constant fold this expression even if the operands
4176 // are constants, return early.
4177 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004178
Chris Lattner3221ad02004-04-17 22:58:41 +00004179 // Otherwise, we can evaluate this instruction if all of its operands are
4180 // constant or derived from a PHI node themselves.
4181 PHINode *PHI = 0;
4182 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004183 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004184 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4185 if (P == 0) return 0; // Not evolving from PHI
4186 if (PHI == 0)
4187 PHI = P;
4188 else if (PHI != P)
4189 return 0; // Evolving from multiple different PHIs.
4190 }
4191
4192 // This is a expression evolving from a constant PHI!
4193 return PHI;
4194}
4195
4196/// EvaluateExpression - Given an expression that passes the
4197/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4198/// in the loop has the value PHIVal. If we can't fold this expression for some
4199/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004200static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4201 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004202 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004203 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004204 Instruction *I = cast<Instruction>(V);
4205
Dan Gohman9d4588f2010-06-22 13:15:46 +00004206 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004207
4208 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004209 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004210 if (Operands[i] == 0) return 0;
4211 }
4212
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004213 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004214 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004215 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004216 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004217 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004218}
4219
4220/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4221/// in the header of its containing loop, we know the loop executes a
4222/// constant number of times, and the PHI node is just a recurrence
4223/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004224Constant *
4225ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004226 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004227 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004228 std::map<PHINode*, Constant*>::iterator I =
4229 ConstantEvolutionLoopExitValue.find(PN);
4230 if (I != ConstantEvolutionLoopExitValue.end())
4231 return I->second;
4232
Dan Gohmane0567812010-04-08 23:03:40 +00004233 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004234 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4235
4236 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4237
4238 // Since the loop is canonicalized, the PHI node must have two entries. One
4239 // entry must be a constant (coming in from outside of the loop), and the
4240 // second must be derived from the same PHI.
4241 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4242 Constant *StartCST =
4243 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4244 if (StartCST == 0)
4245 return RetVal = 0; // Must be a constant.
4246
4247 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004248 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4249 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004250 return RetVal = 0; // Not derived from same PHI.
4251
4252 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004253 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004254 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004255
Dan Gohman46bdfb02009-02-24 18:55:53 +00004256 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004257 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004258 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4259 if (IterationNum == NumIterations)
4260 return RetVal = PHIVal; // Got exit value!
4261
4262 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004263 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004264 if (NextPHI == PHIVal)
4265 return RetVal = NextPHI; // Stopped evolving!
4266 if (NextPHI == 0)
4267 return 0; // Couldn't evaluate!
4268 PHIVal = NextPHI;
4269 }
4270}
4271
Dan Gohman07ad19b2009-07-27 16:09:48 +00004272/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004273/// constant number of times (the condition evolves only from constants),
4274/// try to evaluate a few iterations of the loop until we get the exit
4275/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004276/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004277const SCEV *
4278ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4279 Value *Cond,
4280 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004281 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004282 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004283
Dan Gohmanb92654d2010-06-19 14:17:24 +00004284 // If the loop is canonicalized, the PHI will have exactly two entries.
4285 // That's the only form we support here.
4286 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4287
4288 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004289 // second must be derived from the same PHI.
4290 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4291 Constant *StartCST =
4292 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004293 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004294
4295 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004296 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4297 !isa<Constant>(BEValue))
4298 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004299
4300 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4301 // the loop symbolically to determine when the condition gets a value of
4302 // "ExitWhen".
4303 unsigned IterationNum = 0;
4304 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4305 for (Constant *PHIVal = StartCST;
4306 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004307 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004308 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004309
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004310 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004311 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004312
Reid Spencere8019bb2007-03-01 07:25:48 +00004313 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004314 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004315 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004316 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004317
Chris Lattner3221ad02004-04-17 22:58:41 +00004318 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004319 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004320 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004321 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004322 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004323 }
4324
4325 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004326 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004327}
4328
Dan Gohmane7125f42009-09-03 15:00:26 +00004329/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004330/// at the specified scope in the program. The L value specifies a loop
4331/// nest to evaluate the expression at, where null is the top-level or a
4332/// specified loop is immediately inside of the loop.
4333///
4334/// This method can be used to compute the exit value for a variable defined
4335/// in a loop by querying what the value will hold in the parent loop.
4336///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004337/// In the case that a relevant loop exit value cannot be computed, the
4338/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004339const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004340 // Check to see if we've folded this expression at this loop before.
4341 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4342 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4343 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4344 if (!Pair.second)
4345 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004346
Dan Gohman42214892009-08-31 21:15:23 +00004347 // Otherwise compute it.
4348 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004349 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004350 return C;
4351}
4352
4353const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004354 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004355
Nick Lewycky3e630762008-02-20 06:48:22 +00004356 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004357 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004358 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004359 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004360 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004361 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4362 if (PHINode *PN = dyn_cast<PHINode>(I))
4363 if (PN->getParent() == LI->getHeader()) {
4364 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004365 // to see if the loop that contains it has a known backedge-taken
4366 // count. If so, we may be able to force computation of the exit
4367 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004368 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004369 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004370 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004371 // Okay, we know how many times the containing loop executes. If
4372 // this is a constant evolving PHI node, get the final value at
4373 // the specified iteration number.
4374 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004375 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004376 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004377 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004378 }
4379 }
4380
Reid Spencer09906f32006-12-04 21:33:23 +00004381 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004382 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004383 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004384 // result. This is particularly useful for computing loop exit values.
4385 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004386 SmallVector<Constant *, 4> Operands;
4387 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004388 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4389 Value *Op = I->getOperand(i);
4390 if (Constant *C = dyn_cast<Constant>(Op)) {
4391 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004392 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004393 }
Dan Gohman11046452010-06-29 23:43:06 +00004394
4395 // If any of the operands is non-constant and if they are
4396 // non-integer and non-pointer, don't even try to analyze them
4397 // with scev techniques.
4398 if (!isSCEVable(Op->getType()))
4399 return V;
4400
4401 const SCEV *OrigV = getSCEV(Op);
4402 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4403 MadeImprovement |= OrigV != OpV;
4404
4405 Constant *C = 0;
4406 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4407 C = SC->getValue();
4408 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4409 C = dyn_cast<Constant>(SU->getValue());
4410 if (!C) return V;
4411 if (C->getType() != Op->getType())
4412 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4413 Op->getType(),
4414 false),
4415 C, Op->getType());
4416 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004417 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004418
Dan Gohman11046452010-06-29 23:43:06 +00004419 // Check to see if getSCEVAtScope actually made an improvement.
4420 if (MadeImprovement) {
4421 Constant *C = 0;
4422 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4423 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4424 Operands[0], Operands[1], TD);
4425 else
4426 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4427 &Operands[0], Operands.size(), TD);
4428 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004429 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004430 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004431 }
4432 }
4433
4434 // This is some other type of SCEVUnknown, just return it.
4435 return V;
4436 }
4437
Dan Gohman622ed672009-05-04 22:02:23 +00004438 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004439 // Avoid performing the look-up in the common case where the specified
4440 // expression has no loop-variant portions.
4441 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004442 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004443 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004444 // Okay, at least one of these operands is loop variant but might be
4445 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004446 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4447 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004448 NewOps.push_back(OpAtScope);
4449
4450 for (++i; i != e; ++i) {
4451 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004452 NewOps.push_back(OpAtScope);
4453 }
4454 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004455 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004456 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004457 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004458 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004459 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004460 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004461 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004462 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004463 }
4464 }
4465 // If we got here, all operands are loop invariant.
4466 return Comm;
4467 }
4468
Dan Gohman622ed672009-05-04 22:02:23 +00004469 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004470 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4471 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004472 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4473 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004474 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004475 }
4476
4477 // If this is a loop recurrence for a loop that does not contain L, then we
4478 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004479 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004480 // First, attempt to evaluate each operand.
4481 // Avoid performing the look-up in the common case where the specified
4482 // expression has no loop-variant portions.
4483 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4484 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4485 if (OpAtScope == AddRec->getOperand(i))
4486 continue;
4487
4488 // Okay, at least one of these operands is loop variant but might be
4489 // foldable. Build a new instance of the folded commutative expression.
4490 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4491 AddRec->op_begin()+i);
4492 NewOps.push_back(OpAtScope);
4493 for (++i; i != e; ++i)
4494 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4495
4496 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4497 break;
4498 }
4499
4500 // If the scope is outside the addrec's loop, evaluate it by using the
4501 // loop exit value of the addrec.
4502 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004503 // To evaluate this recurrence, we need to know how many times the AddRec
4504 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004505 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004506 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004507
Eli Friedmanb42a6262008-08-04 23:49:06 +00004508 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004509 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004510 }
Dan Gohman11046452010-06-29 23:43:06 +00004511
Dan Gohmand594e6f2009-05-24 23:25:42 +00004512 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004513 }
4514
Dan Gohman622ed672009-05-04 22:02:23 +00004515 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004516 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004517 if (Op == Cast->getOperand())
4518 return Cast; // must be loop invariant
4519 return getZeroExtendExpr(Op, Cast->getType());
4520 }
4521
Dan Gohman622ed672009-05-04 22:02:23 +00004522 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004523 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004524 if (Op == Cast->getOperand())
4525 return Cast; // must be loop invariant
4526 return getSignExtendExpr(Op, Cast->getType());
4527 }
4528
Dan Gohman622ed672009-05-04 22:02:23 +00004529 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004530 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004531 if (Op == Cast->getOperand())
4532 return Cast; // must be loop invariant
4533 return getTruncateExpr(Op, Cast->getType());
4534 }
4535
Torok Edwinc23197a2009-07-14 16:55:14 +00004536 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004537 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004538}
4539
Dan Gohman66a7e852009-05-08 20:38:54 +00004540/// getSCEVAtScope - This is a convenience function which does
4541/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004542const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004543 return getSCEVAtScope(getSCEV(V), L);
4544}
4545
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004546/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4547/// following equation:
4548///
4549/// A * X = B (mod N)
4550///
4551/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4552/// A and B isn't important.
4553///
4554/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004555static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004556 ScalarEvolution &SE) {
4557 uint32_t BW = A.getBitWidth();
4558 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4559 assert(A != 0 && "A must be non-zero.");
4560
4561 // 1. D = gcd(A, N)
4562 //
4563 // The gcd of A and N may have only one prime factor: 2. The number of
4564 // trailing zeros in A is its multiplicity
4565 uint32_t Mult2 = A.countTrailingZeros();
4566 // D = 2^Mult2
4567
4568 // 2. Check if B is divisible by D.
4569 //
4570 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4571 // is not less than multiplicity of this prime factor for D.
4572 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004573 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004574
4575 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4576 // modulo (N / D).
4577 //
4578 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4579 // bit width during computations.
4580 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4581 APInt Mod(BW + 1, 0);
4582 Mod.set(BW - Mult2); // Mod = N / D
4583 APInt I = AD.multiplicativeInverse(Mod);
4584
4585 // 4. Compute the minimum unsigned root of the equation:
4586 // I * (B / D) mod (N / D)
4587 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4588
4589 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4590 // bits.
4591 return SE.getConstant(Result.trunc(BW));
4592}
Chris Lattner53e677a2004-04-02 20:23:17 +00004593
4594/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4595/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4596/// might be the same) or two SCEVCouldNotCompute objects.
4597///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004598static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004599SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004600 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004601 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4602 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4603 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004604
Chris Lattner53e677a2004-04-02 20:23:17 +00004605 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004606 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004607 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004608 return std::make_pair(CNC, CNC);
4609 }
4610
Reid Spencere8019bb2007-03-01 07:25:48 +00004611 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004612 const APInt &L = LC->getValue()->getValue();
4613 const APInt &M = MC->getValue()->getValue();
4614 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004615 APInt Two(BitWidth, 2);
4616 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004617
Dan Gohman64a845e2009-06-24 04:48:43 +00004618 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004619 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004620 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004621 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4622 // The B coefficient is M-N/2
4623 APInt B(M);
4624 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004625
Reid Spencere8019bb2007-03-01 07:25:48 +00004626 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004627 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004628
Reid Spencere8019bb2007-03-01 07:25:48 +00004629 // Compute the B^2-4ac term.
4630 APInt SqrtTerm(B);
4631 SqrtTerm *= B;
4632 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004633
Reid Spencere8019bb2007-03-01 07:25:48 +00004634 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4635 // integer value or else APInt::sqrt() will assert.
4636 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004637
Dan Gohman64a845e2009-06-24 04:48:43 +00004638 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004639 // The divisions must be performed as signed divisions.
4640 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004641 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004642 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004643 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004644 return std::make_pair(CNC, CNC);
4645 }
4646
Owen Andersone922c022009-07-22 00:24:57 +00004647 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004648
4649 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004650 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004651 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004652 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004653
Dan Gohman64a845e2009-06-24 04:48:43 +00004654 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004655 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004656 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004657}
4658
4659/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004660/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004661ScalarEvolution::BackedgeTakenInfo
4662ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004663 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004664 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004665 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004666 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004667 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004668 }
4669
Dan Gohman35738ac2009-05-04 22:30:44 +00004670 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004671 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004672 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004673
4674 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004675 // If this is an affine expression, the execution count of this branch is
4676 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004677 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004678 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004679 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004680 // equivalent to:
4681 //
4682 // Step*N = -Start (mod 2^BW)
4683 //
4684 // where BW is the common bit width of Start and Step.
4685
Chris Lattner53e677a2004-04-02 20:23:17 +00004686 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004687 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4688 L->getParentLoop());
4689 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4690 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004691
Dan Gohman622ed672009-05-04 22:02:23 +00004692 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004693 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004694
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004695 // First, handle unitary steps.
4696 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004697 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004698 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4699 return Start; // N = Start (as unsigned)
4700
4701 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004702 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004703 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004704 -StartC->getValue()->getValue(),
4705 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004706 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004707 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004708 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4709 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004710 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004711 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004712 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4713 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004714 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004715#if 0
David Greene25e0e872009-12-23 22:18:14 +00004716 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004717 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004718#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004719 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004720 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004721 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004722 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004723 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004724 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004725
Chris Lattner53e677a2004-04-02 20:23:17 +00004726 // We can only use this value if the chrec ends up with an exact zero
4727 // value at this index. When solving for "X*X != 5", for example, we
4728 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004729 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004730 if (Val->isZero())
4731 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004732 }
4733 }
4734 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004735
Dan Gohman1c343752009-06-27 21:21:31 +00004736 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004737}
4738
4739/// HowFarToNonZero - Return the number of times a backedge checking the
4740/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004741/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004742ScalarEvolution::BackedgeTakenInfo
4743ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004744 // Loops that look like: while (X == 0) are very strange indeed. We don't
4745 // handle them yet except for the trivial case. This could be expanded in the
4746 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004747
Chris Lattner53e677a2004-04-02 20:23:17 +00004748 // If the value is a constant, check to see if it is known to be non-zero
4749 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004750 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004751 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004752 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004753 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004754 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004755
Chris Lattner53e677a2004-04-02 20:23:17 +00004756 // We could implement others, but I really doubt anyone writes loops like
4757 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004758 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004759}
4760
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004761/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4762/// (which may not be an immediate predecessor) which has exactly one
4763/// successor from which BB is reachable, or null if no such block is
4764/// found.
4765///
Dan Gohman005752b2010-04-15 16:19:08 +00004766std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004767ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004768 // If the block has a unique predecessor, then there is no path from the
4769 // predecessor to the block that does not go through the direct edge
4770 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004771 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004772 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004773
4774 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004775 // If the header has a unique predecessor outside the loop, it must be
4776 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004777 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004778 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004779
Dan Gohman005752b2010-04-15 16:19:08 +00004780 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004781}
4782
Dan Gohman763bad12009-06-20 00:35:32 +00004783/// HasSameValue - SCEV structural equivalence is usually sufficient for
4784/// testing whether two expressions are equal, however for the purposes of
4785/// looking for a condition guarding a loop, it can be useful to be a little
4786/// more general, since a front-end may have replicated the controlling
4787/// expression.
4788///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004789static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004790 // Quick check to see if they are the same SCEV.
4791 if (A == B) return true;
4792
4793 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4794 // two different instructions with the same value. Check for this case.
4795 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4796 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4797 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4798 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004799 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004800 return true;
4801
4802 // Otherwise assume they may have a different value.
4803 return false;
4804}
4805
Dan Gohmane9796502010-04-24 01:28:42 +00004806/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4807/// predicate Pred. Return true iff any changes were made.
4808///
4809bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4810 const SCEV *&LHS, const SCEV *&RHS) {
4811 bool Changed = false;
4812
4813 // Canonicalize a constant to the right side.
4814 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4815 // Check for both operands constant.
4816 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4817 if (ConstantExpr::getICmp(Pred,
4818 LHSC->getValue(),
4819 RHSC->getValue())->isNullValue())
4820 goto trivially_false;
4821 else
4822 goto trivially_true;
4823 }
4824 // Otherwise swap the operands to put the constant on the right.
4825 std::swap(LHS, RHS);
4826 Pred = ICmpInst::getSwappedPredicate(Pred);
4827 Changed = true;
4828 }
4829
4830 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004831 // addrec's loop, put the addrec on the left. Also make a dominance check,
4832 // as both operands could be addrecs loop-invariant in each other's loop.
4833 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4834 const Loop *L = AR->getLoop();
4835 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004836 std::swap(LHS, RHS);
4837 Pred = ICmpInst::getSwappedPredicate(Pred);
4838 Changed = true;
4839 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004840 }
Dan Gohmane9796502010-04-24 01:28:42 +00004841
4842 // If there's a constant operand, canonicalize comparisons with boundary
4843 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4844 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4845 const APInt &RA = RC->getValue()->getValue();
4846 switch (Pred) {
4847 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4848 case ICmpInst::ICMP_EQ:
4849 case ICmpInst::ICMP_NE:
4850 break;
4851 case ICmpInst::ICMP_UGE:
4852 if ((RA - 1).isMinValue()) {
4853 Pred = ICmpInst::ICMP_NE;
4854 RHS = getConstant(RA - 1);
4855 Changed = true;
4856 break;
4857 }
4858 if (RA.isMaxValue()) {
4859 Pred = ICmpInst::ICMP_EQ;
4860 Changed = true;
4861 break;
4862 }
4863 if (RA.isMinValue()) goto trivially_true;
4864
4865 Pred = ICmpInst::ICMP_UGT;
4866 RHS = getConstant(RA - 1);
4867 Changed = true;
4868 break;
4869 case ICmpInst::ICMP_ULE:
4870 if ((RA + 1).isMaxValue()) {
4871 Pred = ICmpInst::ICMP_NE;
4872 RHS = getConstant(RA + 1);
4873 Changed = true;
4874 break;
4875 }
4876 if (RA.isMinValue()) {
4877 Pred = ICmpInst::ICMP_EQ;
4878 Changed = true;
4879 break;
4880 }
4881 if (RA.isMaxValue()) goto trivially_true;
4882
4883 Pred = ICmpInst::ICMP_ULT;
4884 RHS = getConstant(RA + 1);
4885 Changed = true;
4886 break;
4887 case ICmpInst::ICMP_SGE:
4888 if ((RA - 1).isMinSignedValue()) {
4889 Pred = ICmpInst::ICMP_NE;
4890 RHS = getConstant(RA - 1);
4891 Changed = true;
4892 break;
4893 }
4894 if (RA.isMaxSignedValue()) {
4895 Pred = ICmpInst::ICMP_EQ;
4896 Changed = true;
4897 break;
4898 }
4899 if (RA.isMinSignedValue()) goto trivially_true;
4900
4901 Pred = ICmpInst::ICMP_SGT;
4902 RHS = getConstant(RA - 1);
4903 Changed = true;
4904 break;
4905 case ICmpInst::ICMP_SLE:
4906 if ((RA + 1).isMaxSignedValue()) {
4907 Pred = ICmpInst::ICMP_NE;
4908 RHS = getConstant(RA + 1);
4909 Changed = true;
4910 break;
4911 }
4912 if (RA.isMinSignedValue()) {
4913 Pred = ICmpInst::ICMP_EQ;
4914 Changed = true;
4915 break;
4916 }
4917 if (RA.isMaxSignedValue()) goto trivially_true;
4918
4919 Pred = ICmpInst::ICMP_SLT;
4920 RHS = getConstant(RA + 1);
4921 Changed = true;
4922 break;
4923 case ICmpInst::ICMP_UGT:
4924 if (RA.isMinValue()) {
4925 Pred = ICmpInst::ICMP_NE;
4926 Changed = true;
4927 break;
4928 }
4929 if ((RA + 1).isMaxValue()) {
4930 Pred = ICmpInst::ICMP_EQ;
4931 RHS = getConstant(RA + 1);
4932 Changed = true;
4933 break;
4934 }
4935 if (RA.isMaxValue()) goto trivially_false;
4936 break;
4937 case ICmpInst::ICMP_ULT:
4938 if (RA.isMaxValue()) {
4939 Pred = ICmpInst::ICMP_NE;
4940 Changed = true;
4941 break;
4942 }
4943 if ((RA - 1).isMinValue()) {
4944 Pred = ICmpInst::ICMP_EQ;
4945 RHS = getConstant(RA - 1);
4946 Changed = true;
4947 break;
4948 }
4949 if (RA.isMinValue()) goto trivially_false;
4950 break;
4951 case ICmpInst::ICMP_SGT:
4952 if (RA.isMinSignedValue()) {
4953 Pred = ICmpInst::ICMP_NE;
4954 Changed = true;
4955 break;
4956 }
4957 if ((RA + 1).isMaxSignedValue()) {
4958 Pred = ICmpInst::ICMP_EQ;
4959 RHS = getConstant(RA + 1);
4960 Changed = true;
4961 break;
4962 }
4963 if (RA.isMaxSignedValue()) goto trivially_false;
4964 break;
4965 case ICmpInst::ICMP_SLT:
4966 if (RA.isMaxSignedValue()) {
4967 Pred = ICmpInst::ICMP_NE;
4968 Changed = true;
4969 break;
4970 }
4971 if ((RA - 1).isMinSignedValue()) {
4972 Pred = ICmpInst::ICMP_EQ;
4973 RHS = getConstant(RA - 1);
4974 Changed = true;
4975 break;
4976 }
4977 if (RA.isMinSignedValue()) goto trivially_false;
4978 break;
4979 }
4980 }
4981
4982 // Check for obvious equality.
4983 if (HasSameValue(LHS, RHS)) {
4984 if (ICmpInst::isTrueWhenEqual(Pred))
4985 goto trivially_true;
4986 if (ICmpInst::isFalseWhenEqual(Pred))
4987 goto trivially_false;
4988 }
4989
Dan Gohman03557dc2010-05-03 16:35:17 +00004990 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4991 // adding or subtracting 1 from one of the operands.
4992 switch (Pred) {
4993 case ICmpInst::ICMP_SLE:
4994 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4995 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4996 /*HasNUW=*/false, /*HasNSW=*/true);
4997 Pred = ICmpInst::ICMP_SLT;
4998 Changed = true;
4999 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005000 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005001 /*HasNUW=*/false, /*HasNSW=*/true);
5002 Pred = ICmpInst::ICMP_SLT;
5003 Changed = true;
5004 }
5005 break;
5006 case ICmpInst::ICMP_SGE:
5007 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005008 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005009 /*HasNUW=*/false, /*HasNSW=*/true);
5010 Pred = ICmpInst::ICMP_SGT;
5011 Changed = true;
5012 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5013 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5014 /*HasNUW=*/false, /*HasNSW=*/true);
5015 Pred = ICmpInst::ICMP_SGT;
5016 Changed = true;
5017 }
5018 break;
5019 case ICmpInst::ICMP_ULE:
5020 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005021 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005022 /*HasNUW=*/true, /*HasNSW=*/false);
5023 Pred = ICmpInst::ICMP_ULT;
5024 Changed = true;
5025 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005026 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005027 /*HasNUW=*/true, /*HasNSW=*/false);
5028 Pred = ICmpInst::ICMP_ULT;
5029 Changed = true;
5030 }
5031 break;
5032 case ICmpInst::ICMP_UGE:
5033 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005034 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005035 /*HasNUW=*/true, /*HasNSW=*/false);
5036 Pred = ICmpInst::ICMP_UGT;
5037 Changed = true;
5038 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005039 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005040 /*HasNUW=*/true, /*HasNSW=*/false);
5041 Pred = ICmpInst::ICMP_UGT;
5042 Changed = true;
5043 }
5044 break;
5045 default:
5046 break;
5047 }
5048
Dan Gohmane9796502010-04-24 01:28:42 +00005049 // TODO: More simplifications are possible here.
5050
5051 return Changed;
5052
5053trivially_true:
5054 // Return 0 == 0.
5055 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5056 Pred = ICmpInst::ICMP_EQ;
5057 return true;
5058
5059trivially_false:
5060 // Return 0 != 0.
5061 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5062 Pred = ICmpInst::ICMP_NE;
5063 return true;
5064}
5065
Dan Gohman85b05a22009-07-13 21:35:55 +00005066bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5067 return getSignedRange(S).getSignedMax().isNegative();
5068}
5069
5070bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5071 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5072}
5073
5074bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5075 return !getSignedRange(S).getSignedMin().isNegative();
5076}
5077
5078bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5079 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5080}
5081
5082bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5083 return isKnownNegative(S) || isKnownPositive(S);
5084}
5085
5086bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5087 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005088 // Canonicalize the inputs first.
5089 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5090
Dan Gohman53c66ea2010-04-11 22:16:48 +00005091 // If LHS or RHS is an addrec, check to see if the condition is true in
5092 // every iteration of the loop.
5093 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5094 if (isLoopEntryGuardedByCond(
5095 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5096 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005097 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005098 return true;
5099 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5100 if (isLoopEntryGuardedByCond(
5101 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5102 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005103 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005104 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005105
Dan Gohman53c66ea2010-04-11 22:16:48 +00005106 // Otherwise see what can be done with known constant ranges.
5107 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5108}
5109
5110bool
5111ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5112 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005113 if (HasSameValue(LHS, RHS))
5114 return ICmpInst::isTrueWhenEqual(Pred);
5115
Dan Gohman53c66ea2010-04-11 22:16:48 +00005116 // This code is split out from isKnownPredicate because it is called from
5117 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005118 switch (Pred) {
5119 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005120 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005121 break;
5122 case ICmpInst::ICMP_SGT:
5123 Pred = ICmpInst::ICMP_SLT;
5124 std::swap(LHS, RHS);
5125 case ICmpInst::ICMP_SLT: {
5126 ConstantRange LHSRange = getSignedRange(LHS);
5127 ConstantRange RHSRange = getSignedRange(RHS);
5128 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5129 return true;
5130 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5131 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005132 break;
5133 }
5134 case ICmpInst::ICMP_SGE:
5135 Pred = ICmpInst::ICMP_SLE;
5136 std::swap(LHS, RHS);
5137 case ICmpInst::ICMP_SLE: {
5138 ConstantRange LHSRange = getSignedRange(LHS);
5139 ConstantRange RHSRange = getSignedRange(RHS);
5140 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5141 return true;
5142 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5143 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005144 break;
5145 }
5146 case ICmpInst::ICMP_UGT:
5147 Pred = ICmpInst::ICMP_ULT;
5148 std::swap(LHS, RHS);
5149 case ICmpInst::ICMP_ULT: {
5150 ConstantRange LHSRange = getUnsignedRange(LHS);
5151 ConstantRange RHSRange = getUnsignedRange(RHS);
5152 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5153 return true;
5154 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5155 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005156 break;
5157 }
5158 case ICmpInst::ICMP_UGE:
5159 Pred = ICmpInst::ICMP_ULE;
5160 std::swap(LHS, RHS);
5161 case ICmpInst::ICMP_ULE: {
5162 ConstantRange LHSRange = getUnsignedRange(LHS);
5163 ConstantRange RHSRange = getUnsignedRange(RHS);
5164 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5165 return true;
5166 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5167 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005168 break;
5169 }
5170 case ICmpInst::ICMP_NE: {
5171 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5172 return true;
5173 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5174 return true;
5175
5176 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5177 if (isKnownNonZero(Diff))
5178 return true;
5179 break;
5180 }
5181 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005182 // The check at the top of the function catches the case where
5183 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005184 break;
5185 }
5186 return false;
5187}
5188
5189/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5190/// protected by a conditional between LHS and RHS. This is used to
5191/// to eliminate casts.
5192bool
5193ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5194 ICmpInst::Predicate Pred,
5195 const SCEV *LHS, const SCEV *RHS) {
5196 // Interpret a null as meaning no loop, where there is obviously no guard
5197 // (interprocedural conditions notwithstanding).
5198 if (!L) return true;
5199
5200 BasicBlock *Latch = L->getLoopLatch();
5201 if (!Latch)
5202 return false;
5203
5204 BranchInst *LoopContinuePredicate =
5205 dyn_cast<BranchInst>(Latch->getTerminator());
5206 if (!LoopContinuePredicate ||
5207 LoopContinuePredicate->isUnconditional())
5208 return false;
5209
Dan Gohmanaf08a362010-08-10 23:46:30 +00005210 return isImpliedCond(Pred, LHS, RHS,
5211 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005212 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005213}
5214
Dan Gohman3948d0b2010-04-11 19:27:13 +00005215/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005216/// by a conditional between LHS and RHS. This is used to help avoid max
5217/// expressions in loop trip counts, and to eliminate casts.
5218bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005219ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5220 ICmpInst::Predicate Pred,
5221 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005222 // Interpret a null as meaning no loop, where there is obviously no guard
5223 // (interprocedural conditions notwithstanding).
5224 if (!L) return false;
5225
Dan Gohman859b4822009-05-18 15:36:09 +00005226 // Starting at the loop predecessor, climb up the predecessor chain, as long
5227 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005228 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005229 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005230 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005231 Pair.first;
5232 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005233
5234 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005235 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005236 if (!LoopEntryPredicate ||
5237 LoopEntryPredicate->isUnconditional())
5238 continue;
5239
Dan Gohmanaf08a362010-08-10 23:46:30 +00005240 if (isImpliedCond(Pred, LHS, RHS,
5241 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005242 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005243 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005244 }
5245
Dan Gohman38372182008-08-12 20:17:31 +00005246 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005247}
5248
Dan Gohman0f4b2852009-07-21 23:03:19 +00005249/// isImpliedCond - Test whether the condition described by Pred, LHS,
5250/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005251bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005252 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005253 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005254 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005255 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005257 if (BO->getOpcode() == Instruction::And) {
5258 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005259 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5260 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005261 } else if (BO->getOpcode() == Instruction::Or) {
5262 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005263 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5264 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005265 }
5266 }
5267
Dan Gohmanaf08a362010-08-10 23:46:30 +00005268 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005269 if (!ICI) return false;
5270
Dan Gohman85b05a22009-07-13 21:35:55 +00005271 // Bail if the ICmp's operands' types are wider than the needed type
5272 // before attempting to call getSCEV on them. This avoids infinite
5273 // recursion, since the analysis of widening casts can require loop
5274 // exit condition information for overflow checking, which would
5275 // lead back here.
5276 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005277 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005278 return false;
5279
Dan Gohman0f4b2852009-07-21 23:03:19 +00005280 // Now that we found a conditional branch that dominates the loop, check to
5281 // see if it is the comparison we are looking for.
5282 ICmpInst::Predicate FoundPred;
5283 if (Inverse)
5284 FoundPred = ICI->getInversePredicate();
5285 else
5286 FoundPred = ICI->getPredicate();
5287
5288 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5289 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005290
5291 // Balance the types. The case where FoundLHS' type is wider than
5292 // LHS' type is checked for above.
5293 if (getTypeSizeInBits(LHS->getType()) >
5294 getTypeSizeInBits(FoundLHS->getType())) {
5295 if (CmpInst::isSigned(Pred)) {
5296 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5297 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5298 } else {
5299 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5300 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5301 }
5302 }
5303
Dan Gohman0f4b2852009-07-21 23:03:19 +00005304 // Canonicalize the query to match the way instcombine will have
5305 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005306 if (SimplifyICmpOperands(Pred, LHS, RHS))
5307 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005308 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005309 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5310 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005311 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005312
5313 // Check to see if we can make the LHS or RHS match.
5314 if (LHS == FoundRHS || RHS == FoundLHS) {
5315 if (isa<SCEVConstant>(RHS)) {
5316 std::swap(FoundLHS, FoundRHS);
5317 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5318 } else {
5319 std::swap(LHS, RHS);
5320 Pred = ICmpInst::getSwappedPredicate(Pred);
5321 }
5322 }
5323
5324 // Check whether the found predicate is the same as the desired predicate.
5325 if (FoundPred == Pred)
5326 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5327
5328 // Check whether swapping the found predicate makes it the same as the
5329 // desired predicate.
5330 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5331 if (isa<SCEVConstant>(RHS))
5332 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5333 else
5334 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5335 RHS, LHS, FoundLHS, FoundRHS);
5336 }
5337
5338 // Check whether the actual condition is beyond sufficient.
5339 if (FoundPred == ICmpInst::ICMP_EQ)
5340 if (ICmpInst::isTrueWhenEqual(Pred))
5341 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5342 return true;
5343 if (Pred == ICmpInst::ICMP_NE)
5344 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5345 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5346 return true;
5347
5348 // Otherwise assume the worst.
5349 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005350}
5351
Dan Gohman0f4b2852009-07-21 23:03:19 +00005352/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005353/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005354/// and FoundRHS is true.
5355bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5356 const SCEV *LHS, const SCEV *RHS,
5357 const SCEV *FoundLHS,
5358 const SCEV *FoundRHS) {
5359 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5360 FoundLHS, FoundRHS) ||
5361 // ~x < ~y --> x > y
5362 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5363 getNotSCEV(FoundRHS),
5364 getNotSCEV(FoundLHS));
5365}
5366
5367/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005368/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005369/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005370bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005371ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5372 const SCEV *LHS, const SCEV *RHS,
5373 const SCEV *FoundLHS,
5374 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005375 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005376 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5377 case ICmpInst::ICMP_EQ:
5378 case ICmpInst::ICMP_NE:
5379 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5380 return true;
5381 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005382 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005383 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005384 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5385 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005386 return true;
5387 break;
5388 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005389 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005390 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5391 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005392 return true;
5393 break;
5394 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005395 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005396 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5397 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005398 return true;
5399 break;
5400 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005401 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005402 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5403 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005404 return true;
5405 break;
5406 }
5407
5408 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005409}
5410
Dan Gohman51f53b72009-06-21 23:46:38 +00005411/// getBECount - Subtract the end and start values and divide by the step,
5412/// rounding up, to get the number of times the backedge is executed. Return
5413/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005414const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005415 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005416 const SCEV *Step,
5417 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005418 assert(!isKnownNegative(Step) &&
5419 "This code doesn't handle negative strides yet!");
5420
Dan Gohman51f53b72009-06-21 23:46:38 +00005421 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005422 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005423 const SCEV *Diff = getMinusSCEV(End, Start);
5424 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005425
5426 // Add an adjustment to the difference between End and Start so that
5427 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005428 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005429
Dan Gohman1f96e672009-09-17 18:05:20 +00005430 if (!NoWrap) {
5431 // Check Add for unsigned overflow.
5432 // TODO: More sophisticated things could be done here.
5433 const Type *WideTy = IntegerType::get(getContext(),
5434 getTypeSizeInBits(Ty) + 1);
5435 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5436 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5437 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5438 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5439 return getCouldNotCompute();
5440 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005441
5442 return getUDivExpr(Add, Step);
5443}
5444
Chris Lattnerdb25de42005-08-15 23:33:51 +00005445/// HowManyLessThans - Return the number of times a backedge containing the
5446/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005447/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005448ScalarEvolution::BackedgeTakenInfo
5449ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5450 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005451 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005452 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005453
Dan Gohman35738ac2009-05-04 22:30:44 +00005454 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005455 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005456 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005457
Dan Gohman1f96e672009-09-17 18:05:20 +00005458 // Check to see if we have a flag which makes analysis easy.
5459 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5460 AddRec->hasNoUnsignedWrap();
5461
Chris Lattnerdb25de42005-08-15 23:33:51 +00005462 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005463 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005464 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005465
Dan Gohman52fddd32010-01-26 04:40:18 +00005466 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005467 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005468 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005469 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005470 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005471 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005472 // value and past the maximum value for its type in a single step.
5473 // Note that it's not sufficient to check NoWrap here, because even
5474 // though the value after a wrap is undefined, it's not undefined
5475 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005476 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005477 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005478 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005479 if (isSigned) {
5480 APInt Max = APInt::getSignedMaxValue(BitWidth);
5481 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5482 .slt(getSignedRange(RHS).getSignedMax()))
5483 return getCouldNotCompute();
5484 } else {
5485 APInt Max = APInt::getMaxValue(BitWidth);
5486 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5487 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5488 return getCouldNotCompute();
5489 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005490 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005491 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005492 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005493
Dan Gohmana1af7572009-04-30 20:47:05 +00005494 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5495 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5496 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005497 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005498
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005499 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005500 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005501
Dan Gohmana1af7572009-04-30 20:47:05 +00005502 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005503 const SCEV *MinStart = getConstant(isSigned ?
5504 getSignedRange(Start).getSignedMin() :
5505 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005506
Dan Gohmana1af7572009-04-30 20:47:05 +00005507 // If we know that the condition is true in order to enter the loop,
5508 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005509 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5510 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005511 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005512 if (!isLoopEntryGuardedByCond(L,
5513 isSigned ? ICmpInst::ICMP_SLT :
5514 ICmpInst::ICMP_ULT,
5515 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005516 End = isSigned ? getSMaxExpr(RHS, Start)
5517 : getUMaxExpr(RHS, Start);
5518
5519 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005520 const SCEV *MaxEnd = getConstant(isSigned ?
5521 getSignedRange(End).getSignedMax() :
5522 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005523
Dan Gohman52fddd32010-01-26 04:40:18 +00005524 // If MaxEnd is within a step of the maximum integer value in its type,
5525 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005526 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005527 // compute the correct value.
5528 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005529 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005530 MaxEnd = isSigned ?
5531 getSMinExpr(MaxEnd,
5532 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5533 StepMinusOne)) :
5534 getUMinExpr(MaxEnd,
5535 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5536 StepMinusOne));
5537
Dan Gohmana1af7572009-04-30 20:47:05 +00005538 // Finally, we subtract these two values and divide, rounding up, to get
5539 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005540 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005541
5542 // The maximum backedge count is similar, except using the minimum start
5543 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005544 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005545
5546 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005547 }
5548
Dan Gohman1c343752009-06-27 21:21:31 +00005549 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005550}
5551
Chris Lattner53e677a2004-04-02 20:23:17 +00005552/// getNumIterationsInRange - Return the number of iterations of this loop that
5553/// produce values in the specified constant range. Another way of looking at
5554/// this is that it returns the first iteration number where the value is not in
5555/// the condition, thus computing the exit count. If the iteration count can't
5556/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005557const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005558 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005559 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005560 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005561
5562 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005563 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005564 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005565 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005566 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005567 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005568 if (const SCEVAddRecExpr *ShiftedAddRec =
5569 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005570 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005571 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005572 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005573 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005574 }
5575
5576 // The only time we can solve this is when we have all constant indices.
5577 // Otherwise, we cannot determine the overflow conditions.
5578 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5579 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005580 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005581
5582
5583 // Okay at this point we know that all elements of the chrec are constants and
5584 // that the start element is zero.
5585
5586 // First check to see if the range contains zero. If not, the first
5587 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005588 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005589 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005590 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005591
Chris Lattner53e677a2004-04-02 20:23:17 +00005592 if (isAffine()) {
5593 // If this is an affine expression then we have this situation:
5594 // Solve {0,+,A} in Range === Ax in Range
5595
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005596 // We know that zero is in the range. If A is positive then we know that
5597 // the upper value of the range must be the first possible exit value.
5598 // If A is negative then the lower of the range is the last possible loop
5599 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005600 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005601 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5602 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005603
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005604 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005605 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005606 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005607
5608 // Evaluate at the exit value. If we really did fall out of the valid
5609 // range, then we computed our trip count, otherwise wrap around or other
5610 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005611 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005612 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005613 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005614
5615 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005616 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005617 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005618 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005619 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005620 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005621 } else if (isQuadratic()) {
5622 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5623 // quadratic equation to solve it. To do this, we must frame our problem in
5624 // terms of figuring out when zero is crossed, instead of when
5625 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005626 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005627 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005628 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005629
5630 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005631 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005632 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005633 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5634 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005635 if (R1) {
5636 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005637 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005638 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005639 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005640 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005641 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005642
Chris Lattner53e677a2004-04-02 20:23:17 +00005643 // Make sure the root is not off by one. The returned iteration should
5644 // not be in the range, but the previous one should be. When solving
5645 // for "X*X < 5", for example, we should not return a root of 2.
5646 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005647 R1->getValue(),
5648 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005649 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005650 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005651 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005652 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005653
Dan Gohman246b2562007-10-22 18:31:58 +00005654 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005655 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005656 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005657 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005658 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005659
Chris Lattner53e677a2004-04-02 20:23:17 +00005660 // If R1 was not in the range, then it is a good return value. Make
5661 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005662 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005663 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005664 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005665 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005666 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005667 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005668 }
5669 }
5670 }
5671
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005672 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005673}
5674
5675
5676
5677//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005678// SCEVCallbackVH Class Implementation
5679//===----------------------------------------------------------------------===//
5680
Dan Gohman1959b752009-05-19 19:22:47 +00005681void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005682 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005683 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5684 SE->ConstantEvolutionLoopExitValue.erase(PN);
5685 SE->Scalars.erase(getValPtr());
5686 // this now dangles!
5687}
5688
Dan Gohman81f91212010-07-28 01:09:07 +00005689void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005690 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005691
Dan Gohman35738ac2009-05-04 22:30:44 +00005692 // Forget all the expressions associated with users of the old value,
5693 // so that future queries will recompute the expressions using the new
5694 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005695 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005696 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005697 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005698 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5699 UI != UE; ++UI)
5700 Worklist.push_back(*UI);
5701 while (!Worklist.empty()) {
5702 User *U = Worklist.pop_back_val();
5703 // Deleting the Old value will cause this to dangle. Postpone
5704 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005705 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005706 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005707 if (!Visited.insert(U))
5708 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005709 if (PHINode *PN = dyn_cast<PHINode>(U))
5710 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005711 SE->Scalars.erase(U);
5712 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5713 UI != UE; ++UI)
5714 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005715 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005716 // Delete the Old value.
5717 if (PHINode *PN = dyn_cast<PHINode>(Old))
5718 SE->ConstantEvolutionLoopExitValue.erase(PN);
5719 SE->Scalars.erase(Old);
5720 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005721}
5722
Dan Gohman1959b752009-05-19 19:22:47 +00005723ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005724 : CallbackVH(V), SE(se) {}
5725
5726//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005727// ScalarEvolution Class Implementation
5728//===----------------------------------------------------------------------===//
5729
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005730ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005731 : FunctionPass(ID), FirstUnknown(0) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005732}
5733
Chris Lattner53e677a2004-04-02 20:23:17 +00005734bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005735 this->F = &F;
5736 LI = &getAnalysis<LoopInfo>();
5737 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005738 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005739 return false;
5740}
5741
5742void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005743 // Iterate through all the SCEVUnknown instances and call their
5744 // destructors, so that they release their references to their values.
5745 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5746 U->~SCEVUnknown();
5747 FirstUnknown = 0;
5748
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005749 Scalars.clear();
5750 BackedgeTakenCounts.clear();
5751 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005752 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005753 UniqueSCEVs.clear();
5754 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005755}
5756
5757void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5758 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005759 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005760 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005761}
5762
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005763bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005764 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005765}
5766
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005767static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005768 const Loop *L) {
5769 // Print all inner loops first
5770 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5771 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005772
Dan Gohman30733292010-01-09 18:17:45 +00005773 OS << "Loop ";
5774 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5775 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005776
Dan Gohman5d984912009-12-18 01:14:11 +00005777 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005778 L->getExitBlocks(ExitBlocks);
5779 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005780 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005781
Dan Gohman46bdfb02009-02-24 18:55:53 +00005782 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5783 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005784 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005785 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005786 }
5787
Dan Gohman30733292010-01-09 18:17:45 +00005788 OS << "\n"
5789 "Loop ";
5790 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5791 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005792
5793 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5794 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5795 } else {
5796 OS << "Unpredictable max backedge-taken count. ";
5797 }
5798
5799 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005800}
5801
Dan Gohman5d984912009-12-18 01:14:11 +00005802void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005803 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005804 // out SCEV values of all instructions that are interesting. Doing
5805 // this potentially causes it to create new SCEV objects though,
5806 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005807 // observable from outside the class though, so casting away the
5808 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005809 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005810
Dan Gohman30733292010-01-09 18:17:45 +00005811 OS << "Classifying expressions for: ";
5812 WriteAsOperand(OS, F, /*PrintType=*/false);
5813 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005814 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005815 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005816 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005817 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005818 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005819 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005820
Dan Gohman0c689c52009-06-19 17:49:54 +00005821 const Loop *L = LI->getLoopFor((*I).getParent());
5822
Dan Gohman0bba49c2009-07-07 17:06:11 +00005823 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005824 if (AtUse != SV) {
5825 OS << " --> ";
5826 AtUse->print(OS);
5827 }
5828
5829 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005830 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005831 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005832 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005833 OS << "<<Unknown>>";
5834 } else {
5835 OS << *ExitValue;
5836 }
5837 }
5838
Chris Lattner53e677a2004-04-02 20:23:17 +00005839 OS << "\n";
5840 }
5841
Dan Gohman30733292010-01-09 18:17:45 +00005842 OS << "Determining loop execution counts for: ";
5843 WriteAsOperand(OS, F, /*PrintType=*/false);
5844 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005845 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5846 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005847}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005848