blob: 1d6f21d3e380ea2e5b113d4efafcb414c64b9887 [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
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
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 Gohmanc93b4cf2010-03-18 16:16:38 +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 Gohman95531882010-03-18 18:49:47 +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 Gohmanc93b4cf2010-03-18 16:16:38 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202 unsigned SCEVTy, const SCEV *op, const Type *ty)
203 : 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 Gohmanc93b4cf2010-03-18 16:16:38 +0000213SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214 const SCEV *op, const Type *ty)
215 : 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 Gohmanc93b4cf2010-03-18 16:16:38 +0000225SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226 const SCEV *op, const Type *ty)
227 : 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 Gohmanc93b4cf2010-03-18 16:16:38 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238 const SCEV *op, const Type *ty)
239 : 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;
254 if (next(I) != E)
255 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
306 // This recurrence is variant w.r.t. QueryLoop if any of its operands
307 // are variant.
308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
309 if (!getOperand(i)->isLoopInvariant(QueryLoop))
310 return false;
311
312 // Otherwise it's loop-invariant.
313 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000314}
315
Dan Gohman39125d82010-02-13 00:19:39 +0000316bool
317SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
318 return DT->dominates(L->getHeader(), BB) &&
319 SCEVNAryExpr::dominates(BB, DT);
320}
321
322bool
323SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
324 // This uses a "dominates" query instead of "properly dominates" query because
325 // the instruction which produces the addrec's value is a PHI, and a PHI
326 // effectively properly dominates its entire containing block.
327 return DT->dominates(L->getHeader(), BB) &&
328 SCEVNAryExpr::properlyDominates(BB, DT);
329}
330
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000331void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000333 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000335 OS << "}<";
336 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
337 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338}
Chris Lattner53e677a2004-04-02 20:23:17 +0000339
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000340bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
341 // All non-instruction values are loop invariant. All instructions are loop
342 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000343 // Instructions are never considered invariant in the function body
344 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000346 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000347 return true;
348}
Chris Lattner53e677a2004-04-02 20:23:17 +0000349
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000350bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
351 if (Instruction *I = dyn_cast<Instruction>(getValue()))
352 return DT->dominates(I->getParent(), BB);
353 return true;
354}
355
Dan Gohman6e70e312009-09-27 15:26:03 +0000356bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
357 if (Instruction *I = dyn_cast<Instruction>(getValue()))
358 return DT->properlyDominates(I->getParent(), BB);
359 return true;
360}
361
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000362const Type *SCEVUnknown::getType() const {
363 return V->getType();
364}
Chris Lattner53e677a2004-04-02 20:23:17 +0000365
Dan Gohman0f5efe52010-01-28 02:15:55 +0000366bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
367 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
368 if (VCE->getOpcode() == Instruction::PtrToInt)
369 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000370 if (CE->getOpcode() == Instruction::GetElementPtr &&
371 CE->getOperand(0)->isNullValue() &&
372 CE->getNumOperands() == 2)
373 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
374 if (CI->isOne()) {
375 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
376 ->getElementType();
377 return true;
378 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000379
380 return false;
381}
382
383bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
384 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
385 if (VCE->getOpcode() == Instruction::PtrToInt)
386 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000387 if (CE->getOpcode() == Instruction::GetElementPtr &&
388 CE->getOperand(0)->isNullValue()) {
389 const Type *Ty =
390 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
391 if (const StructType *STy = dyn_cast<StructType>(Ty))
392 if (!STy->isPacked() &&
393 CE->getNumOperands() == 3 &&
394 CE->getOperand(1)->isNullValue()) {
395 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
396 if (CI->isOne() &&
397 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000398 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000399 AllocTy = STy->getElementType(1);
400 return true;
401 }
402 }
403 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000404
405 return false;
406}
407
Dan Gohman4f8eea82010-02-01 18:27:38 +0000408bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
409 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
410 if (VCE->getOpcode() == Instruction::PtrToInt)
411 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
412 if (CE->getOpcode() == Instruction::GetElementPtr &&
413 CE->getNumOperands() == 3 &&
414 CE->getOperand(0)->isNullValue() &&
415 CE->getOperand(1)->isNullValue()) {
416 const Type *Ty =
417 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
418 // Ignore vector types here so that ScalarEvolutionExpander doesn't
419 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000420 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000421 CTy = Ty;
422 FieldNo = CE->getOperand(2);
423 return true;
424 }
425 }
426
427 return false;
428}
429
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000430void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000431 const Type *AllocTy;
432 if (isSizeOf(AllocTy)) {
433 OS << "sizeof(" << *AllocTy << ")";
434 return;
435 }
436 if (isAlignOf(AllocTy)) {
437 OS << "alignof(" << *AllocTy << ")";
438 return;
439 }
440
Dan Gohman4f8eea82010-02-01 18:27:38 +0000441 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000442 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000443 if (isOffsetOf(CTy, FieldNo)) {
444 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000445 WriteAsOperand(OS, FieldNo, false);
446 OS << ")";
447 return;
448 }
449
450 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000451 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000452}
453
Chris Lattner8d741b82004-06-20 06:23:15 +0000454//===----------------------------------------------------------------------===//
455// SCEV Utilities
456//===----------------------------------------------------------------------===//
457
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000458static bool CompareTypes(const Type *A, const Type *B) {
459 if (A->getTypeID() != B->getTypeID())
460 return A->getTypeID() < B->getTypeID();
461 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
462 const IntegerType *BI = cast<IntegerType>(B);
463 return AI->getBitWidth() < BI->getBitWidth();
464 }
465 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
466 const PointerType *BI = cast<PointerType>(B);
467 return CompareTypes(AI->getElementType(), BI->getElementType());
468 }
469 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
470 const ArrayType *BI = cast<ArrayType>(B);
471 if (AI->getNumElements() != BI->getNumElements())
472 return AI->getNumElements() < BI->getNumElements();
473 return CompareTypes(AI->getElementType(), BI->getElementType());
474 }
475 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
476 const VectorType *BI = cast<VectorType>(B);
477 if (AI->getNumElements() != BI->getNumElements())
478 return AI->getNumElements() < BI->getNumElements();
479 return CompareTypes(AI->getElementType(), BI->getElementType());
480 }
481 if (const StructType *AI = dyn_cast<StructType>(A)) {
482 const StructType *BI = cast<StructType>(B);
483 if (AI->getNumElements() != BI->getNumElements())
484 return AI->getNumElements() < BI->getNumElements();
485 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
486 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
487 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
488 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
489 }
490 return false;
491}
492
Chris Lattner8d741b82004-06-20 06:23:15 +0000493namespace {
494 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
495 /// than the complexity of the RHS. This comparator is used to canonicalize
496 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000497 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000498 LoopInfo *LI;
499 public:
500 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
501
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000502 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000503 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
504 if (LHS == RHS)
505 return false;
506
Dan Gohman72861302009-05-07 14:39:04 +0000507 // Primarily, sort the SCEVs by their getSCEVType().
508 if (LHS->getSCEVType() != RHS->getSCEVType())
509 return LHS->getSCEVType() < RHS->getSCEVType();
510
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000511 // Then, pick an arbitrary sort. Use the profiling data for speed.
512 const FoldingSetNodeIDRef &L = LHS->getProfile();
513 const FoldingSetNodeIDRef &R = RHS->getProfile();
514 size_t LSize = L.getSize();
515 size_t RSize = R.getSize();
516 if (LSize != RSize)
517 return LSize < RSize;
518 return memcmp(L.getData(), R.getData(),
519 LSize * sizeof(*L.getData())) < 0;
Chris Lattner8d741b82004-06-20 06:23:15 +0000520 }
521 };
522}
523
524/// GroupByComplexity - Given a list of SCEV objects, order them by their
525/// complexity, and group objects of the same complexity together by value.
526/// When this routine is finished, we know that any duplicates in the vector are
527/// consecutive and that complexity is monotonically increasing.
528///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000529/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000530/// results from this routine. In other words, we don't want the results of
531/// this to depend on where the addresses of various SCEV objects happened to
532/// land in memory.
533///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000534static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000535 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000536 if (Ops.size() < 2) return; // Noop
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000537
538 SCEVComplexityCompare Comp(LI);
539
Chris Lattner8d741b82004-06-20 06:23:15 +0000540 if (Ops.size() == 2) {
541 // This is the common case, which also happens to be trivially simple.
542 // Special case it.
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000543 if (Comp(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000544 std::swap(Ops[0], Ops[1]);
545 return;
546 }
547
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000548 std::stable_sort(Ops.begin(), Ops.end(), Comp);
Chris Lattner8d741b82004-06-20 06:23:15 +0000549}
550
Chris Lattner53e677a2004-04-02 20:23:17 +0000551
Chris Lattner53e677a2004-04-02 20:23:17 +0000552
553//===----------------------------------------------------------------------===//
554// Simple SCEV method implementations
555//===----------------------------------------------------------------------===//
556
Eli Friedmanb42a6262008-08-04 23:49:06 +0000557/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000558/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000559static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000560 ScalarEvolution &SE,
561 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000562 // Handle the simplest case efficiently.
563 if (K == 1)
564 return SE.getTruncateOrZeroExtend(It, ResultTy);
565
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000566 // We are using the following formula for BC(It, K):
567 //
568 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
569 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000570 // Suppose, W is the bitwidth of the return value. We must be prepared for
571 // overflow. Hence, we must assure that the result of our computation is
572 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
573 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000574 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000575 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000576 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000577 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
578 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000579 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000581 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000582 // This formula is trivially equivalent to the previous formula. However,
583 // this formula can be implemented much more efficiently. The trick is that
584 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
585 // arithmetic. To do exact division in modular arithmetic, all we have
586 // to do is multiply by the inverse. Therefore, this step can be done at
587 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000588 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000589 // The next issue is how to safely do the division by 2^T. The way this
590 // is done is by doing the multiplication step at a width of at least W + T
591 // bits. This way, the bottom W+T bits of the product are accurate. Then,
592 // when we perform the division by 2^T (which is equivalent to a right shift
593 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
594 // truncated out after the division by 2^T.
595 //
596 // In comparison to just directly using the first formula, this technique
597 // is much more efficient; using the first formula requires W * K bits,
598 // but this formula less than W + K bits. Also, the first formula requires
599 // a division step, whereas this formula only requires multiplies and shifts.
600 //
601 // It doesn't matter whether the subtraction step is done in the calculation
602 // width or the input iteration count's width; if the subtraction overflows,
603 // the result must be zero anyway. We prefer here to do it in the width of
604 // the induction variable because it helps a lot for certain cases; CodeGen
605 // isn't smart enough to ignore the overflow, which leads to much less
606 // efficient code if the width of the subtraction is wider than the native
607 // register width.
608 //
609 // (It's possible to not widen at all by pulling out factors of 2 before
610 // the multiplication; for example, K=2 can be calculated as
611 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
612 // extra arithmetic, so it's not an obvious win, and it gets
613 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000614
Eli Friedmanb42a6262008-08-04 23:49:06 +0000615 // Protection from insane SCEVs; this bound is conservative,
616 // but it probably doesn't matter.
617 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000618 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000619
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000620 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000621
Eli Friedmanb42a6262008-08-04 23:49:06 +0000622 // Calculate K! / 2^T and T; we divide out the factors of two before
623 // multiplying for calculating K! / 2^T to avoid overflow.
624 // Other overflow doesn't matter because we only care about the bottom
625 // W bits of the result.
626 APInt OddFactorial(W, 1);
627 unsigned T = 1;
628 for (unsigned i = 3; i <= K; ++i) {
629 APInt Mult(W, i);
630 unsigned TwoFactors = Mult.countTrailingZeros();
631 T += TwoFactors;
632 Mult = Mult.lshr(TwoFactors);
633 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000634 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000635
Eli Friedmanb42a6262008-08-04 23:49:06 +0000636 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000637 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000638
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000639 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000640 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
641
642 // Calculate the multiplicative inverse of K! / 2^T;
643 // this multiplication factor will perform the exact division by
644 // K! / 2^T.
645 APInt Mod = APInt::getSignedMinValue(W+1);
646 APInt MultiplyFactor = OddFactorial.zext(W+1);
647 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
648 MultiplyFactor = MultiplyFactor.trunc(W);
649
650 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000651 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
652 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000653 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000654 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000655 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000656 Dividend = SE.getMulExpr(Dividend,
657 SE.getTruncateOrZeroExtend(S, CalculationTy));
658 }
659
660 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000661 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000662
663 // Truncate the result, and divide by K! / 2^T.
664
665 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
666 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000667}
668
Chris Lattner53e677a2004-04-02 20:23:17 +0000669/// evaluateAtIteration - Return the value of this chain of recurrences at
670/// the specified iteration number. We can evaluate this recurrence by
671/// multiplying each element in the chain by the binomial coefficient
672/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
673///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000675///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000676/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000677///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000678const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000679 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000680 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000681 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000682 // The computation is correct in the face of overflow provided that the
683 // multiplication is performed _after_ the evaluation of the binomial
684 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000685 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000686 if (isa<SCEVCouldNotCompute>(Coeff))
687 return Coeff;
688
689 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000690 }
691 return Result;
692}
693
Chris Lattner53e677a2004-04-02 20:23:17 +0000694//===----------------------------------------------------------------------===//
695// SCEV Expression folder implementations
696//===----------------------------------------------------------------------===//
697
Dan Gohman0bba49c2009-07-07 17:06:11 +0000698const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000699 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000700 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000701 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000702 assert(isSCEVable(Ty) &&
703 "This is not a conversion to a SCEVable type!");
704 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000705
Dan Gohmanc050fd92009-07-13 20:50:19 +0000706 FoldingSetNodeID ID;
707 ID.AddInteger(scTruncate);
708 ID.AddPointer(Op);
709 ID.AddPointer(Ty);
710 void *IP = 0;
711 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
712
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000713 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000714 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000715 return getConstant(
716 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000717
Dan Gohman20900ca2009-04-22 16:20:48 +0000718 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000719 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000720 return getTruncateExpr(ST->getOperand(), Ty);
721
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000722 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000723 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000724 return getTruncateOrSignExtend(SS->getOperand(), Ty);
725
726 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000727 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000728 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
729
Dan Gohman6864db62009-06-18 16:24:47 +0000730 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000731 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000732 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000733 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000734 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
735 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000736 }
737
Dan Gohmanc050fd92009-07-13 20:50:19 +0000738 // The cast wasn't folded; create an explicit cast node.
739 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000740 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000741 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
742 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000743 UniqueSCEVs.InsertNode(S, IP);
744 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000745}
746
Dan Gohman0bba49c2009-07-07 17:06:11 +0000747const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000748 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000749 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000750 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000751 assert(isSCEVable(Ty) &&
752 "This is not a conversion to a SCEVable type!");
753 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000754
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000755 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000756 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000757 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000758 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
759 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000760 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000761 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000762
Dan Gohman20900ca2009-04-22 16:20:48 +0000763 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000764 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000765 return getZeroExtendExpr(SZ->getOperand(), Ty);
766
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000767 // Before doing any expensive analysis, check to see if we've already
768 // computed a SCEV for this Op and Ty.
769 FoldingSetNodeID ID;
770 ID.AddInteger(scZeroExtend);
771 ID.AddPointer(Op);
772 ID.AddPointer(Ty);
773 void *IP = 0;
774 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
775
Dan Gohman01ecca22009-04-27 20:16:15 +0000776 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000777 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000778 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000779 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000780 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000781 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000782 const SCEV *Start = AR->getStart();
783 const SCEV *Step = AR->getStepRecurrence(*this);
784 unsigned BitWidth = getTypeSizeInBits(AR->getType());
785 const Loop *L = AR->getLoop();
786
Dan Gohmaneb490a72009-07-25 01:22:26 +0000787 // If we have special knowledge that this addrec won't overflow,
788 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000789 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000790 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
791 getZeroExtendExpr(Step, Ty),
792 L);
793
Dan Gohman01ecca22009-04-27 20:16:15 +0000794 // Check whether the backedge-taken count is SCEVCouldNotCompute.
795 // Note that this serves two purposes: It filters out loops that are
796 // simply not analyzable, and it covers the case where this code is
797 // being called from within backedge-taken count analysis, such that
798 // attempting to ask for the backedge-taken count would likely result
799 // in infinite recursion. In the later case, the analysis code will
800 // cope with a conservative value, and it will take care to purge
801 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000802 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000803 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000804 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000805 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000806
807 // Check whether the backedge-taken count can be losslessly casted to
808 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000809 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000810 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000811 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000812 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
813 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000814 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000815 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000816 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000817 const SCEV *Add = getAddExpr(Start, ZMul);
818 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000819 getAddExpr(getZeroExtendExpr(Start, WideTy),
820 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
821 getZeroExtendExpr(Step, WideTy)));
822 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000823 // Return the expression with the addrec on the outside.
824 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
825 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000826 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000827
828 // Similar to above, only this time treat the step value as signed.
829 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000830 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000831 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000832 OperandExtendedAdd =
833 getAddExpr(getZeroExtendExpr(Start, WideTy),
834 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
835 getSignExtendExpr(Step, WideTy)));
836 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000837 // Return the expression with the addrec on the outside.
838 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
839 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000840 L);
841 }
842
843 // If the backedge is guarded by a comparison with the pre-inc value
844 // the addrec is safe. Also, if the entry is guarded by a comparison
845 // with the start value and the backedge is guarded by a comparison
846 // with the post-inc value, the addrec is safe.
847 if (isKnownPositive(Step)) {
848 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
849 getUnsignedRange(Step).getUnsignedMax());
850 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000851 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000852 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
853 AR->getPostIncExpr(*this), N)))
854 // Return the expression with the addrec on the outside.
855 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
856 getZeroExtendExpr(Step, Ty),
857 L);
858 } else if (isKnownNegative(Step)) {
859 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
860 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000861 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
862 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000863 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
864 AR->getPostIncExpr(*this), N)))
865 // Return the expression with the addrec on the outside.
866 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
867 getSignExtendExpr(Step, Ty),
868 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000869 }
870 }
871 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000872
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000873 // The cast wasn't folded; create an explicit cast node.
874 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000875 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000876 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
877 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000878 UniqueSCEVs.InsertNode(S, IP);
879 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000880}
881
Dan Gohman0bba49c2009-07-07 17:06:11 +0000882const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000883 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000884 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000885 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000886 assert(isSCEVable(Ty) &&
887 "This is not a conversion to a SCEVable type!");
888 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000889
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000890 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000891 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000892 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000893 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
894 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000895 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000896 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000897
Dan Gohman20900ca2009-04-22 16:20:48 +0000898 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000899 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000900 return getSignExtendExpr(SS->getOperand(), Ty);
901
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000902 // Before doing any expensive analysis, check to see if we've already
903 // computed a SCEV for this Op and Ty.
904 FoldingSetNodeID ID;
905 ID.AddInteger(scSignExtend);
906 ID.AddPointer(Op);
907 ID.AddPointer(Ty);
908 void *IP = 0;
909 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
910
Dan Gohman01ecca22009-04-27 20:16:15 +0000911 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000912 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000913 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000914 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000915 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000916 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000917 const SCEV *Start = AR->getStart();
918 const SCEV *Step = AR->getStepRecurrence(*this);
919 unsigned BitWidth = getTypeSizeInBits(AR->getType());
920 const Loop *L = AR->getLoop();
921
Dan Gohmaneb490a72009-07-25 01:22:26 +0000922 // If we have special knowledge that this addrec won't overflow,
923 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000924 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000925 return getAddRecExpr(getSignExtendExpr(Start, Ty),
926 getSignExtendExpr(Step, Ty),
927 L);
928
Dan Gohman01ecca22009-04-27 20:16:15 +0000929 // Check whether the backedge-taken count is SCEVCouldNotCompute.
930 // Note that this serves two purposes: It filters out loops that are
931 // simply not analyzable, and it covers the case where this code is
932 // being called from within backedge-taken count analysis, such that
933 // attempting to ask for the backedge-taken count would likely result
934 // in infinite recursion. In the later case, the analysis code will
935 // cope with a conservative value, and it will take care to purge
936 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000937 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000938 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000939 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000940 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000941
942 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000943 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000944 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000945 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000946 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000947 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
948 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000949 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000950 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000951 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000952 const SCEV *Add = getAddExpr(Start, SMul);
953 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000954 getAddExpr(getSignExtendExpr(Start, WideTy),
955 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
956 getSignExtendExpr(Step, WideTy)));
957 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000958 // Return the expression with the addrec on the outside.
959 return getAddRecExpr(getSignExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000961 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000962
963 // Similar to above, only this time treat the step value as unsigned.
964 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +0000965 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +0000966 Add = getAddExpr(Start, UMul);
967 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +0000968 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +0000969 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
970 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +0000971 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +0000972 // Return the expression with the addrec on the outside.
973 return getAddRecExpr(getSignExtendExpr(Start, Ty),
974 getZeroExtendExpr(Step, Ty),
975 L);
Dan Gohman85b05a22009-07-13 21:35:55 +0000976 }
977
978 // If the backedge is guarded by a comparison with the pre-inc value
979 // the addrec is safe. Also, if the entry is guarded by a comparison
980 // with the start value and the backedge is guarded by a comparison
981 // with the post-inc value, the addrec is safe.
982 if (isKnownPositive(Step)) {
983 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
984 getSignedRange(Step).getSignedMax());
985 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000986 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000987 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
988 AR->getPostIncExpr(*this), N)))
989 // Return the expression with the addrec on the outside.
990 return getAddRecExpr(getSignExtendExpr(Start, Ty),
991 getSignExtendExpr(Step, Ty),
992 L);
993 } else if (isKnownNegative(Step)) {
994 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
995 getSignedRange(Step).getSignedMin());
996 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000997 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000998 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
999 AR->getPostIncExpr(*this), N)))
1000 // Return the expression with the addrec on the outside.
1001 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1002 getSignExtendExpr(Step, Ty),
1003 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001004 }
1005 }
1006 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001007
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001008 // The cast wasn't folded; create an explicit cast node.
1009 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001010 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001011 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1012 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001013 UniqueSCEVs.InsertNode(S, IP);
1014 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001015}
1016
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001017/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1018/// unspecified bits out to the given type.
1019///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001020const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001021 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001022 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1023 "This is not an extending conversion!");
1024 assert(isSCEVable(Ty) &&
1025 "This is not a conversion to a SCEVable type!");
1026 Ty = getEffectiveSCEVType(Ty);
1027
1028 // Sign-extend negative constants.
1029 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1030 if (SC->getValue()->getValue().isNegative())
1031 return getSignExtendExpr(Op, Ty);
1032
1033 // Peel off a truncate cast.
1034 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001035 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001036 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1037 return getAnyExtendExpr(NewOp, Ty);
1038 return getTruncateOrNoop(NewOp, Ty);
1039 }
1040
1041 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001042 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001043 if (!isa<SCEVZeroExtendExpr>(ZExt))
1044 return ZExt;
1045
1046 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001047 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001048 if (!isa<SCEVSignExtendExpr>(SExt))
1049 return SExt;
1050
Dan Gohmana10756e2010-01-21 02:09:26 +00001051 // Force the cast to be folded into the operands of an addrec.
1052 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1053 SmallVector<const SCEV *, 4> Ops;
1054 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1055 I != E; ++I)
1056 Ops.push_back(getAnyExtendExpr(*I, Ty));
1057 return getAddRecExpr(Ops, AR->getLoop());
1058 }
1059
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001060 // If the expression is obviously signed, use the sext cast value.
1061 if (isa<SCEVSMaxExpr>(Op))
1062 return SExt;
1063
1064 // Absent any other information, use the zext cast value.
1065 return ZExt;
1066}
1067
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001068/// CollectAddOperandsWithScales - Process the given Ops list, which is
1069/// a list of operands to be added under the given scale, update the given
1070/// map. This is a helper function for getAddRecExpr. As an example of
1071/// what it does, given a sequence of operands that would form an add
1072/// expression like this:
1073///
1074/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1075///
1076/// where A and B are constants, update the map with these values:
1077///
1078/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1079///
1080/// and add 13 + A*B*29 to AccumulatedConstant.
1081/// This will allow getAddRecExpr to produce this:
1082///
1083/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1084///
1085/// This form often exposes folding opportunities that are hidden in
1086/// the original operand list.
1087///
1088/// Return true iff it appears that any interesting folding opportunities
1089/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1090/// the common case where no interesting opportunities are present, and
1091/// is also used as a check to avoid infinite recursion.
1092///
1093static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001094CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1095 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001096 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001097 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001098 const APInt &Scale,
1099 ScalarEvolution &SE) {
1100 bool Interesting = false;
1101
1102 // Iterate over the add operands.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001103 for (unsigned i = 0, e = NumOperands; i != e; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001104 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1105 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1106 APInt NewScale =
1107 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1108 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1109 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001110 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001111 Interesting |=
1112 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001113 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001114 NewScale, SE);
1115 } else {
1116 // A multiplication of a constant with some other value. Update
1117 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001118 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1119 const SCEV *Key = SE.getMulExpr(MulOps);
1120 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001121 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001122 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001123 NewOps.push_back(Pair.first->first);
1124 } else {
1125 Pair.first->second += NewScale;
1126 // The map already had an entry for this value, which may indicate
1127 // a folding opportunity.
1128 Interesting = true;
1129 }
1130 }
1131 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1132 // Pull a buried constant out to the outside.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001133 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001134 Interesting = true;
1135 AccumulatedConstant += Scale * C->getValue()->getValue();
1136 } else {
1137 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001138 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001139 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001140 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001141 NewOps.push_back(Pair.first->first);
1142 } else {
1143 Pair.first->second += Scale;
1144 // The map already had an entry for this value, which may indicate
1145 // a folding opportunity.
1146 Interesting = true;
1147 }
1148 }
1149 }
1150
1151 return Interesting;
1152}
1153
1154namespace {
1155 struct APIntCompare {
1156 bool operator()(const APInt &LHS, const APInt &RHS) const {
1157 return LHS.ult(RHS);
1158 }
1159 };
1160}
1161
Dan Gohman6c0866c2009-05-24 23:45:28 +00001162/// getAddExpr - Get a canonical add expression, or something simpler if
1163/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001164const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1165 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001166 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001167 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001168#ifndef NDEBUG
1169 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1170 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1171 getEffectiveSCEVType(Ops[0]->getType()) &&
1172 "SCEVAddExpr operand types don't match!");
1173#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001174
Dan Gohmana10756e2010-01-21 02:09:26 +00001175 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1176 if (!HasNUW && HasNSW) {
1177 bool All = true;
1178 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1179 if (!isKnownNonNegative(Ops[i])) {
1180 All = false;
1181 break;
1182 }
1183 if (All) HasNUW = true;
1184 }
1185
Chris Lattner53e677a2004-04-02 20:23:17 +00001186 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001187 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001188
1189 // If there are any constants, fold them together.
1190 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001191 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001192 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001193 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001194 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001195 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001196 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1197 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001198 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001199 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001200 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001201 }
1202
1203 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001204 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001205 Ops.erase(Ops.begin());
1206 --Idx;
1207 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001208
Dan Gohmanbca091d2010-04-12 23:08:18 +00001209 if (Ops.size() == 1) return Ops[0];
1210 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001211
Chris Lattner53e677a2004-04-02 20:23:17 +00001212 // Okay, check to see if the same value occurs in the operand list twice. If
1213 // so, merge them together into an multiply expression. Since we sorted the
1214 // list, these values are required to be adjacent.
1215 const Type *Ty = Ops[0]->getType();
1216 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1217 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1218 // Found a match, merge the two values into a multiply, and add any
1219 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001220 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001221 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 if (Ops.size() == 2)
1223 return Mul;
1224 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1225 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001226 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001227 }
1228
Dan Gohman728c7f32009-05-08 21:03:19 +00001229 // Check for truncates. If all the operands are truncated from the same
1230 // type, see if factoring out the truncate would permit the result to be
1231 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1232 // if the contents of the resulting outer trunc fold to something simple.
1233 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1234 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1235 const Type *DstType = Trunc->getType();
1236 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001237 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001238 bool Ok = true;
1239 // Check all the operands to see if they can be represented in the
1240 // source type of the truncate.
1241 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1242 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1243 if (T->getOperand()->getType() != SrcType) {
1244 Ok = false;
1245 break;
1246 }
1247 LargeOps.push_back(T->getOperand());
1248 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001249 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001250 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001251 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001252 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1253 if (const SCEVTruncateExpr *T =
1254 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1255 if (T->getOperand()->getType() != SrcType) {
1256 Ok = false;
1257 break;
1258 }
1259 LargeMulOps.push_back(T->getOperand());
1260 } else if (const SCEVConstant *C =
1261 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001262 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001263 } else {
1264 Ok = false;
1265 break;
1266 }
1267 }
1268 if (Ok)
1269 LargeOps.push_back(getMulExpr(LargeMulOps));
1270 } else {
1271 Ok = false;
1272 break;
1273 }
1274 }
1275 if (Ok) {
1276 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001277 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001278 // If it folds to something simple, use it. Otherwise, don't.
1279 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1280 return getTruncateExpr(Fold, DstType);
1281 }
1282 }
1283
1284 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001285 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1286 ++Idx;
1287
1288 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001289 if (Idx < Ops.size()) {
1290 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001291 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001292 // If we have an add, expand the add operands onto the end of the operands
1293 // list.
1294 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1295 Ops.erase(Ops.begin()+Idx);
1296 DeletedAdd = true;
1297 }
1298
1299 // If we deleted at least one add, we added operands to the end of the list,
1300 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001301 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001302 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001303 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001304 }
1305
1306 // Skip over the add expression until we get to a multiply.
1307 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1308 ++Idx;
1309
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001310 // Check to see if there are any folding opportunities present with
1311 // operands multiplied by constant values.
1312 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1313 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001314 DenseMap<const SCEV *, APInt> M;
1315 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001316 APInt AccumulatedConstant(BitWidth, 0);
1317 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001318 Ops.data(), Ops.size(),
1319 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001320 // Some interesting folding opportunity is present, so its worthwhile to
1321 // re-generate the operands list. Group the operands by constant scale,
1322 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001323 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1324 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001325 E = NewOps.end(); I != E; ++I)
1326 MulOpLists[M.find(*I)->second].push_back(*I);
1327 // Re-generate the operands list.
1328 Ops.clear();
1329 if (AccumulatedConstant != 0)
1330 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001331 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1332 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001333 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001334 Ops.push_back(getMulExpr(getConstant(I->first),
1335 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001336 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001337 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001338 if (Ops.size() == 1)
1339 return Ops[0];
1340 return getAddExpr(Ops);
1341 }
1342 }
1343
Chris Lattner53e677a2004-04-02 20:23:17 +00001344 // If we are adding something to a multiply expression, make sure the
1345 // something is not already an operand of the multiply. If so, merge it into
1346 // the multiply.
1347 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001348 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001350 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001351 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001352 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001353 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001354 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 if (Mul->getNumOperands() != 2) {
1356 // If the multiply has more than two operands, we must get the
1357 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001358 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001359 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001360 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001361 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001362 const SCEV *One = getConstant(Ty, 1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001363 const SCEV *AddOne = getAddExpr(InnerMul, One);
1364 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001365 if (Ops.size() == 2) return OuterMul;
1366 if (AddOp < Idx) {
1367 Ops.erase(Ops.begin()+AddOp);
1368 Ops.erase(Ops.begin()+Idx-1);
1369 } else {
1370 Ops.erase(Ops.begin()+Idx);
1371 Ops.erase(Ops.begin()+AddOp-1);
1372 }
1373 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001374 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001375 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001376
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 // Check this multiply against other multiplies being added together.
1378 for (unsigned OtherMulIdx = Idx+1;
1379 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1380 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001381 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 // If MulOp occurs in OtherMul, we can fold the two multiplies
1383 // together.
1384 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1385 OMulOp != e; ++OMulOp)
1386 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1387 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001388 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001390 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1391 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001392 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001393 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001394 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001395 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001397 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1398 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001399 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001400 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001402 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1403 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 if (Ops.size() == 2) return OuterMul;
1405 Ops.erase(Ops.begin()+Idx);
1406 Ops.erase(Ops.begin()+OtherMulIdx-1);
1407 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001408 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001409 }
1410 }
1411 }
1412 }
1413
1414 // If there are any add recurrences in the operands list, see if any other
1415 // added values are loop invariant. If so, we can fold them into the
1416 // recurrence.
1417 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1418 ++Idx;
1419
1420 // Scan over all recurrences, trying to fold loop invariants into them.
1421 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1422 // Scan all of the other operands to this add and add them to the vector if
1423 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001424 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001425 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001426 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001427 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001428 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001429 LIOps.push_back(Ops[i]);
1430 Ops.erase(Ops.begin()+i);
1431 --i; --e;
1432 }
1433
1434 // If we found some loop invariants, fold them into the recurrence.
1435 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001436 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 LIOps.push_back(AddRec->getStart());
1438
Dan Gohman0bba49c2009-07-07 17:06:11 +00001439 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001440 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001441 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001442
Dan Gohman355b4f32009-12-19 01:46:34 +00001443 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001444 // is not associative so this isn't necessarily safe.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001445 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop);
Dan Gohman59de33e2009-12-18 18:45:31 +00001446
Chris Lattner53e677a2004-04-02 20:23:17 +00001447 // If all of the other operands were loop invariant, we are done.
1448 if (Ops.size() == 1) return NewRec;
1449
1450 // Otherwise, add the folded AddRec by the non-liv parts.
1451 for (unsigned i = 0;; ++i)
1452 if (Ops[i] == AddRec) {
1453 Ops[i] = NewRec;
1454 break;
1455 }
Dan Gohman246b2562007-10-22 18:31:58 +00001456 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001457 }
1458
1459 // Okay, if there weren't any loop invariants to be folded, check to see if
1460 // there are multiple AddRec's with the same loop induction variable being
1461 // added together. If so, we can fold them.
1462 for (unsigned OtherIdx = Idx+1;
1463 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1464 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001465 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001466 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001468 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1469 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1471 if (i >= NewOps.size()) {
1472 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1473 OtherAddRec->op_end());
1474 break;
1475 }
Dan Gohman246b2562007-10-22 18:31:58 +00001476 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001478 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001479
1480 if (Ops.size() == 2) return NewAddRec;
1481
1482 Ops.erase(Ops.begin()+Idx);
1483 Ops.erase(Ops.begin()+OtherIdx-1);
1484 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001485 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 }
1487 }
1488
1489 // Otherwise couldn't fold anything into this recurrence. Move onto the
1490 // next one.
1491 }
1492
1493 // Okay, it looks like we really DO need an add expr. Check to see if we
1494 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001495 FoldingSetNodeID ID;
1496 ID.AddInteger(scAddExpr);
1497 ID.AddInteger(Ops.size());
1498 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1499 ID.AddPointer(Ops[i]);
1500 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001501 SCEVAddExpr *S =
1502 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1503 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001504 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1505 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001506 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1507 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001508 UniqueSCEVs.InsertNode(S, IP);
1509 }
Dan Gohman3645b012009-10-09 00:10:36 +00001510 if (HasNUW) S->setHasNoUnsignedWrap(true);
1511 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001512 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001513}
1514
Dan Gohman6c0866c2009-05-24 23:45:28 +00001515/// getMulExpr - Get a canonical multiply expression, or something simpler if
1516/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001517const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1518 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001519 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001520 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001521#ifndef NDEBUG
1522 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1523 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1524 getEffectiveSCEVType(Ops[0]->getType()) &&
1525 "SCEVMulExpr operand types don't match!");
1526#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001527
Dan Gohmana10756e2010-01-21 02:09:26 +00001528 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1529 if (!HasNUW && HasNSW) {
1530 bool All = true;
1531 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1532 if (!isKnownNonNegative(Ops[i])) {
1533 All = false;
1534 break;
1535 }
1536 if (All) HasNUW = true;
1537 }
1538
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001540 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001541
1542 // If there are any constants, fold them together.
1543 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001544 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001545
1546 // C1*(C2+V) -> C1*C2 + C1*V
1547 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001548 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 if (Add->getNumOperands() == 2 &&
1550 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001551 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1552 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001553
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001555 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001556 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001557 ConstantInt *Fold = ConstantInt::get(getContext(),
1558 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001559 RHSC->getValue()->getValue());
1560 Ops[0] = getConstant(Fold);
1561 Ops.erase(Ops.begin()+1); // Erase the folded element
1562 if (Ops.size() == 1) return Ops[0];
1563 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001564 }
1565
1566 // If we are left with a constant one being multiplied, strip it off.
1567 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1568 Ops.erase(Ops.begin());
1569 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001570 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001571 // If we have a multiply of zero, it will always be zero.
1572 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001573 } else if (Ops[0]->isAllOnesValue()) {
1574 // If we have a mul by -1 of an add, try distributing the -1 among the
1575 // add operands.
1576 if (Ops.size() == 2)
1577 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1578 SmallVector<const SCEV *, 4> NewOps;
1579 bool AnyFolded = false;
1580 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1581 I != E; ++I) {
1582 const SCEV *Mul = getMulExpr(Ops[0], *I);
1583 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1584 NewOps.push_back(Mul);
1585 }
1586 if (AnyFolded)
1587 return getAddExpr(NewOps);
1588 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001590
1591 if (Ops.size() == 1)
1592 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001593 }
1594
1595 // Skip over the add expression until we get to a multiply.
1596 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1597 ++Idx;
1598
Chris Lattner53e677a2004-04-02 20:23:17 +00001599 // If there are mul operands inline them all into this expression.
1600 if (Idx < Ops.size()) {
1601 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001602 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001603 // If we have an mul, expand the mul operands onto the end of the operands
1604 // list.
1605 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1606 Ops.erase(Ops.begin()+Idx);
1607 DeletedMul = true;
1608 }
1609
1610 // If we deleted at least one mul, we added operands to the end of the list,
1611 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001612 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001613 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001614 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 }
1616
1617 // If there are any add recurrences in the operands list, see if any other
1618 // added values are loop invariant. If so, we can fold them into the
1619 // recurrence.
1620 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1621 ++Idx;
1622
1623 // Scan over all recurrences, trying to fold loop invariants into them.
1624 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1625 // Scan all of the other operands to this mul and add them to the vector if
1626 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001627 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001628 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001629 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1630 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1631 LIOps.push_back(Ops[i]);
1632 Ops.erase(Ops.begin()+i);
1633 --i; --e;
1634 }
1635
1636 // If we found some loop invariants, fold them into the recurrence.
1637 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001638 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001639 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001640 NewOps.reserve(AddRec->getNumOperands());
1641 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001642 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001643 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001644 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001645 } else {
1646 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001647 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001648 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001649 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 }
1651 }
1652
Dan Gohman355b4f32009-12-19 01:46:34 +00001653 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001654 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001655 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1656 HasNUW && AddRec->hasNoUnsignedWrap(),
1657 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001658
1659 // If all of the other operands were loop invariant, we are done.
1660 if (Ops.size() == 1) return NewRec;
1661
1662 // Otherwise, multiply the folded AddRec by the non-liv parts.
1663 for (unsigned i = 0;; ++i)
1664 if (Ops[i] == AddRec) {
1665 Ops[i] = NewRec;
1666 break;
1667 }
Dan Gohman246b2562007-10-22 18:31:58 +00001668 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001669 }
1670
1671 // Okay, if there weren't any loop invariants to be folded, check to see if
1672 // there are multiple AddRec's with the same loop induction variable being
1673 // multiplied together. If so, we can fold them.
1674 for (unsigned OtherIdx = Idx+1;
1675 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1676 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001677 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001678 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1679 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001680 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001681 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001683 const SCEV *B = F->getStepRecurrence(*this);
1684 const SCEV *D = G->getStepRecurrence(*this);
1685 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001686 getMulExpr(G, B),
1687 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001688 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001689 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001690 if (Ops.size() == 2) return NewAddRec;
1691
1692 Ops.erase(Ops.begin()+Idx);
1693 Ops.erase(Ops.begin()+OtherIdx-1);
1694 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001695 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001696 }
1697 }
1698
1699 // Otherwise couldn't fold anything into this recurrence. Move onto the
1700 // next one.
1701 }
1702
1703 // Okay, it looks like we really DO need an mul expr. Check to see if we
1704 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001705 FoldingSetNodeID ID;
1706 ID.AddInteger(scMulExpr);
1707 ID.AddInteger(Ops.size());
1708 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1709 ID.AddPointer(Ops[i]);
1710 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001711 SCEVMulExpr *S =
1712 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1713 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001714 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1715 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001716 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1717 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001718 UniqueSCEVs.InsertNode(S, IP);
1719 }
Dan Gohman3645b012009-10-09 00:10:36 +00001720 if (HasNUW) S->setHasNoUnsignedWrap(true);
1721 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001722 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001723}
1724
Andreas Bolka8a11c982009-08-07 22:55:26 +00001725/// getUDivExpr - Get a canonical unsigned division expression, or something
1726/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001727const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1728 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001729 assert(getEffectiveSCEVType(LHS->getType()) ==
1730 getEffectiveSCEVType(RHS->getType()) &&
1731 "SCEVUDivExpr operand types don't match!");
1732
Dan Gohman622ed672009-05-04 22:02:23 +00001733 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001734 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001735 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001736 // If the denominator is zero, the result of the udiv is undefined. Don't
1737 // try to analyze it, because the resolution chosen here may differ from
1738 // the resolution chosen in other parts of the compiler.
1739 if (!RHSC->getValue()->isZero()) {
1740 // Determine if the division can be folded into the operands of
1741 // its operands.
1742 // TODO: Generalize this to non-constants by using known-bits information.
1743 const Type *Ty = LHS->getType();
1744 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1745 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1746 // For non-power-of-two values, effectively round the value up to the
1747 // nearest power of two.
1748 if (!RHSC->getValue()->getValue().isPowerOf2())
1749 ++MaxShiftAmt;
1750 const IntegerType *ExtTy =
1751 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1752 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1753 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1754 if (const SCEVConstant *Step =
1755 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1756 if (!Step->getValue()->getValue()
1757 .urem(RHSC->getValue()->getValue()) &&
1758 getZeroExtendExpr(AR, ExtTy) ==
1759 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1760 getZeroExtendExpr(Step, ExtTy),
1761 AR->getLoop())) {
1762 SmallVector<const SCEV *, 4> Operands;
1763 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1764 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1765 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001766 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001767 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1768 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1769 SmallVector<const SCEV *, 4> Operands;
1770 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1771 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1772 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1773 // Find an operand that's safely divisible.
1774 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1775 const SCEV *Op = M->getOperand(i);
1776 const SCEV *Div = getUDivExpr(Op, RHSC);
1777 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1778 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1779 M->op_end());
1780 Operands[i] = Div;
1781 return getMulExpr(Operands);
1782 }
1783 }
Dan Gohman185cf032009-05-08 20:18:49 +00001784 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001785 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1786 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1787 SmallVector<const SCEV *, 4> Operands;
1788 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1789 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1790 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1791 Operands.clear();
1792 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1793 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1794 if (isa<SCEVUDivExpr>(Op) ||
1795 getMulExpr(Op, RHS) != A->getOperand(i))
1796 break;
1797 Operands.push_back(Op);
1798 }
1799 if (Operands.size() == A->getNumOperands())
1800 return getAddExpr(Operands);
1801 }
1802 }
Dan Gohman185cf032009-05-08 20:18:49 +00001803
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001804 // Fold if both operands are constant.
1805 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1806 Constant *LHSCV = LHSC->getValue();
1807 Constant *RHSCV = RHSC->getValue();
1808 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1809 RHSCV)));
1810 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001811 }
1812 }
1813
Dan Gohman1c343752009-06-27 21:21:31 +00001814 FoldingSetNodeID ID;
1815 ID.AddInteger(scUDivExpr);
1816 ID.AddPointer(LHS);
1817 ID.AddPointer(RHS);
1818 void *IP = 0;
1819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001820 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1821 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001822 UniqueSCEVs.InsertNode(S, IP);
1823 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001824}
1825
1826
Dan Gohman6c0866c2009-05-24 23:45:28 +00001827/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1828/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001829const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001830 const SCEV *Step, const Loop *L,
1831 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001832 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001833 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001834 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001835 if (StepChrec->getLoop() == L) {
1836 Operands.insert(Operands.end(), StepChrec->op_begin(),
1837 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001838 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001839 }
1840
1841 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001842 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001843}
1844
Dan Gohman6c0866c2009-05-24 23:45:28 +00001845/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1846/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001847const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001848ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001849 const Loop *L,
1850 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001851 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001852#ifndef NDEBUG
1853 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1854 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1855 getEffectiveSCEVType(Operands[0]->getType()) &&
1856 "SCEVAddRecExpr operand types don't match!");
1857#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001858
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001859 if (Operands.back()->isZero()) {
1860 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001861 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001862 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001863
Dan Gohmanbc028532010-02-19 18:49:22 +00001864 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1865 // use that information to infer NUW and NSW flags. However, computing a
1866 // BE count requires calling getAddRecExpr, so we may not yet have a
1867 // meaningful BE count at this point (and if we don't, we'd be stuck
1868 // with a SCEVCouldNotCompute as the cached BE count).
1869
Dan Gohmana10756e2010-01-21 02:09:26 +00001870 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1871 if (!HasNUW && HasNSW) {
1872 bool All = true;
1873 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1874 if (!isKnownNonNegative(Operands[i])) {
1875 All = false;
1876 break;
1877 }
1878 if (All) HasNUW = true;
1879 }
1880
Dan Gohmand9cc7492008-08-08 18:33:12 +00001881 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001882 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001883 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001884 if (L->contains(NestedLoop->getHeader()) ?
1885 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1886 (!NestedLoop->contains(L->getHeader()) &&
1887 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001888 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001889 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001890 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001891 // AddRecs require their operands be loop-invariant with respect to their
1892 // loops. Don't perform this transformation if it would break this
1893 // requirement.
1894 bool AllInvariant = true;
1895 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1896 if (!Operands[i]->isLoopInvariant(L)) {
1897 AllInvariant = false;
1898 break;
1899 }
1900 if (AllInvariant) {
1901 NestedOperands[0] = getAddRecExpr(Operands, L);
1902 AllInvariant = true;
1903 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1904 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1905 AllInvariant = false;
1906 break;
1907 }
1908 if (AllInvariant)
1909 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00001910 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00001911 }
1912 // Reset Operands to its original state.
1913 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001914 }
1915 }
1916
Dan Gohman67847532010-01-19 22:27:22 +00001917 // Okay, it looks like we really DO need an addrec expr. Check to see if we
1918 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001919 FoldingSetNodeID ID;
1920 ID.AddInteger(scAddRecExpr);
1921 ID.AddInteger(Operands.size());
1922 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1923 ID.AddPointer(Operands[i]);
1924 ID.AddPointer(L);
1925 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001926 SCEVAddRecExpr *S =
1927 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1928 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001929 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
1930 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001931 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
1932 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00001933 UniqueSCEVs.InsertNode(S, IP);
1934 }
Dan Gohman3645b012009-10-09 00:10:36 +00001935 if (HasNUW) S->setHasNoUnsignedWrap(true);
1936 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001937 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001938}
1939
Dan Gohman9311ef62009-06-24 14:49:00 +00001940const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1941 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001942 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001943 Ops.push_back(LHS);
1944 Ops.push_back(RHS);
1945 return getSMaxExpr(Ops);
1946}
1947
Dan Gohman0bba49c2009-07-07 17:06:11 +00001948const SCEV *
1949ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001950 assert(!Ops.empty() && "Cannot get empty smax!");
1951 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001952#ifndef NDEBUG
1953 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1954 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1955 getEffectiveSCEVType(Ops[0]->getType()) &&
1956 "SCEVSMaxExpr operand types don't match!");
1957#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001958
1959 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001960 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001961
1962 // If there are any constants, fold them together.
1963 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001964 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001965 ++Idx;
1966 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001967 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001968 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001969 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001970 APIntOps::smax(LHSC->getValue()->getValue(),
1971 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001972 Ops[0] = getConstant(Fold);
1973 Ops.erase(Ops.begin()+1); // Erase the folded element
1974 if (Ops.size() == 1) return Ops[0];
1975 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001976 }
1977
Dan Gohmane5aceed2009-06-24 14:46:22 +00001978 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001979 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1980 Ops.erase(Ops.begin());
1981 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001982 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1983 // If we have an smax with a constant maximum-int, it will always be
1984 // maximum-int.
1985 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001986 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001987
Dan Gohman3ab13122010-04-13 16:49:23 +00001988 if (Ops.size() == 1) return Ops[0];
1989 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001990
1991 // Find the first SMax
1992 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1993 ++Idx;
1994
1995 // Check to see if one of the operands is an SMax. If so, expand its operands
1996 // onto our operand list, and recurse to simplify.
1997 if (Idx < Ops.size()) {
1998 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001999 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002000 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2001 Ops.erase(Ops.begin()+Idx);
2002 DeletedSMax = true;
2003 }
2004
2005 if (DeletedSMax)
2006 return getSMaxExpr(Ops);
2007 }
2008
2009 // Okay, check to see if the same value occurs in the operand list twice. If
2010 // so, delete one. Since we sorted the list, these values are required to
2011 // be adjacent.
2012 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002013 // X smax Y smax Y --> X smax Y
2014 // X smax Y --> X, if X is always greater than Y
2015 if (Ops[i] == Ops[i+1] ||
2016 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2017 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2018 --i; --e;
2019 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002020 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2021 --i; --e;
2022 }
2023
2024 if (Ops.size() == 1) return Ops[0];
2025
2026 assert(!Ops.empty() && "Reduced smax down to nothing!");
2027
Nick Lewycky3e630762008-02-20 06:48:22 +00002028 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002029 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002030 FoldingSetNodeID ID;
2031 ID.AddInteger(scSMaxExpr);
2032 ID.AddInteger(Ops.size());
2033 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2034 ID.AddPointer(Ops[i]);
2035 void *IP = 0;
2036 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002037 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2038 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002039 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2040 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002041 UniqueSCEVs.InsertNode(S, IP);
2042 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002043}
2044
Dan Gohman9311ef62009-06-24 14:49:00 +00002045const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2046 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002047 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002048 Ops.push_back(LHS);
2049 Ops.push_back(RHS);
2050 return getUMaxExpr(Ops);
2051}
2052
Dan Gohman0bba49c2009-07-07 17:06:11 +00002053const SCEV *
2054ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002055 assert(!Ops.empty() && "Cannot get empty umax!");
2056 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002057#ifndef NDEBUG
2058 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2059 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2060 getEffectiveSCEVType(Ops[0]->getType()) &&
2061 "SCEVUMaxExpr operand types don't match!");
2062#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002063
2064 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002065 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002066
2067 // If there are any constants, fold them together.
2068 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002069 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002070 ++Idx;
2071 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002072 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002073 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002074 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002075 APIntOps::umax(LHSC->getValue()->getValue(),
2076 RHSC->getValue()->getValue()));
2077 Ops[0] = getConstant(Fold);
2078 Ops.erase(Ops.begin()+1); // Erase the folded element
2079 if (Ops.size() == 1) return Ops[0];
2080 LHSC = cast<SCEVConstant>(Ops[0]);
2081 }
2082
Dan Gohmane5aceed2009-06-24 14:46:22 +00002083 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002084 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2085 Ops.erase(Ops.begin());
2086 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002087 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2088 // If we have an umax with a constant maximum-int, it will always be
2089 // maximum-int.
2090 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002091 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002092
Dan Gohman3ab13122010-04-13 16:49:23 +00002093 if (Ops.size() == 1) return Ops[0];
2094 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002095
2096 // Find the first UMax
2097 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2098 ++Idx;
2099
2100 // Check to see if one of the operands is a UMax. If so, expand its operands
2101 // onto our operand list, and recurse to simplify.
2102 if (Idx < Ops.size()) {
2103 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002104 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002105 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2106 Ops.erase(Ops.begin()+Idx);
2107 DeletedUMax = true;
2108 }
2109
2110 if (DeletedUMax)
2111 return getUMaxExpr(Ops);
2112 }
2113
2114 // Okay, check to see if the same value occurs in the operand list twice. If
2115 // so, delete one. Since we sorted the list, these values are required to
2116 // be adjacent.
2117 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002118 // X umax Y umax Y --> X umax Y
2119 // X umax Y --> X, if X is always greater than Y
2120 if (Ops[i] == Ops[i+1] ||
2121 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2122 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2123 --i; --e;
2124 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002125 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2126 --i; --e;
2127 }
2128
2129 if (Ops.size() == 1) return Ops[0];
2130
2131 assert(!Ops.empty() && "Reduced umax down to nothing!");
2132
2133 // Okay, it looks like we really DO need a umax expr. Check to see if we
2134 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002135 FoldingSetNodeID ID;
2136 ID.AddInteger(scUMaxExpr);
2137 ID.AddInteger(Ops.size());
2138 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2139 ID.AddPointer(Ops[i]);
2140 void *IP = 0;
2141 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002142 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2143 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002144 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2145 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002146 UniqueSCEVs.InsertNode(S, IP);
2147 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002148}
2149
Dan Gohman9311ef62009-06-24 14:49:00 +00002150const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2151 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002152 // ~smax(~x, ~y) == smin(x, y).
2153 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2154}
2155
Dan Gohman9311ef62009-06-24 14:49:00 +00002156const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2157 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002158 // ~umax(~x, ~y) == umin(x, y)
2159 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2160}
2161
Dan Gohman4f8eea82010-02-01 18:27:38 +00002162const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002163 // If we have TargetData, we can bypass creating a target-independent
2164 // constant expression and then folding it back into a ConstantInt.
2165 // This is just a compile-time optimization.
2166 if (TD)
2167 return getConstant(TD->getIntPtrType(getContext()),
2168 TD->getTypeAllocSize(AllocTy));
2169
Dan Gohman4f8eea82010-02-01 18:27:38 +00002170 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2171 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002172 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2173 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002174 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2175 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2176}
2177
2178const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2179 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2180 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002181 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2182 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002183 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2184 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2185}
2186
2187const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2188 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002189 // If we have TargetData, we can bypass creating a target-independent
2190 // constant expression and then folding it back into a ConstantInt.
2191 // This is just a compile-time optimization.
2192 if (TD)
2193 return getConstant(TD->getIntPtrType(getContext()),
2194 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2195
Dan Gohman0f5efe52010-01-28 02:15:55 +00002196 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2197 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002198 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2199 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002200 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002201 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002202}
2203
Dan Gohman4f8eea82010-02-01 18:27:38 +00002204const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2205 Constant *FieldNo) {
2206 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002207 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002208 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2209 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002210 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002211 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002212}
2213
Dan Gohman0bba49c2009-07-07 17:06:11 +00002214const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002215 // Don't attempt to do anything other than create a SCEVUnknown object
2216 // here. createSCEV only calls getUnknown after checking for all other
2217 // interesting possibilities, and any other code that calls getUnknown
2218 // is doing so in order to hide a value from SCEV canonicalization.
2219
Dan Gohman1c343752009-06-27 21:21:31 +00002220 FoldingSetNodeID ID;
2221 ID.AddInteger(scUnknown);
2222 ID.AddPointer(V);
2223 void *IP = 0;
2224 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00002225 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +00002226 UniqueSCEVs.InsertNode(S, IP);
2227 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002228}
2229
Chris Lattner53e677a2004-04-02 20:23:17 +00002230//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002231// Basic SCEV Analysis and PHI Idiom Recognition Code
2232//
2233
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002234/// isSCEVable - Test if values of the given type are analyzable within
2235/// the SCEV framework. This primarily includes integer types, and it
2236/// can optionally include pointer types if the ScalarEvolution class
2237/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002238bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002239 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002240 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002241}
2242
2243/// getTypeSizeInBits - Return the size in bits of the specified type,
2244/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002245uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002246 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2247
2248 // If we have a TargetData, use it!
2249 if (TD)
2250 return TD->getTypeSizeInBits(Ty);
2251
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002252 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002253 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002254 return Ty->getPrimitiveSizeInBits();
2255
2256 // The only other support type is pointer. Without TargetData, conservatively
2257 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002258 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002259 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002260}
2261
2262/// getEffectiveSCEVType - Return a type with the same bitwidth as
2263/// the given type and which represents how SCEV will treat the given
2264/// type, for which isSCEVable must return true. For pointer types,
2265/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002266const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002267 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2268
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002269 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002270 return Ty;
2271
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002272 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002273 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002274 if (TD) return TD->getIntPtrType(getContext());
2275
2276 // Without TargetData, conservatively assume pointers are 64-bit.
2277 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002278}
Chris Lattner53e677a2004-04-02 20:23:17 +00002279
Dan Gohman0bba49c2009-07-07 17:06:11 +00002280const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002281 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002282}
2283
Chris Lattner53e677a2004-04-02 20:23:17 +00002284/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2285/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002286const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002287 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002288
Dan Gohman0bba49c2009-07-07 17:06:11 +00002289 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002290 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002291 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002292 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002293 return S;
2294}
2295
Dan Gohman6bbcba12009-06-24 00:54:57 +00002296/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002297/// specified signed integer value and return a SCEV for the constant.
Dan Gohman32efba62010-02-04 02:43:51 +00002298const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002299 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002300 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002301}
2302
2303/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2304///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002305const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002306 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002307 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002308 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002309
2310 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002311 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002312 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002313 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002314}
2315
2316/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002317const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002318 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002319 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002320 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002321
2322 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002323 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002324 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002325 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002326 return getMinusSCEV(AllOnes, V);
2327}
2328
2329/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2330///
Dan Gohman9311ef62009-06-24 14:49:00 +00002331const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2332 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002333 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002334 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002335}
2336
2337/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2338/// input value to the specified type. If the type must be extended, it is zero
2339/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002340const SCEV *
2341ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002342 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002343 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002344 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002346 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002347 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002348 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002349 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002350 return getTruncateExpr(V, Ty);
2351 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002352}
2353
2354/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2355/// input value to the specified type. If the type must be extended, it is sign
2356/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002357const SCEV *
2358ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002359 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002360 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002361 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2362 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002363 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002364 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002365 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002366 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002367 return getTruncateExpr(V, Ty);
2368 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002369}
2370
Dan Gohman467c4302009-05-13 03:46:30 +00002371/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2372/// input value to the specified type. If the type must be extended, it is zero
2373/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002374const SCEV *
2375ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002376 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002377 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2378 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002379 "Cannot noop or zero extend with non-integer arguments!");
2380 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2381 "getNoopOrZeroExtend cannot truncate!");
2382 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2383 return V; // No conversion
2384 return getZeroExtendExpr(V, Ty);
2385}
2386
2387/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2388/// input value to the specified type. If the type must be extended, it is sign
2389/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002390const SCEV *
2391ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002392 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002393 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2394 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002395 "Cannot noop or sign extend with non-integer arguments!");
2396 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2397 "getNoopOrSignExtend cannot truncate!");
2398 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2399 return V; // No conversion
2400 return getSignExtendExpr(V, Ty);
2401}
2402
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002403/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2404/// the input value to the specified type. If the type must be extended,
2405/// it is extended with unspecified bits. The conversion must not be
2406/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002407const SCEV *
2408ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002409 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002410 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2411 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002412 "Cannot noop or any extend with non-integer arguments!");
2413 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2414 "getNoopOrAnyExtend cannot truncate!");
2415 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2416 return V; // No conversion
2417 return getAnyExtendExpr(V, Ty);
2418}
2419
Dan Gohman467c4302009-05-13 03:46:30 +00002420/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2421/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002422const SCEV *
2423ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002424 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002425 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2426 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002427 "Cannot truncate or noop with non-integer arguments!");
2428 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2429 "getTruncateOrNoop cannot extend!");
2430 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2431 return V; // No conversion
2432 return getTruncateExpr(V, Ty);
2433}
2434
Dan Gohmana334aa72009-06-22 00:31:57 +00002435/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2436/// the types using zero-extension, and then perform a umax operation
2437/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002438const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2439 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002440 const SCEV *PromotedLHS = LHS;
2441 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002442
2443 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2444 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2445 else
2446 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2447
2448 return getUMaxExpr(PromotedLHS, PromotedRHS);
2449}
2450
Dan Gohmanc9759e82009-06-22 15:03:27 +00002451/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2452/// the types using zero-extension, and then perform a umin operation
2453/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002454const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2455 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002456 const SCEV *PromotedLHS = LHS;
2457 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002458
2459 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2460 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2461 else
2462 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2463
2464 return getUMinExpr(PromotedLHS, PromotedRHS);
2465}
2466
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002467/// PushDefUseChildren - Push users of the given Instruction
2468/// onto the given Worklist.
2469static void
2470PushDefUseChildren(Instruction *I,
2471 SmallVectorImpl<Instruction *> &Worklist) {
2472 // Push the def-use children onto the Worklist stack.
2473 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2474 UI != UE; ++UI)
2475 Worklist.push_back(cast<Instruction>(UI));
2476}
2477
2478/// ForgetSymbolicValue - This looks up computed SCEV values for all
2479/// instructions that depend on the given instruction and removes them from
2480/// the Scalars map if they reference SymName. This is used during PHI
2481/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002482void
Dan Gohman85669632010-02-25 06:57:05 +00002483ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002484 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002485 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002486
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002487 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002488 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002489 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002490 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002491 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002492
Dan Gohman5d984912009-12-18 01:14:11 +00002493 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002494 Scalars.find(static_cast<Value *>(I));
2495 if (It != Scalars.end()) {
2496 // Short-circuit the def-use traversal if the symbolic name
2497 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002498 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002499 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002500
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002501 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002502 // structure, it's a PHI that's in the progress of being computed
2503 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2504 // additional loop trip count information isn't going to change anything.
2505 // In the second case, createNodeForPHI will perform the necessary
2506 // updates on its own when it gets to that point. In the third, we do
2507 // want to forget the SCEVUnknown.
2508 if (!isa<PHINode>(I) ||
2509 !isa<SCEVUnknown>(It->second) ||
2510 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002511 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002512 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002513 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002514 }
2515
2516 PushDefUseChildren(I, Worklist);
2517 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002518}
Chris Lattner53e677a2004-04-02 20:23:17 +00002519
2520/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2521/// a loop header, making it a potential recurrence, or it doesn't.
2522///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002523const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002524 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2525 if (L->getHeader() == PN->getParent()) {
2526 // The loop may have multiple entrances or multiple exits; we can analyze
2527 // this phi as an addrec if it has a unique entry value and a unique
2528 // backedge value.
2529 Value *BEValueV = 0, *StartValueV = 0;
2530 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2531 Value *V = PN->getIncomingValue(i);
2532 if (L->contains(PN->getIncomingBlock(i))) {
2533 if (!BEValueV) {
2534 BEValueV = V;
2535 } else if (BEValueV != V) {
2536 BEValueV = 0;
2537 break;
2538 }
2539 } else if (!StartValueV) {
2540 StartValueV = V;
2541 } else if (StartValueV != V) {
2542 StartValueV = 0;
2543 break;
2544 }
2545 }
2546 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002547 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002548 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002549 assert(Scalars.find(PN) == Scalars.end() &&
2550 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002551 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002552
2553 // Using this symbolic name for the PHI, analyze the value coming around
2554 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002555 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002556
2557 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2558 // has a special value for the first iteration of the loop.
2559
2560 // If the value coming around the backedge is an add with the symbolic
2561 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002562 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 // If there is a single occurrence of the symbolic value, replace it
2564 // with a recurrence.
2565 unsigned FoundIndex = Add->getNumOperands();
2566 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2567 if (Add->getOperand(i) == SymbolicName)
2568 if (FoundIndex == e) {
2569 FoundIndex = i;
2570 break;
2571 }
2572
2573 if (FoundIndex != Add->getNumOperands()) {
2574 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002575 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002576 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2577 if (i != FoundIndex)
2578 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002579 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002580
2581 // This is not a valid addrec if the step amount is varying each
2582 // loop iteration, but is not itself an addrec in this loop.
2583 if (Accum->isLoopInvariant(L) ||
2584 (isa<SCEVAddRecExpr>(Accum) &&
2585 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002586 bool HasNUW = false;
2587 bool HasNSW = false;
2588
2589 // If the increment doesn't overflow, then neither the addrec nor
2590 // the post-increment will overflow.
2591 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2592 if (OBO->hasNoUnsignedWrap())
2593 HasNUW = true;
2594 if (OBO->hasNoSignedWrap())
2595 HasNSW = true;
2596 }
2597
Dan Gohman27dead42010-04-12 07:49:36 +00002598 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002599 const SCEV *PHISCEV =
2600 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002601
Dan Gohmana10756e2010-01-21 02:09:26 +00002602 // Since the no-wrap flags are on the increment, they apply to the
2603 // post-incremented value as well.
2604 if (Accum->isLoopInvariant(L))
2605 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2606 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002607
2608 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002609 // to be symbolic. We now need to go back and purge all of the
2610 // entries for the scalars that use the symbolic expression.
2611 ForgetSymbolicName(PN, SymbolicName);
2612 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002613 return PHISCEV;
2614 }
2615 }
Dan Gohman622ed672009-05-04 22:02:23 +00002616 } else if (const SCEVAddRecExpr *AddRec =
2617 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002618 // Otherwise, this could be a loop like this:
2619 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2620 // In this case, j = {1,+,1} and BEValue is j.
2621 // Because the other in-value of i (0) fits the evolution of BEValue
2622 // i really is an addrec evolution.
2623 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002624 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002625
2626 // If StartVal = j.start - j.stride, we can use StartVal as the
2627 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002628 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002629 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002630 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002631 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002632
2633 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002634 // to be symbolic. We now need to go back and purge all of the
2635 // entries for the scalars that use the symbolic expression.
2636 ForgetSymbolicName(PN, SymbolicName);
2637 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002638 return PHISCEV;
2639 }
2640 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002641 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002642 }
Dan Gohman27dead42010-04-12 07:49:36 +00002643 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002644
Dan Gohman85669632010-02-25 06:57:05 +00002645 // If the PHI has a single incoming value, follow that value, unless the
2646 // PHI's incoming blocks are in a different loop, in which case doing so
2647 // risks breaking LCSSA form. Instcombine would normally zap these, but
2648 // it doesn't have DominatorTree information, so it may miss cases.
2649 if (Value *V = PN->hasConstantValue(DT)) {
2650 bool AllSameLoop = true;
2651 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2652 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2653 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2654 AllSameLoop = false;
2655 break;
2656 }
2657 if (AllSameLoop)
2658 return getSCEV(V);
2659 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002660
Chris Lattner53e677a2004-04-02 20:23:17 +00002661 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002662 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002663}
2664
Dan Gohman26466c02009-05-08 20:26:55 +00002665/// createNodeForGEP - Expand GEP instructions into add and multiply
2666/// operations. This allows them to be analyzed by regular SCEV code.
2667///
Dan Gohmand281ed22009-12-18 02:09:29 +00002668const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002669
Dan Gohmand281ed22009-12-18 02:09:29 +00002670 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002671 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002672 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002673 // Don't attempt to analyze GEPs over unsized objects.
2674 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2675 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002676 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002677 gep_type_iterator GTI = gep_type_begin(GEP);
2678 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2679 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002680 I != E; ++I) {
2681 Value *Index = *I;
2682 // Compute the (potentially symbolic) offset in bytes for this index.
2683 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2684 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002685 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002686 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002687 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002688 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002689 } else {
2690 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002691 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002692 // Getelementptr indices are signed.
Dan Gohman8db08df2010-02-02 01:38:49 +00002693 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002694 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002695 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002696 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2697 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2698 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002699 }
2700 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002701 return getAddExpr(getSCEV(Base), TotalOffset,
2702 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002703}
2704
Nick Lewycky83bb0052007-11-22 07:59:40 +00002705/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2706/// guaranteed to end in (at every loop iteration). It is, at the same time,
2707/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2708/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002709uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002710ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002711 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002712 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002713
Dan Gohman622ed672009-05-04 22:02:23 +00002714 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002715 return std::min(GetMinTrailingZeros(T->getOperand()),
2716 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002717
Dan Gohman622ed672009-05-04 22:02:23 +00002718 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002719 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2720 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2721 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002722 }
2723
Dan Gohman622ed672009-05-04 22:02:23 +00002724 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002725 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2726 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2727 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002728 }
2729
Dan Gohman622ed672009-05-04 22:02:23 +00002730 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002731 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002732 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002733 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002734 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002735 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002736 }
2737
Dan Gohman622ed672009-05-04 22:02:23 +00002738 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002739 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002740 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2741 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002742 for (unsigned i = 1, e = M->getNumOperands();
2743 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002744 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002745 BitWidth);
2746 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002747 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002748
Dan Gohman622ed672009-05-04 22:02:23 +00002749 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002750 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002751 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002752 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002753 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002754 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002755 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002756
Dan Gohman622ed672009-05-04 22:02:23 +00002757 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002758 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002759 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002760 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002761 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002762 return MinOpRes;
2763 }
2764
Dan Gohman622ed672009-05-04 22:02:23 +00002765 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002766 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002767 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002768 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002769 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002770 return MinOpRes;
2771 }
2772
Dan Gohman2c364ad2009-06-19 23:29:04 +00002773 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2774 // For a SCEVUnknown, ask ValueTracking.
2775 unsigned BitWidth = getTypeSizeInBits(U->getType());
2776 APInt Mask = APInt::getAllOnesValue(BitWidth);
2777 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2778 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2779 return Zeros.countTrailingOnes();
2780 }
2781
2782 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002783 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002784}
Chris Lattner53e677a2004-04-02 20:23:17 +00002785
Dan Gohman85b05a22009-07-13 21:35:55 +00002786/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2787///
2788ConstantRange
2789ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002790
2791 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002792 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002793
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002794 unsigned BitWidth = getTypeSizeInBits(S->getType());
2795 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2796
2797 // If the value has known zeros, the maximum unsigned value will have those
2798 // known zeros as well.
2799 uint32_t TZ = GetMinTrailingZeros(S);
2800 if (TZ != 0)
2801 ConservativeResult =
2802 ConstantRange(APInt::getMinValue(BitWidth),
2803 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2804
Dan Gohman85b05a22009-07-13 21:35:55 +00002805 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2806 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2807 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2808 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002809 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002810 }
2811
2812 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2813 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2814 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2815 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002816 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002817 }
2818
2819 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2820 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2821 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2822 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002823 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002824 }
2825
2826 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2827 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2828 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2829 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002830 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002831 }
2832
2833 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2834 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2835 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002836 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002837 }
2838
2839 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2840 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002841 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002842 }
2843
2844 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2845 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002846 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002847 }
2848
2849 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2850 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002851 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002852 }
2853
Dan Gohman85b05a22009-07-13 21:35:55 +00002854 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002855 // If there's no unsigned wrap, the value will never be less than its
2856 // initial value.
2857 if (AddRec->hasNoUnsignedWrap())
2858 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00002859 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00002860 ConservativeResult =
Dan Gohmanb64cf892010-04-11 22:13:11 +00002861 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002862
2863 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002864 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002865 const Type *Ty = AddRec->getType();
2866 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002867 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2868 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002869 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2870
2871 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00002872 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002873
2874 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00002875 ConstantRange StepRange = getSignedRange(Step);
2876 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
2877 ConstantRange EndRange =
2878 StartRange.add(MaxBECountRange.multiply(StepRange));
2879
2880 // Check for overflow. This must be done with ConstantRange arithmetic
2881 // because we could be called from within the ScalarEvolution overflow
2882 // checking code.
2883 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
2884 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
2885 ConstantRange ExtMaxBECountRange =
2886 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
2887 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
2888 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
2889 ExtEndRange)
2890 return ConservativeResult;
2891
Dan Gohman85b05a22009-07-13 21:35:55 +00002892 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2893 EndRange.getUnsignedMin());
2894 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2895 EndRange.getUnsignedMax());
2896 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002897 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002898 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002899 }
2900 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002901
2902 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002903 }
2904
2905 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2906 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002907 APInt Mask = APInt::getAllOnesValue(BitWidth);
2908 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2909 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002910 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002911 return ConservativeResult;
2912 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002913 }
2914
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002915 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002916}
2917
Dan Gohman85b05a22009-07-13 21:35:55 +00002918/// getSignedRange - Determine the signed range for a particular SCEV.
2919///
2920ConstantRange
2921ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002922
Dan Gohman85b05a22009-07-13 21:35:55 +00002923 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2924 return ConstantRange(C->getValue()->getValue());
2925
Dan Gohman52fddd32010-01-26 04:40:18 +00002926 unsigned BitWidth = getTypeSizeInBits(S->getType());
2927 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2928
2929 // If the value has known zeros, the maximum signed value will have those
2930 // known zeros as well.
2931 uint32_t TZ = GetMinTrailingZeros(S);
2932 if (TZ != 0)
2933 ConservativeResult =
2934 ConstantRange(APInt::getSignedMinValue(BitWidth),
2935 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2936
Dan Gohman85b05a22009-07-13 21:35:55 +00002937 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2938 ConstantRange X = getSignedRange(Add->getOperand(0));
2939 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2940 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002941 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002942 }
2943
Dan Gohman85b05a22009-07-13 21:35:55 +00002944 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2945 ConstantRange X = getSignedRange(Mul->getOperand(0));
2946 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2947 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002948 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002949 }
2950
Dan Gohman85b05a22009-07-13 21:35:55 +00002951 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2952 ConstantRange X = getSignedRange(SMax->getOperand(0));
2953 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2954 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002955 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002956 }
Dan Gohman62849c02009-06-24 01:05:09 +00002957
Dan Gohman85b05a22009-07-13 21:35:55 +00002958 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2959 ConstantRange X = getSignedRange(UMax->getOperand(0));
2960 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2961 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002962 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002963 }
Dan Gohman62849c02009-06-24 01:05:09 +00002964
Dan Gohman85b05a22009-07-13 21:35:55 +00002965 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2966 ConstantRange X = getSignedRange(UDiv->getLHS());
2967 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00002968 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002969 }
Dan Gohman62849c02009-06-24 01:05:09 +00002970
Dan Gohman85b05a22009-07-13 21:35:55 +00002971 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2972 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002973 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002974 }
2975
2976 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2977 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002978 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002979 }
2980
2981 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2982 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002983 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002984 }
2985
Dan Gohman85b05a22009-07-13 21:35:55 +00002986 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002987 // If there's no signed wrap, and all the operands have the same sign or
2988 // zero, the value won't ever change sign.
2989 if (AddRec->hasNoSignedWrap()) {
2990 bool AllNonNeg = true;
2991 bool AllNonPos = true;
2992 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
2993 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
2994 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
2995 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002996 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00002997 ConservativeResult = ConservativeResult.intersectWith(
2998 ConstantRange(APInt(BitWidth, 0),
2999 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003000 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003001 ConservativeResult = ConservativeResult.intersectWith(
3002 ConstantRange(APInt::getSignedMinValue(BitWidth),
3003 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003004 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003005
3006 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003007 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003008 const Type *Ty = AddRec->getType();
3009 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003010 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3011 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003012 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3013
3014 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003015 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003016
3017 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003018 ConstantRange StepRange = getSignedRange(Step);
3019 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3020 ConstantRange EndRange =
3021 StartRange.add(MaxBECountRange.multiply(StepRange));
3022
3023 // Check for overflow. This must be done with ConstantRange arithmetic
3024 // because we could be called from within the ScalarEvolution overflow
3025 // checking code.
3026 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3027 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3028 ConstantRange ExtMaxBECountRange =
3029 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3030 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3031 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3032 ExtEndRange)
3033 return ConservativeResult;
3034
Dan Gohman85b05a22009-07-13 21:35:55 +00003035 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3036 EndRange.getSignedMin());
3037 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3038 EndRange.getSignedMax());
3039 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003040 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003041 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003042 }
Dan Gohman62849c02009-06-24 01:05:09 +00003043 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003044
3045 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003046 }
3047
Dan Gohman2c364ad2009-06-19 23:29:04 +00003048 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3049 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003050 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003051 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003052 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3053 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003054 return ConservativeResult;
3055 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003056 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003057 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003058 }
3059
Dan Gohman52fddd32010-01-26 04:40:18 +00003060 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003061}
3062
Chris Lattner53e677a2004-04-02 20:23:17 +00003063/// createSCEV - We know that there is no SCEV for the specified value.
3064/// Analyze the expression.
3065///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003066const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003067 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003068 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003069
Dan Gohman6c459a22008-06-22 19:56:46 +00003070 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003071 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003072 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003073
3074 // Don't attempt to analyze instructions in blocks that aren't
3075 // reachable. Such instructions don't matter, and they aren't required
3076 // to obey basic rules for definitions dominating uses which this
3077 // analysis depends on.
3078 if (!DT->isReachableFromEntry(I->getParent()))
3079 return getUnknown(V);
3080 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003081 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003082 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3083 return getConstant(CI);
3084 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003085 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003086 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3087 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003088 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003089 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003090
Dan Gohmanca178902009-07-17 20:47:02 +00003091 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003092 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003093 case Instruction::Add:
3094 // Don't transfer the NSW and NUW bits from the Add instruction to the
3095 // Add expression, because the Instruction may be guarded by control
3096 // flow and the no-overflow bits may not be valid for the expression in
3097 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003098 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003099 getSCEV(U->getOperand(1)));
3100 case Instruction::Mul:
3101 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3102 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003103 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003104 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003105 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003106 return getUDivExpr(getSCEV(U->getOperand(0)),
3107 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003108 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003109 return getMinusSCEV(getSCEV(U->getOperand(0)),
3110 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003111 case Instruction::And:
3112 // For an expression like x&255 that merely masks off the high bits,
3113 // use zext(trunc(x)) as the SCEV expression.
3114 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003115 if (CI->isNullValue())
3116 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003117 if (CI->isAllOnesValue())
3118 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003119 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003120
3121 // Instcombine's ShrinkDemandedConstant may strip bits out of
3122 // constants, obscuring what would otherwise be a low-bits mask.
3123 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3124 // knew about to reconstruct a low-bits mask value.
3125 unsigned LZ = A.countLeadingZeros();
3126 unsigned BitWidth = A.getBitWidth();
3127 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3128 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3129 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3130
3131 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3132
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003133 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003134 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003135 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003136 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003137 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003138 }
3139 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003140
Dan Gohman6c459a22008-06-22 19:56:46 +00003141 case Instruction::Or:
3142 // If the RHS of the Or is a constant, we may have something like:
3143 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3144 // optimizations will transparently handle this case.
3145 //
3146 // In order for this transformation to be safe, the LHS must be of the
3147 // form X*(2^n) and the Or constant must be less than 2^n.
3148 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003149 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003150 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003151 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003152 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3153 // Build a plain add SCEV.
3154 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3155 // If the LHS of the add was an addrec and it has no-wrap flags,
3156 // transfer the no-wrap flags, since an or won't introduce a wrap.
3157 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3158 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3159 if (OldAR->hasNoUnsignedWrap())
3160 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3161 if (OldAR->hasNoSignedWrap())
3162 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3163 }
3164 return S;
3165 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003166 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003167 break;
3168 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003169 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003170 // If the RHS of the xor is a signbit, then this is just an add.
3171 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003172 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003173 return getAddExpr(getSCEV(U->getOperand(0)),
3174 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003175
3176 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003177 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003178 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003179
3180 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3181 // This is a variant of the check for xor with -1, and it handles
3182 // the case where instcombine has trimmed non-demanded bits out
3183 // of an xor with -1.
3184 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3185 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3186 if (BO->getOpcode() == Instruction::And &&
3187 LCI->getValue() == CI->getValue())
3188 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003189 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003190 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003191 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003192 const Type *Z0Ty = Z0->getType();
3193 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3194
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003195 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003196 // mask off the high bits. Complement the operand and
3197 // re-apply the zext.
3198 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3199 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3200
3201 // If C is a single bit, it may be in the sign-bit position
3202 // before the zero-extend. In this case, represent the xor
3203 // using an add, which is equivalent, and re-apply the zext.
3204 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3205 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3206 Trunc.isSignBit())
3207 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3208 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003209 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003210 }
3211 break;
3212
3213 case Instruction::Shl:
3214 // Turn shift left of a constant amount into a multiply.
3215 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003216 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003217
3218 // If the shift count is not less than the bitwidth, the result of
3219 // the shift is undefined. Don't try to analyze it, because the
3220 // resolution chosen here may differ from the resolution chosen in
3221 // other parts of the compiler.
3222 if (SA->getValue().uge(BitWidth))
3223 break;
3224
Owen Andersoneed707b2009-07-24 23:12:02 +00003225 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003226 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003227 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003228 }
3229 break;
3230
Nick Lewycky01eaf802008-07-07 06:15:49 +00003231 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003232 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003233 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003234 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003235
3236 // If the shift count is not less than the bitwidth, the result of
3237 // the shift is undefined. Don't try to analyze it, because the
3238 // resolution chosen here may differ from the resolution chosen in
3239 // other parts of the compiler.
3240 if (SA->getValue().uge(BitWidth))
3241 break;
3242
Owen Andersoneed707b2009-07-24 23:12:02 +00003243 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003244 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003245 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003246 }
3247 break;
3248
Dan Gohman4ee29af2009-04-21 02:26:00 +00003249 case Instruction::AShr:
3250 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3251 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003252 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003253 if (L->getOpcode() == Instruction::Shl &&
3254 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003255 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3256
3257 // If the shift count is not less than the bitwidth, the result of
3258 // the shift is undefined. Don't try to analyze it, because the
3259 // resolution chosen here may differ from the resolution chosen in
3260 // other parts of the compiler.
3261 if (CI->getValue().uge(BitWidth))
3262 break;
3263
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003264 uint64_t Amt = BitWidth - CI->getZExtValue();
3265 if (Amt == BitWidth)
3266 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003267 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003268 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003269 IntegerType::get(getContext(),
3270 Amt)),
3271 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003272 }
3273 break;
3274
Dan Gohman6c459a22008-06-22 19:56:46 +00003275 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003276 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003277
3278 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003279 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003280
3281 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003282 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003283
3284 case Instruction::BitCast:
3285 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003286 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003287 return getSCEV(U->getOperand(0));
3288 break;
3289
Dan Gohman4f8eea82010-02-01 18:27:38 +00003290 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3291 // lead to pointer expressions which cannot safely be expanded to GEPs,
3292 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3293 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003294
Dan Gohman26466c02009-05-08 20:26:55 +00003295 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003296 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003297
Dan Gohman6c459a22008-06-22 19:56:46 +00003298 case Instruction::PHI:
3299 return createNodeForPHI(cast<PHINode>(U));
3300
3301 case Instruction::Select:
3302 // This could be a smax or umax that was lowered earlier.
3303 // Try to recover it.
3304 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3305 Value *LHS = ICI->getOperand(0);
3306 Value *RHS = ICI->getOperand(1);
3307 switch (ICI->getPredicate()) {
3308 case ICmpInst::ICMP_SLT:
3309 case ICmpInst::ICMP_SLE:
3310 std::swap(LHS, RHS);
3311 // fall through
3312 case ICmpInst::ICMP_SGT:
3313 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003314 // a >s b ? a+x : b+x -> smax(a, b)+x
3315 // a >s b ? b+x : a+x -> smin(a, b)+x
3316 if (LHS->getType() == U->getType()) {
3317 const SCEV *LS = getSCEV(LHS);
3318 const SCEV *RS = getSCEV(RHS);
3319 const SCEV *LA = getSCEV(U->getOperand(1));
3320 const SCEV *RA = getSCEV(U->getOperand(2));
3321 const SCEV *LDiff = getMinusSCEV(LA, LS);
3322 const SCEV *RDiff = getMinusSCEV(RA, RS);
3323 if (LDiff == RDiff)
3324 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3325 LDiff = getMinusSCEV(LA, RS);
3326 RDiff = getMinusSCEV(RA, LS);
3327 if (LDiff == RDiff)
3328 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3329 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003330 break;
3331 case ICmpInst::ICMP_ULT:
3332 case ICmpInst::ICMP_ULE:
3333 std::swap(LHS, RHS);
3334 // fall through
3335 case ICmpInst::ICMP_UGT:
3336 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003337 // a >u b ? a+x : b+x -> umax(a, b)+x
3338 // a >u b ? b+x : a+x -> umin(a, b)+x
3339 if (LHS->getType() == U->getType()) {
3340 const SCEV *LS = getSCEV(LHS);
3341 const SCEV *RS = getSCEV(RHS);
3342 const SCEV *LA = getSCEV(U->getOperand(1));
3343 const SCEV *RA = getSCEV(U->getOperand(2));
3344 const SCEV *LDiff = getMinusSCEV(LA, LS);
3345 const SCEV *RDiff = getMinusSCEV(RA, RS);
3346 if (LDiff == RDiff)
3347 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3348 LDiff = getMinusSCEV(LA, RS);
3349 RDiff = getMinusSCEV(RA, LS);
3350 if (LDiff == RDiff)
3351 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3352 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003353 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003354 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003355 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3356 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003357 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003358 cast<ConstantInt>(RHS)->isZero()) {
3359 const SCEV *One = getConstant(LHS->getType(), 1);
3360 const SCEV *LS = getSCEV(LHS);
3361 const SCEV *LA = getSCEV(U->getOperand(1));
3362 const SCEV *RA = getSCEV(U->getOperand(2));
3363 const SCEV *LDiff = getMinusSCEV(LA, LS);
3364 const SCEV *RDiff = getMinusSCEV(RA, One);
3365 if (LDiff == RDiff)
3366 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3367 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003368 break;
3369 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003370 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3371 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003372 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003373 cast<ConstantInt>(RHS)->isZero()) {
3374 const SCEV *One = getConstant(LHS->getType(), 1);
3375 const SCEV *LS = getSCEV(LHS);
3376 const SCEV *LA = getSCEV(U->getOperand(1));
3377 const SCEV *RA = getSCEV(U->getOperand(2));
3378 const SCEV *LDiff = getMinusSCEV(LA, One);
3379 const SCEV *RDiff = getMinusSCEV(RA, LS);
3380 if (LDiff == RDiff)
3381 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3382 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003383 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003384 default:
3385 break;
3386 }
3387 }
3388
3389 default: // We cannot analyze this expression.
3390 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003391 }
3392
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003393 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003394}
3395
3396
3397
3398//===----------------------------------------------------------------------===//
3399// Iteration Count Computation Code
3400//
3401
Dan Gohman46bdfb02009-02-24 18:55:53 +00003402/// getBackedgeTakenCount - If the specified loop has a predictable
3403/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3404/// object. The backedge-taken count is the number of times the loop header
3405/// will be branched to from within the loop. This is one less than the
3406/// trip count of the loop, since it doesn't count the first iteration,
3407/// when the header is branched to from outside the loop.
3408///
3409/// Note that it is not valid to call this method on a loop without a
3410/// loop-invariant backedge-taken count (see
3411/// hasLoopInvariantBackedgeTakenCount).
3412///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003413const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003414 return getBackedgeTakenInfo(L).Exact;
3415}
3416
3417/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3418/// return the least SCEV value that is known never to be less than the
3419/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003420const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003421 return getBackedgeTakenInfo(L).Max;
3422}
3423
Dan Gohman59ae6b92009-07-08 19:23:34 +00003424/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3425/// onto the given Worklist.
3426static void
3427PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3428 BasicBlock *Header = L->getHeader();
3429
3430 // Push all Loop-header PHIs onto the Worklist stack.
3431 for (BasicBlock::iterator I = Header->begin();
3432 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3433 Worklist.push_back(PN);
3434}
3435
Dan Gohmana1af7572009-04-30 20:47:05 +00003436const ScalarEvolution::BackedgeTakenInfo &
3437ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003438 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003439 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003440 // update the value. The temporary CouldNotCompute value tells SCEV
3441 // code elsewhere that it shouldn't attempt to request a new
3442 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003443 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003444 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3445 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003446 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3447 if (BECount.Exact != getCouldNotCompute()) {
3448 assert(BECount.Exact->isLoopInvariant(L) &&
3449 BECount.Max->isLoopInvariant(L) &&
3450 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003451 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003452
Dan Gohman01ecca22009-04-27 20:16:15 +00003453 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003454 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003455 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003456 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003457 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003458 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003459 if (isa<PHINode>(L->getHeader()->begin()))
3460 // Only count loops that have phi nodes as not being computable.
3461 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003462 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003463
3464 // Now that we know more about the trip count for this loop, forget any
3465 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003466 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003467 // information. This is similar to the code in forgetLoop, except that
3468 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003469 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003470 SmallVector<Instruction *, 16> Worklist;
3471 PushLoopPHIs(L, Worklist);
3472
3473 SmallPtrSet<Instruction *, 8> Visited;
3474 while (!Worklist.empty()) {
3475 Instruction *I = Worklist.pop_back_val();
3476 if (!Visited.insert(I)) continue;
3477
Dan Gohman5d984912009-12-18 01:14:11 +00003478 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003479 Scalars.find(static_cast<Value *>(I));
3480 if (It != Scalars.end()) {
3481 // SCEVUnknown for a PHI either means that it has an unrecognized
3482 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003483 // by createNodeForPHI. In the former case, additional loop trip
3484 // count information isn't going to change anything. In the later
3485 // case, createNodeForPHI will perform the necessary updates on its
3486 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003487 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3488 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003489 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003490 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003491 if (PHINode *PN = dyn_cast<PHINode>(I))
3492 ConstantEvolutionLoopExitValue.erase(PN);
3493 }
3494
3495 PushDefUseChildren(I, Worklist);
3496 }
3497 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003498 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003499 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003500}
3501
Dan Gohman4c7279a2009-10-31 15:04:55 +00003502/// forgetLoop - This method should be called by the client when it has
3503/// changed a loop in a way that may effect ScalarEvolution's ability to
3504/// compute a trip count, or if the loop is deleted.
3505void ScalarEvolution::forgetLoop(const Loop *L) {
3506 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003507 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003508
Dan Gohman4c7279a2009-10-31 15:04:55 +00003509 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003510 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003511 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003512
Dan Gohman59ae6b92009-07-08 19:23:34 +00003513 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003514 while (!Worklist.empty()) {
3515 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003516 if (!Visited.insert(I)) continue;
3517
Dan Gohman5d984912009-12-18 01:14:11 +00003518 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003519 Scalars.find(static_cast<Value *>(I));
3520 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003521 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003522 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003523 if (PHINode *PN = dyn_cast<PHINode>(I))
3524 ConstantEvolutionLoopExitValue.erase(PN);
3525 }
3526
3527 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003528 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003529}
3530
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003531/// forgetValue - This method should be called by the client when it has
3532/// changed a value in a way that may effect its value, or which may
3533/// disconnect it from a def-use chain linking it to a loop.
3534void ScalarEvolution::forgetValue(Value *V) {
3535 Instruction *I = dyn_cast<Instruction>(V);
3536 if (!I) return;
3537
3538 // Drop information about expressions based on loop-header PHIs.
3539 SmallVector<Instruction *, 16> Worklist;
3540 Worklist.push_back(I);
3541
3542 SmallPtrSet<Instruction *, 8> Visited;
3543 while (!Worklist.empty()) {
3544 I = Worklist.pop_back_val();
3545 if (!Visited.insert(I)) continue;
3546
3547 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3548 Scalars.find(static_cast<Value *>(I));
3549 if (It != Scalars.end()) {
3550 ValuesAtScopes.erase(It->second);
3551 Scalars.erase(It);
3552 if (PHINode *PN = dyn_cast<PHINode>(I))
3553 ConstantEvolutionLoopExitValue.erase(PN);
3554 }
3555
3556 PushDefUseChildren(I, Worklist);
3557 }
3558}
3559
Dan Gohman46bdfb02009-02-24 18:55:53 +00003560/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3561/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003562ScalarEvolution::BackedgeTakenInfo
3563ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003564 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003565 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003566
Dan Gohmana334aa72009-06-22 00:31:57 +00003567 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003568 const SCEV *BECount = getCouldNotCompute();
3569 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003570 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003571 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3572 BackedgeTakenInfo NewBTI =
3573 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003574
Dan Gohman1c343752009-06-27 21:21:31 +00003575 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003576 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003577 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003578 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003579 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003580 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003581 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003582 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003583 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003584 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003585 }
Dan Gohman1c343752009-06-27 21:21:31 +00003586 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003587 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003588 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003589 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003590 }
3591
3592 return BackedgeTakenInfo(BECount, MaxBECount);
3593}
3594
3595/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3596/// of the specified loop will execute if it exits via the specified block.
3597ScalarEvolution::BackedgeTakenInfo
3598ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3599 BasicBlock *ExitingBlock) {
3600
3601 // Okay, we've chosen an exiting block. See what condition causes us to
3602 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003603 //
3604 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003605 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003606 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003607 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003608
Chris Lattner8b0e3602007-01-07 02:24:26 +00003609 // At this point, we know we have a conditional branch that determines whether
3610 // the loop is exited. However, we don't know if the branch is executed each
3611 // time through the loop. If not, then the execution count of the branch will
3612 // not be equal to the trip count of the loop.
3613 //
3614 // Currently we check for this by checking to see if the Exit branch goes to
3615 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003616 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003617 // loop header. This is common for un-rotated loops.
3618 //
3619 // If both of those tests fail, walk up the unique predecessor chain to the
3620 // header, stopping if there is an edge that doesn't exit the loop. If the
3621 // header is reached, the execution count of the branch will be equal to the
3622 // trip count of the loop.
3623 //
3624 // More extensive analysis could be done to handle more cases here.
3625 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003626 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003627 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003628 ExitBr->getParent() != L->getHeader()) {
3629 // The simple checks failed, try climbing the unique predecessor chain
3630 // up to the header.
3631 bool Ok = false;
3632 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3633 BasicBlock *Pred = BB->getUniquePredecessor();
3634 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003635 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003636 TerminatorInst *PredTerm = Pred->getTerminator();
3637 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3638 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3639 if (PredSucc == BB)
3640 continue;
3641 // If the predecessor has a successor that isn't BB and isn't
3642 // outside the loop, assume the worst.
3643 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003644 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003645 }
3646 if (Pred == L->getHeader()) {
3647 Ok = true;
3648 break;
3649 }
3650 BB = Pred;
3651 }
3652 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003653 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003654 }
3655
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003656 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003657 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3658 ExitBr->getSuccessor(0),
3659 ExitBr->getSuccessor(1));
3660}
3661
3662/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3663/// backedge of the specified loop will execute if its exit condition
3664/// were a conditional branch of ExitCond, TBB, and FBB.
3665ScalarEvolution::BackedgeTakenInfo
3666ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3667 Value *ExitCond,
3668 BasicBlock *TBB,
3669 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003670 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003671 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3672 if (BO->getOpcode() == Instruction::And) {
3673 // Recurse on the operands of the and.
3674 BackedgeTakenInfo BTI0 =
3675 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3676 BackedgeTakenInfo BTI1 =
3677 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003678 const SCEV *BECount = getCouldNotCompute();
3679 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003680 if (L->contains(TBB)) {
3681 // Both conditions must be true for the loop to continue executing.
3682 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003683 if (BTI0.Exact == getCouldNotCompute() ||
3684 BTI1.Exact == getCouldNotCompute())
3685 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003686 else
3687 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003688 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003689 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003690 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003691 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003692 else
3693 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003694 } else {
3695 // Both conditions must be true for the loop to exit.
3696 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003697 if (BTI0.Exact != getCouldNotCompute() &&
3698 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003699 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003700 if (BTI0.Max != getCouldNotCompute() &&
3701 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003702 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3703 }
3704
3705 return BackedgeTakenInfo(BECount, MaxBECount);
3706 }
3707 if (BO->getOpcode() == Instruction::Or) {
3708 // Recurse on the operands of the or.
3709 BackedgeTakenInfo BTI0 =
3710 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3711 BackedgeTakenInfo BTI1 =
3712 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003713 const SCEV *BECount = getCouldNotCompute();
3714 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003715 if (L->contains(FBB)) {
3716 // Both conditions must be false for the loop to continue executing.
3717 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003718 if (BTI0.Exact == getCouldNotCompute() ||
3719 BTI1.Exact == getCouldNotCompute())
3720 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003721 else
3722 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003723 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003724 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003725 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003726 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003727 else
3728 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003729 } else {
3730 // Both conditions must be false for the loop to exit.
3731 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003732 if (BTI0.Exact != getCouldNotCompute() &&
3733 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003734 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003735 if (BTI0.Max != getCouldNotCompute() &&
3736 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003737 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3738 }
3739
3740 return BackedgeTakenInfo(BECount, MaxBECount);
3741 }
3742 }
3743
3744 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003745 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003746 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3747 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748
Dan Gohman00cb5b72010-02-19 18:12:07 +00003749 // Check for a constant condition. These are normally stripped out by
3750 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3751 // preserve the CFG and is temporarily leaving constant conditions
3752 // in place.
3753 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3754 if (L->contains(FBB) == !CI->getZExtValue())
3755 // The backedge is always taken.
3756 return getCouldNotCompute();
3757 else
3758 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003759 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003760 }
3761
Eli Friedman361e54d2009-05-09 12:32:42 +00003762 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003763 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3764}
3765
3766/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3767/// backedge of the specified loop will execute if its exit condition
3768/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3769ScalarEvolution::BackedgeTakenInfo
3770ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3771 ICmpInst *ExitCond,
3772 BasicBlock *TBB,
3773 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003774
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 // If the condition was exit on true, convert the condition to exit on false
3776 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003777 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003778 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003779 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003780 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003781
3782 // Handle common loops like: for (X = "string"; *X; ++X)
3783 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3784 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003785 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003786 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003787 if (ItCnt.hasAnyInfo())
3788 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003789 }
3790
Dan Gohman0bba49c2009-07-07 17:06:11 +00003791 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3792 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003793
3794 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003795 LHS = getSCEVAtScope(LHS, L);
3796 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003797
Dan Gohman64a845e2009-06-24 04:48:43 +00003798 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003799 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003800 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3801 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003802 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003803 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003804 }
3805
Dan Gohman03557dc2010-05-03 16:35:17 +00003806 // Simplify the operands before analyzing them.
3807 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3808
Chris Lattner53e677a2004-04-02 20:23:17 +00003809 // If we have a comparison of a chrec against a constant, try to use value
3810 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003811 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3812 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003813 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003814 // Form the constant range.
3815 ConstantRange CompRange(
3816 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003817
Dan Gohman0bba49c2009-07-07 17:06:11 +00003818 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003819 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003820 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003821
Chris Lattner53e677a2004-04-02 20:23:17 +00003822 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003823 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003824 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003825 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3826 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003827 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003828 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003829 case ICmpInst::ICMP_EQ: { // while (X == Y)
3830 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003831 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3832 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003833 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003834 }
3835 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003836 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3837 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003838 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003839 }
3840 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003841 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3842 getNotSCEV(RHS), L, true);
3843 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003844 break;
3845 }
3846 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003847 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3848 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003849 break;
3850 }
3851 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003852 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3853 getNotSCEV(RHS), L, false);
3854 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003855 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003856 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003857 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003858#if 0
David Greene25e0e872009-12-23 22:18:14 +00003859 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003860 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003861 dbgs() << "[unsigned] ";
3862 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003863 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003864 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003865#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003866 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003867 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003868 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003869 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003870}
3871
Chris Lattner673e02b2004-10-12 01:49:27 +00003872static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003873EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3874 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003875 const SCEV *InVal = SE.getConstant(C);
3876 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003877 assert(isa<SCEVConstant>(Val) &&
3878 "Evaluation of SCEV at constant didn't fold correctly?");
3879 return cast<SCEVConstant>(Val)->getValue();
3880}
3881
3882/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3883/// and a GEP expression (missing the pointer index) indexing into it, return
3884/// the addressed element of the initializer or null if the index expression is
3885/// invalid.
3886static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003887GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003888 const std::vector<ConstantInt*> &Indices) {
3889 Constant *Init = GV->getInitializer();
3890 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003891 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003892 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3893 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3894 Init = cast<Constant>(CS->getOperand(Idx));
3895 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3896 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3897 Init = cast<Constant>(CA->getOperand(Idx));
3898 } else if (isa<ConstantAggregateZero>(Init)) {
3899 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3900 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003901 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003902 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3903 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003904 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003905 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003906 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003907 }
3908 return 0;
3909 } else {
3910 return 0; // Unknown initializer type
3911 }
3912 }
3913 return Init;
3914}
3915
Dan Gohman46bdfb02009-02-24 18:55:53 +00003916/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3917/// 'icmp op load X, cst', try to see if we can compute the backedge
3918/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003919ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00003920ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3921 LoadInst *LI,
3922 Constant *RHS,
3923 const Loop *L,
3924 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003925 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003926
3927 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003928 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00003929 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003930 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003931
3932 // Make sure that it is really a constant global we are gepping, with an
3933 // initializer, and make sure the first IDX is really 0.
3934 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003935 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003936 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3937 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003938 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003939
3940 // Okay, we allow one non-constant index into the GEP instruction.
3941 Value *VarIdx = 0;
3942 std::vector<ConstantInt*> Indexes;
3943 unsigned VarIdxNum = 0;
3944 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3945 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3946 Indexes.push_back(CI);
3947 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003948 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003949 VarIdx = GEP->getOperand(i);
3950 VarIdxNum = i-2;
3951 Indexes.push_back(0);
3952 }
3953
3954 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3955 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003956 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003957 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003958
3959 // We can only recognize very limited forms of loop index expressions, in
3960 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003961 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003962 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3963 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3964 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003965 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003966
3967 unsigned MaxSteps = MaxBruteForceIterations;
3968 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003969 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003970 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003971 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003972
3973 // Form the GEP offset.
3974 Indexes[VarIdxNum] = Val;
3975
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003976 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003977 if (Result == 0) break; // Cannot compute!
3978
3979 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003980 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003981 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003982 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003983#if 0
David Greene25e0e872009-12-23 22:18:14 +00003984 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003985 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3986 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003987#endif
3988 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003989 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003990 }
3991 }
Dan Gohman1c343752009-06-27 21:21:31 +00003992 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003993}
3994
3995
Chris Lattner3221ad02004-04-17 22:58:41 +00003996/// CanConstantFold - Return true if we can constant fold an instruction of the
3997/// specified type, assuming that all operands were constants.
3998static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003999 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004000 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4001 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004002
Chris Lattner3221ad02004-04-17 22:58:41 +00004003 if (const CallInst *CI = dyn_cast<CallInst>(I))
4004 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004005 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004006 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004007}
4008
Chris Lattner3221ad02004-04-17 22:58:41 +00004009/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4010/// in the loop that V is derived from. We allow arbitrary operations along the
4011/// way, but the operands of an operation must either be constants or a value
4012/// derived from a constant PHI. If this expression does not fit with these
4013/// constraints, return null.
4014static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4015 // If this is not an instruction, or if this is an instruction outside of the
4016 // loop, it can't be derived from a loop PHI.
4017 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004018 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004019
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004020 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004021 if (L->getHeader() == I->getParent())
4022 return PN;
4023 else
4024 // We don't currently keep track of the control flow needed to evaluate
4025 // PHIs, so we cannot handle PHIs inside of loops.
4026 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004027 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004028
4029 // If we won't be able to constant fold this expression even if the operands
4030 // are constants, return early.
4031 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004032
Chris Lattner3221ad02004-04-17 22:58:41 +00004033 // Otherwise, we can evaluate this instruction if all of its operands are
4034 // constant or derived from a PHI node themselves.
4035 PHINode *PHI = 0;
4036 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4037 if (!(isa<Constant>(I->getOperand(Op)) ||
4038 isa<GlobalValue>(I->getOperand(Op)))) {
4039 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4040 if (P == 0) return 0; // Not evolving from PHI
4041 if (PHI == 0)
4042 PHI = P;
4043 else if (PHI != P)
4044 return 0; // Evolving from multiple different PHIs.
4045 }
4046
4047 // This is a expression evolving from a constant PHI!
4048 return PHI;
4049}
4050
4051/// EvaluateExpression - Given an expression that passes the
4052/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4053/// in the loop has the value PHIVal. If we can't fold this expression for some
4054/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004055static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4056 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004057 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004058 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00004059 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00004060 Instruction *I = cast<Instruction>(V);
4061
4062 std::vector<Constant*> Operands;
4063 Operands.resize(I->getNumOperands());
4064
4065 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004066 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004067 if (Operands[i] == 0) return 0;
4068 }
4069
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004070 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004071 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004072 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004073 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004074 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004075}
4076
4077/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4078/// in the header of its containing loop, we know the loop executes a
4079/// constant number of times, and the PHI node is just a recurrence
4080/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004081Constant *
4082ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004083 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004084 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004085 std::map<PHINode*, Constant*>::iterator I =
4086 ConstantEvolutionLoopExitValue.find(PN);
4087 if (I != ConstantEvolutionLoopExitValue.end())
4088 return I->second;
4089
Dan Gohmane0567812010-04-08 23:03:40 +00004090 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004091 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4092
4093 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4094
4095 // Since the loop is canonicalized, the PHI node must have two entries. One
4096 // entry must be a constant (coming in from outside of the loop), and the
4097 // second must be derived from the same PHI.
4098 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4099 Constant *StartCST =
4100 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4101 if (StartCST == 0)
4102 return RetVal = 0; // Must be a constant.
4103
4104 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4105 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4106 if (PN2 != PN)
4107 return RetVal = 0; // Not derived from same PHI.
4108
4109 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004110 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004111 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004112
Dan Gohman46bdfb02009-02-24 18:55:53 +00004113 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004114 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004115 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4116 if (IterationNum == NumIterations)
4117 return RetVal = PHIVal; // Got exit value!
4118
4119 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004120 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004121 if (NextPHI == PHIVal)
4122 return RetVal = NextPHI; // Stopped evolving!
4123 if (NextPHI == 0)
4124 return 0; // Couldn't evaluate!
4125 PHIVal = NextPHI;
4126 }
4127}
4128
Dan Gohman07ad19b2009-07-27 16:09:48 +00004129/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004130/// constant number of times (the condition evolves only from constants),
4131/// try to evaluate a few iterations of the loop until we get the exit
4132/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004133/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004134const SCEV *
4135ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4136 Value *Cond,
4137 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004138 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004139 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004140
4141 // Since the loop is canonicalized, the PHI node must have two entries. One
4142 // entry must be a constant (coming in from outside of the loop), and the
4143 // second must be derived from the same PHI.
4144 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4145 Constant *StartCST =
4146 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004147 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004148
4149 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4150 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004151 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004152
4153 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4154 // the loop symbolically to determine when the condition gets a value of
4155 // "ExitWhen".
4156 unsigned IterationNum = 0;
4157 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4158 for (Constant *PHIVal = StartCST;
4159 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004160 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004161 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004162
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004163 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004164 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004165
Reid Spencere8019bb2007-03-01 07:25:48 +00004166 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004167 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004168 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004169 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004170
Chris Lattner3221ad02004-04-17 22:58:41 +00004171 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004172 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004173 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004174 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004175 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004176 }
4177
4178 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004179 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004180}
4181
Dan Gohmane7125f42009-09-03 15:00:26 +00004182/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004183/// at the specified scope in the program. The L value specifies a loop
4184/// nest to evaluate the expression at, where null is the top-level or a
4185/// specified loop is immediately inside of the loop.
4186///
4187/// This method can be used to compute the exit value for a variable defined
4188/// in a loop by querying what the value will hold in the parent loop.
4189///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004190/// In the case that a relevant loop exit value cannot be computed, the
4191/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004192const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004193 // Check to see if we've folded this expression at this loop before.
4194 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4195 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4196 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4197 if (!Pair.second)
4198 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004199
Dan Gohman42214892009-08-31 21:15:23 +00004200 // Otherwise compute it.
4201 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004202 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004203 return C;
4204}
4205
4206const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004207 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004208
Nick Lewycky3e630762008-02-20 06:48:22 +00004209 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004210 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004211 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004212 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004213 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004214 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4215 if (PHINode *PN = dyn_cast<PHINode>(I))
4216 if (PN->getParent() == LI->getHeader()) {
4217 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004218 // to see if the loop that contains it has a known backedge-taken
4219 // count. If so, we may be able to force computation of the exit
4220 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004221 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004222 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004223 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004224 // Okay, we know how many times the containing loop executes. If
4225 // this is a constant evolving PHI node, get the final value at
4226 // the specified iteration number.
4227 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004228 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004229 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004230 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004231 }
4232 }
4233
Reid Spencer09906f32006-12-04 21:33:23 +00004234 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004235 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004236 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004237 // result. This is particularly useful for computing loop exit values.
4238 if (CanConstantFold(I)) {
4239 std::vector<Constant*> Operands;
4240 Operands.reserve(I->getNumOperands());
4241 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4242 Value *Op = I->getOperand(i);
4243 if (Constant *C = dyn_cast<Constant>(Op)) {
4244 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004245 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004246 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004247 // non-integer and non-pointer, don't even try to analyze them
4248 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004249 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004250 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004251
Dan Gohman5d984912009-12-18 01:14:11 +00004252 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004254 Constant *C = SC->getValue();
4255 if (C->getType() != Op->getType())
4256 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4257 Op->getType(),
4258 false),
4259 C, Op->getType());
4260 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004261 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004262 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4263 if (C->getType() != Op->getType())
4264 C =
4265 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4266 Op->getType(),
4267 false),
4268 C, Op->getType());
4269 Operands.push_back(C);
4270 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004271 return V;
4272 } else {
4273 return V;
4274 }
4275 }
4276 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004277
Dan Gohmane177c9a2010-02-24 19:31:47 +00004278 Constant *C = 0;
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004279 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4280 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004281 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004282 else
4283 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004284 &Operands[0], Operands.size(), TD);
Dan Gohmane177c9a2010-02-24 19:31:47 +00004285 if (C)
4286 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004287 }
4288 }
4289
4290 // This is some other type of SCEVUnknown, just return it.
4291 return V;
4292 }
4293
Dan Gohman622ed672009-05-04 22:02:23 +00004294 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004295 // Avoid performing the look-up in the common case where the specified
4296 // expression has no loop-variant portions.
4297 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004298 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004299 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004300 // Okay, at least one of these operands is loop variant but might be
4301 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004302 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4303 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004304 NewOps.push_back(OpAtScope);
4305
4306 for (++i; i != e; ++i) {
4307 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004308 NewOps.push_back(OpAtScope);
4309 }
4310 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004311 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004312 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004313 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004314 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004315 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004316 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004317 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004318 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004319 }
4320 }
4321 // If we got here, all operands are loop invariant.
4322 return Comm;
4323 }
4324
Dan Gohman622ed672009-05-04 22:02:23 +00004325 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004326 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4327 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004328 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4329 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004330 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004331 }
4332
4333 // If this is a loop recurrence for a loop that does not contain L, then we
4334 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004335 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004336 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004337 // To evaluate this recurrence, we need to know how many times the AddRec
4338 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004339 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004340 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004341
Eli Friedmanb42a6262008-08-04 23:49:06 +00004342 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004343 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004344 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004345 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004346 }
4347
Dan Gohman622ed672009-05-04 22:02:23 +00004348 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004349 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004350 if (Op == Cast->getOperand())
4351 return Cast; // must be loop invariant
4352 return getZeroExtendExpr(Op, Cast->getType());
4353 }
4354
Dan Gohman622ed672009-05-04 22:02:23 +00004355 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004356 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004357 if (Op == Cast->getOperand())
4358 return Cast; // must be loop invariant
4359 return getSignExtendExpr(Op, Cast->getType());
4360 }
4361
Dan Gohman622ed672009-05-04 22:02:23 +00004362 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004363 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004364 if (Op == Cast->getOperand())
4365 return Cast; // must be loop invariant
4366 return getTruncateExpr(Op, Cast->getType());
4367 }
4368
Torok Edwinc23197a2009-07-14 16:55:14 +00004369 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004370 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004371}
4372
Dan Gohman66a7e852009-05-08 20:38:54 +00004373/// getSCEVAtScope - This is a convenience function which does
4374/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004375const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004376 return getSCEVAtScope(getSCEV(V), L);
4377}
4378
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004379/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4380/// following equation:
4381///
4382/// A * X = B (mod N)
4383///
4384/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4385/// A and B isn't important.
4386///
4387/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004388static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004389 ScalarEvolution &SE) {
4390 uint32_t BW = A.getBitWidth();
4391 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4392 assert(A != 0 && "A must be non-zero.");
4393
4394 // 1. D = gcd(A, N)
4395 //
4396 // The gcd of A and N may have only one prime factor: 2. The number of
4397 // trailing zeros in A is its multiplicity
4398 uint32_t Mult2 = A.countTrailingZeros();
4399 // D = 2^Mult2
4400
4401 // 2. Check if B is divisible by D.
4402 //
4403 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4404 // is not less than multiplicity of this prime factor for D.
4405 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004406 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004407
4408 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4409 // modulo (N / D).
4410 //
4411 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4412 // bit width during computations.
4413 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4414 APInt Mod(BW + 1, 0);
4415 Mod.set(BW - Mult2); // Mod = N / D
4416 APInt I = AD.multiplicativeInverse(Mod);
4417
4418 // 4. Compute the minimum unsigned root of the equation:
4419 // I * (B / D) mod (N / D)
4420 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4421
4422 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4423 // bits.
4424 return SE.getConstant(Result.trunc(BW));
4425}
Chris Lattner53e677a2004-04-02 20:23:17 +00004426
4427/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4428/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4429/// might be the same) or two SCEVCouldNotCompute objects.
4430///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004431static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004432SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004433 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004434 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4435 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4436 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004437
Chris Lattner53e677a2004-04-02 20:23:17 +00004438 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004439 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004440 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004441 return std::make_pair(CNC, CNC);
4442 }
4443
Reid Spencere8019bb2007-03-01 07:25:48 +00004444 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004445 const APInt &L = LC->getValue()->getValue();
4446 const APInt &M = MC->getValue()->getValue();
4447 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004448 APInt Two(BitWidth, 2);
4449 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004450
Dan Gohman64a845e2009-06-24 04:48:43 +00004451 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004452 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004453 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004454 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4455 // The B coefficient is M-N/2
4456 APInt B(M);
4457 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004458
Reid Spencere8019bb2007-03-01 07:25:48 +00004459 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004460 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004461
Reid Spencere8019bb2007-03-01 07:25:48 +00004462 // Compute the B^2-4ac term.
4463 APInt SqrtTerm(B);
4464 SqrtTerm *= B;
4465 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004466
Reid Spencere8019bb2007-03-01 07:25:48 +00004467 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4468 // integer value or else APInt::sqrt() will assert.
4469 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004470
Dan Gohman64a845e2009-06-24 04:48:43 +00004471 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004472 // The divisions must be performed as signed divisions.
4473 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004474 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004475 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004476 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004477 return std::make_pair(CNC, CNC);
4478 }
4479
Owen Andersone922c022009-07-22 00:24:57 +00004480 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004481
4482 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004483 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004484 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004485 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004486
Dan Gohman64a845e2009-06-24 04:48:43 +00004487 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004488 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004489 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004490}
4491
4492/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004493/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004494ScalarEvolution::BackedgeTakenInfo
4495ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004496 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004497 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004498 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004499 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004500 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004501 }
4502
Dan Gohman35738ac2009-05-04 22:30:44 +00004503 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004504 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004505 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004506
4507 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004508 // If this is an affine expression, the execution count of this branch is
4509 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004510 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004511 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004512 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004513 // equivalent to:
4514 //
4515 // Step*N = -Start (mod 2^BW)
4516 //
4517 // where BW is the common bit width of Start and Step.
4518
Chris Lattner53e677a2004-04-02 20:23:17 +00004519 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004520 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4521 L->getParentLoop());
4522 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4523 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004524
Dan Gohman622ed672009-05-04 22:02:23 +00004525 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004526 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004527
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004528 // First, handle unitary steps.
4529 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004530 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004531 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4532 return Start; // N = Start (as unsigned)
4533
4534 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004535 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004536 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004537 -StartC->getValue()->getValue(),
4538 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004539 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004540 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004541 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4542 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004543 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004544 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004545 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4546 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004547 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004548#if 0
David Greene25e0e872009-12-23 22:18:14 +00004549 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004550 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004551#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004552 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004553 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004554 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004555 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004556 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004557 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004558
Chris Lattner53e677a2004-04-02 20:23:17 +00004559 // We can only use this value if the chrec ends up with an exact zero
4560 // value at this index. When solving for "X*X != 5", for example, we
4561 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004562 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004563 if (Val->isZero())
4564 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004565 }
4566 }
4567 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004568
Dan Gohman1c343752009-06-27 21:21:31 +00004569 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004570}
4571
4572/// HowFarToNonZero - Return the number of times a backedge checking the
4573/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004574/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004575ScalarEvolution::BackedgeTakenInfo
4576ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004577 // Loops that look like: while (X == 0) are very strange indeed. We don't
4578 // handle them yet except for the trivial case. This could be expanded in the
4579 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004580
Chris Lattner53e677a2004-04-02 20:23:17 +00004581 // If the value is a constant, check to see if it is known to be non-zero
4582 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004583 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004584 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004585 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004586 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004587 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004588
Chris Lattner53e677a2004-04-02 20:23:17 +00004589 // We could implement others, but I really doubt anyone writes loops like
4590 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004591 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004592}
4593
Dan Gohman859b4822009-05-18 15:36:09 +00004594/// getLoopPredecessor - If the given loop's header has exactly one unique
4595/// predecessor outside the loop, return it. Otherwise return null.
Dan Gohman2c93e392010-04-14 16:08:56 +00004596/// This is less strict that the loop "preheader" concept, which requires
4597/// the predecessor to have only one single successor.
Dan Gohman859b4822009-05-18 15:36:09 +00004598///
4599BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4600 BasicBlock *Header = L->getHeader();
4601 BasicBlock *Pred = 0;
4602 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4603 PI != E; ++PI)
4604 if (!L->contains(*PI)) {
4605 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4606 Pred = *PI;
4607 }
4608 return Pred;
4609}
4610
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004611/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4612/// (which may not be an immediate predecessor) which has exactly one
4613/// successor from which BB is reachable, or null if no such block is
4614/// found.
4615///
Dan Gohman005752b2010-04-15 16:19:08 +00004616std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004617ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004618 // If the block has a unique predecessor, then there is no path from the
4619 // predecessor to the block that does not go through the direct edge
4620 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004621 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004622 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004623
4624 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004625 // If the header has a unique predecessor outside the loop, it must be
4626 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004627 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman005752b2010-04-15 16:19:08 +00004628 return std::make_pair(getLoopPredecessor(L), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004629
Dan Gohman005752b2010-04-15 16:19:08 +00004630 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004631}
4632
Dan Gohman763bad12009-06-20 00:35:32 +00004633/// HasSameValue - SCEV structural equivalence is usually sufficient for
4634/// testing whether two expressions are equal, however for the purposes of
4635/// looking for a condition guarding a loop, it can be useful to be a little
4636/// more general, since a front-end may have replicated the controlling
4637/// expression.
4638///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004639static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004640 // Quick check to see if they are the same SCEV.
4641 if (A == B) return true;
4642
4643 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4644 // two different instructions with the same value. Check for this case.
4645 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4646 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4647 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4648 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004649 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004650 return true;
4651
4652 // Otherwise assume they may have a different value.
4653 return false;
4654}
4655
Dan Gohmane9796502010-04-24 01:28:42 +00004656/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4657/// predicate Pred. Return true iff any changes were made.
4658///
4659bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4660 const SCEV *&LHS, const SCEV *&RHS) {
4661 bool Changed = false;
4662
4663 // Canonicalize a constant to the right side.
4664 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4665 // Check for both operands constant.
4666 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4667 if (ConstantExpr::getICmp(Pred,
4668 LHSC->getValue(),
4669 RHSC->getValue())->isNullValue())
4670 goto trivially_false;
4671 else
4672 goto trivially_true;
4673 }
4674 // Otherwise swap the operands to put the constant on the right.
4675 std::swap(LHS, RHS);
4676 Pred = ICmpInst::getSwappedPredicate(Pred);
4677 Changed = true;
4678 }
4679
4680 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004681 // addrec's loop, put the addrec on the left. Also make a dominance check,
4682 // as both operands could be addrecs loop-invariant in each other's loop.
4683 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4684 const Loop *L = AR->getLoop();
4685 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004686 std::swap(LHS, RHS);
4687 Pred = ICmpInst::getSwappedPredicate(Pred);
4688 Changed = true;
4689 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004690 }
Dan Gohmane9796502010-04-24 01:28:42 +00004691
4692 // If there's a constant operand, canonicalize comparisons with boundary
4693 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4694 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4695 const APInt &RA = RC->getValue()->getValue();
4696 switch (Pred) {
4697 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4698 case ICmpInst::ICMP_EQ:
4699 case ICmpInst::ICMP_NE:
4700 break;
4701 case ICmpInst::ICMP_UGE:
4702 if ((RA - 1).isMinValue()) {
4703 Pred = ICmpInst::ICMP_NE;
4704 RHS = getConstant(RA - 1);
4705 Changed = true;
4706 break;
4707 }
4708 if (RA.isMaxValue()) {
4709 Pred = ICmpInst::ICMP_EQ;
4710 Changed = true;
4711 break;
4712 }
4713 if (RA.isMinValue()) goto trivially_true;
4714
4715 Pred = ICmpInst::ICMP_UGT;
4716 RHS = getConstant(RA - 1);
4717 Changed = true;
4718 break;
4719 case ICmpInst::ICMP_ULE:
4720 if ((RA + 1).isMaxValue()) {
4721 Pred = ICmpInst::ICMP_NE;
4722 RHS = getConstant(RA + 1);
4723 Changed = true;
4724 break;
4725 }
4726 if (RA.isMinValue()) {
4727 Pred = ICmpInst::ICMP_EQ;
4728 Changed = true;
4729 break;
4730 }
4731 if (RA.isMaxValue()) goto trivially_true;
4732
4733 Pred = ICmpInst::ICMP_ULT;
4734 RHS = getConstant(RA + 1);
4735 Changed = true;
4736 break;
4737 case ICmpInst::ICMP_SGE:
4738 if ((RA - 1).isMinSignedValue()) {
4739 Pred = ICmpInst::ICMP_NE;
4740 RHS = getConstant(RA - 1);
4741 Changed = true;
4742 break;
4743 }
4744 if (RA.isMaxSignedValue()) {
4745 Pred = ICmpInst::ICMP_EQ;
4746 Changed = true;
4747 break;
4748 }
4749 if (RA.isMinSignedValue()) goto trivially_true;
4750
4751 Pred = ICmpInst::ICMP_SGT;
4752 RHS = getConstant(RA - 1);
4753 Changed = true;
4754 break;
4755 case ICmpInst::ICMP_SLE:
4756 if ((RA + 1).isMaxSignedValue()) {
4757 Pred = ICmpInst::ICMP_NE;
4758 RHS = getConstant(RA + 1);
4759 Changed = true;
4760 break;
4761 }
4762 if (RA.isMinSignedValue()) {
4763 Pred = ICmpInst::ICMP_EQ;
4764 Changed = true;
4765 break;
4766 }
4767 if (RA.isMaxSignedValue()) goto trivially_true;
4768
4769 Pred = ICmpInst::ICMP_SLT;
4770 RHS = getConstant(RA + 1);
4771 Changed = true;
4772 break;
4773 case ICmpInst::ICMP_UGT:
4774 if (RA.isMinValue()) {
4775 Pred = ICmpInst::ICMP_NE;
4776 Changed = true;
4777 break;
4778 }
4779 if ((RA + 1).isMaxValue()) {
4780 Pred = ICmpInst::ICMP_EQ;
4781 RHS = getConstant(RA + 1);
4782 Changed = true;
4783 break;
4784 }
4785 if (RA.isMaxValue()) goto trivially_false;
4786 break;
4787 case ICmpInst::ICMP_ULT:
4788 if (RA.isMaxValue()) {
4789 Pred = ICmpInst::ICMP_NE;
4790 Changed = true;
4791 break;
4792 }
4793 if ((RA - 1).isMinValue()) {
4794 Pred = ICmpInst::ICMP_EQ;
4795 RHS = getConstant(RA - 1);
4796 Changed = true;
4797 break;
4798 }
4799 if (RA.isMinValue()) goto trivially_false;
4800 break;
4801 case ICmpInst::ICMP_SGT:
4802 if (RA.isMinSignedValue()) {
4803 Pred = ICmpInst::ICMP_NE;
4804 Changed = true;
4805 break;
4806 }
4807 if ((RA + 1).isMaxSignedValue()) {
4808 Pred = ICmpInst::ICMP_EQ;
4809 RHS = getConstant(RA + 1);
4810 Changed = true;
4811 break;
4812 }
4813 if (RA.isMaxSignedValue()) goto trivially_false;
4814 break;
4815 case ICmpInst::ICMP_SLT:
4816 if (RA.isMaxSignedValue()) {
4817 Pred = ICmpInst::ICMP_NE;
4818 Changed = true;
4819 break;
4820 }
4821 if ((RA - 1).isMinSignedValue()) {
4822 Pred = ICmpInst::ICMP_EQ;
4823 RHS = getConstant(RA - 1);
4824 Changed = true;
4825 break;
4826 }
4827 if (RA.isMinSignedValue()) goto trivially_false;
4828 break;
4829 }
4830 }
4831
4832 // Check for obvious equality.
4833 if (HasSameValue(LHS, RHS)) {
4834 if (ICmpInst::isTrueWhenEqual(Pred))
4835 goto trivially_true;
4836 if (ICmpInst::isFalseWhenEqual(Pred))
4837 goto trivially_false;
4838 }
4839
Dan Gohman03557dc2010-05-03 16:35:17 +00004840 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4841 // adding or subtracting 1 from one of the operands.
4842 switch (Pred) {
4843 case ICmpInst::ICMP_SLE:
4844 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4845 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4846 /*HasNUW=*/false, /*HasNSW=*/true);
4847 Pred = ICmpInst::ICMP_SLT;
4848 Changed = true;
4849 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004850 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004851 /*HasNUW=*/false, /*HasNSW=*/true);
4852 Pred = ICmpInst::ICMP_SLT;
4853 Changed = true;
4854 }
4855 break;
4856 case ICmpInst::ICMP_SGE:
4857 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004858 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004859 /*HasNUW=*/false, /*HasNSW=*/true);
4860 Pred = ICmpInst::ICMP_SGT;
4861 Changed = true;
4862 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
4863 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4864 /*HasNUW=*/false, /*HasNSW=*/true);
4865 Pred = ICmpInst::ICMP_SGT;
4866 Changed = true;
4867 }
4868 break;
4869 case ICmpInst::ICMP_ULE:
4870 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004871 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004872 /*HasNUW=*/true, /*HasNSW=*/false);
4873 Pred = ICmpInst::ICMP_ULT;
4874 Changed = true;
4875 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004876 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004877 /*HasNUW=*/true, /*HasNSW=*/false);
4878 Pred = ICmpInst::ICMP_ULT;
4879 Changed = true;
4880 }
4881 break;
4882 case ICmpInst::ICMP_UGE:
4883 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004884 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004885 /*HasNUW=*/true, /*HasNSW=*/false);
4886 Pred = ICmpInst::ICMP_UGT;
4887 Changed = true;
4888 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004889 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004890 /*HasNUW=*/true, /*HasNSW=*/false);
4891 Pred = ICmpInst::ICMP_UGT;
4892 Changed = true;
4893 }
4894 break;
4895 default:
4896 break;
4897 }
4898
Dan Gohmane9796502010-04-24 01:28:42 +00004899 // TODO: More simplifications are possible here.
4900
4901 return Changed;
4902
4903trivially_true:
4904 // Return 0 == 0.
4905 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
4906 Pred = ICmpInst::ICMP_EQ;
4907 return true;
4908
4909trivially_false:
4910 // Return 0 != 0.
4911 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
4912 Pred = ICmpInst::ICMP_NE;
4913 return true;
4914}
4915
Dan Gohman85b05a22009-07-13 21:35:55 +00004916bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4917 return getSignedRange(S).getSignedMax().isNegative();
4918}
4919
4920bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4921 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4922}
4923
4924bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4925 return !getSignedRange(S).getSignedMin().isNegative();
4926}
4927
4928bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4929 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4930}
4931
4932bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4933 return isKnownNegative(S) || isKnownPositive(S);
4934}
4935
4936bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4937 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00004938 // Canonicalize the inputs first.
4939 (void)SimplifyICmpOperands(Pred, LHS, RHS);
4940
Dan Gohman53c66ea2010-04-11 22:16:48 +00004941 // If LHS or RHS is an addrec, check to see if the condition is true in
4942 // every iteration of the loop.
4943 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
4944 if (isLoopEntryGuardedByCond(
4945 AR->getLoop(), Pred, AR->getStart(), RHS) &&
4946 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00004947 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00004948 return true;
4949 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
4950 if (isLoopEntryGuardedByCond(
4951 AR->getLoop(), Pred, LHS, AR->getStart()) &&
4952 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00004953 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00004954 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00004955
Dan Gohman53c66ea2010-04-11 22:16:48 +00004956 // Otherwise see what can be done with known constant ranges.
4957 return isKnownPredicateWithRanges(Pred, LHS, RHS);
4958}
4959
4960bool
4961ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
4962 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004963 if (HasSameValue(LHS, RHS))
4964 return ICmpInst::isTrueWhenEqual(Pred);
4965
Dan Gohman53c66ea2010-04-11 22:16:48 +00004966 // This code is split out from isKnownPredicate because it is called from
4967 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00004968 switch (Pred) {
4969 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004970 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004971 break;
4972 case ICmpInst::ICMP_SGT:
4973 Pred = ICmpInst::ICMP_SLT;
4974 std::swap(LHS, RHS);
4975 case ICmpInst::ICMP_SLT: {
4976 ConstantRange LHSRange = getSignedRange(LHS);
4977 ConstantRange RHSRange = getSignedRange(RHS);
4978 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4979 return true;
4980 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4981 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004982 break;
4983 }
4984 case ICmpInst::ICMP_SGE:
4985 Pred = ICmpInst::ICMP_SLE;
4986 std::swap(LHS, RHS);
4987 case ICmpInst::ICMP_SLE: {
4988 ConstantRange LHSRange = getSignedRange(LHS);
4989 ConstantRange RHSRange = getSignedRange(RHS);
4990 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4991 return true;
4992 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4993 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004994 break;
4995 }
4996 case ICmpInst::ICMP_UGT:
4997 Pred = ICmpInst::ICMP_ULT;
4998 std::swap(LHS, RHS);
4999 case ICmpInst::ICMP_ULT: {
5000 ConstantRange LHSRange = getUnsignedRange(LHS);
5001 ConstantRange RHSRange = getUnsignedRange(RHS);
5002 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5003 return true;
5004 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5005 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005006 break;
5007 }
5008 case ICmpInst::ICMP_UGE:
5009 Pred = ICmpInst::ICMP_ULE;
5010 std::swap(LHS, RHS);
5011 case ICmpInst::ICMP_ULE: {
5012 ConstantRange LHSRange = getUnsignedRange(LHS);
5013 ConstantRange RHSRange = getUnsignedRange(RHS);
5014 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5015 return true;
5016 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5017 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005018 break;
5019 }
5020 case ICmpInst::ICMP_NE: {
5021 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5022 return true;
5023 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5024 return true;
5025
5026 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5027 if (isKnownNonZero(Diff))
5028 return true;
5029 break;
5030 }
5031 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005032 // The check at the top of the function catches the case where
5033 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005034 break;
5035 }
5036 return false;
5037}
5038
5039/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5040/// protected by a conditional between LHS and RHS. This is used to
5041/// to eliminate casts.
5042bool
5043ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5044 ICmpInst::Predicate Pred,
5045 const SCEV *LHS, const SCEV *RHS) {
5046 // Interpret a null as meaning no loop, where there is obviously no guard
5047 // (interprocedural conditions notwithstanding).
5048 if (!L) return true;
5049
5050 BasicBlock *Latch = L->getLoopLatch();
5051 if (!Latch)
5052 return false;
5053
5054 BranchInst *LoopContinuePredicate =
5055 dyn_cast<BranchInst>(Latch->getTerminator());
5056 if (!LoopContinuePredicate ||
5057 LoopContinuePredicate->isUnconditional())
5058 return false;
5059
Dan Gohman0f4b2852009-07-21 23:03:19 +00005060 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
5061 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005062}
5063
Dan Gohman3948d0b2010-04-11 19:27:13 +00005064/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005065/// by a conditional between LHS and RHS. This is used to help avoid max
5066/// expressions in loop trip counts, and to eliminate casts.
5067bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005068ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5069 ICmpInst::Predicate Pred,
5070 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005071 // Interpret a null as meaning no loop, where there is obviously no guard
5072 // (interprocedural conditions notwithstanding).
5073 if (!L) return false;
5074
Dan Gohman859b4822009-05-18 15:36:09 +00005075 // Starting at the loop predecessor, climb up the predecessor chain, as long
5076 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005077 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005078 for (std::pair<BasicBlock *, BasicBlock *>
5079 Pair(getLoopPredecessor(L), L->getHeader());
5080 Pair.first;
5081 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005082
5083 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005084 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005085 if (!LoopEntryPredicate ||
5086 LoopEntryPredicate->isUnconditional())
5087 continue;
5088
Dan Gohman0f4b2852009-07-21 23:03:19 +00005089 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
Dan Gohman005752b2010-04-15 16:19:08 +00005090 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005091 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005092 }
5093
Dan Gohman38372182008-08-12 20:17:31 +00005094 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005095}
5096
Dan Gohman0f4b2852009-07-21 23:03:19 +00005097/// isImpliedCond - Test whether the condition described by Pred, LHS,
5098/// and RHS is true whenever the given Cond value evaluates to true.
5099bool ScalarEvolution::isImpliedCond(Value *CondValue,
5100 ICmpInst::Predicate Pred,
5101 const SCEV *LHS, const SCEV *RHS,
5102 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005103 // Recursively handle And and Or conditions.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
5105 if (BO->getOpcode() == Instruction::And) {
5106 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00005107 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5108 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005109 } else if (BO->getOpcode() == Instruction::Or) {
5110 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00005111 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5112 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005113 }
5114 }
5115
5116 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
5117 if (!ICI) return false;
5118
Dan Gohman85b05a22009-07-13 21:35:55 +00005119 // Bail if the ICmp's operands' types are wider than the needed type
5120 // before attempting to call getSCEV on them. This avoids infinite
5121 // recursion, since the analysis of widening casts can require loop
5122 // exit condition information for overflow checking, which would
5123 // lead back here.
5124 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005125 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005126 return false;
5127
Dan Gohman0f4b2852009-07-21 23:03:19 +00005128 // Now that we found a conditional branch that dominates the loop, check to
5129 // see if it is the comparison we are looking for.
5130 ICmpInst::Predicate FoundPred;
5131 if (Inverse)
5132 FoundPred = ICI->getInversePredicate();
5133 else
5134 FoundPred = ICI->getPredicate();
5135
5136 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5137 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005138
5139 // Balance the types. The case where FoundLHS' type is wider than
5140 // LHS' type is checked for above.
5141 if (getTypeSizeInBits(LHS->getType()) >
5142 getTypeSizeInBits(FoundLHS->getType())) {
5143 if (CmpInst::isSigned(Pred)) {
5144 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5145 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5146 } else {
5147 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5148 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5149 }
5150 }
5151
Dan Gohman0f4b2852009-07-21 23:03:19 +00005152 // Canonicalize the query to match the way instcombine will have
5153 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005154 if (SimplifyICmpOperands(Pred, LHS, RHS))
5155 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005156 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005157 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5158 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005159 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005160
5161 // Check to see if we can make the LHS or RHS match.
5162 if (LHS == FoundRHS || RHS == FoundLHS) {
5163 if (isa<SCEVConstant>(RHS)) {
5164 std::swap(FoundLHS, FoundRHS);
5165 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5166 } else {
5167 std::swap(LHS, RHS);
5168 Pred = ICmpInst::getSwappedPredicate(Pred);
5169 }
5170 }
5171
5172 // Check whether the found predicate is the same as the desired predicate.
5173 if (FoundPred == Pred)
5174 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5175
5176 // Check whether swapping the found predicate makes it the same as the
5177 // desired predicate.
5178 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5179 if (isa<SCEVConstant>(RHS))
5180 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5181 else
5182 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5183 RHS, LHS, FoundLHS, FoundRHS);
5184 }
5185
5186 // Check whether the actual condition is beyond sufficient.
5187 if (FoundPred == ICmpInst::ICMP_EQ)
5188 if (ICmpInst::isTrueWhenEqual(Pred))
5189 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5190 return true;
5191 if (Pred == ICmpInst::ICMP_NE)
5192 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5193 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5194 return true;
5195
5196 // Otherwise assume the worst.
5197 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005198}
5199
Dan Gohman0f4b2852009-07-21 23:03:19 +00005200/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005201/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005202/// and FoundRHS is true.
5203bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5204 const SCEV *LHS, const SCEV *RHS,
5205 const SCEV *FoundLHS,
5206 const SCEV *FoundRHS) {
5207 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5208 FoundLHS, FoundRHS) ||
5209 // ~x < ~y --> x > y
5210 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5211 getNotSCEV(FoundRHS),
5212 getNotSCEV(FoundLHS));
5213}
5214
5215/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005216/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005217/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005218bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005219ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5220 const SCEV *LHS, const SCEV *RHS,
5221 const SCEV *FoundLHS,
5222 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005223 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005224 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5225 case ICmpInst::ICMP_EQ:
5226 case ICmpInst::ICMP_NE:
5227 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5228 return true;
5229 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005230 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005231 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005232 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5233 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005234 return true;
5235 break;
5236 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005237 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005238 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5239 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005240 return true;
5241 break;
5242 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005243 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005244 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5245 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005246 return true;
5247 break;
5248 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005249 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005250 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5251 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005252 return true;
5253 break;
5254 }
5255
5256 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005257}
5258
Dan Gohman51f53b72009-06-21 23:46:38 +00005259/// getBECount - Subtract the end and start values and divide by the step,
5260/// rounding up, to get the number of times the backedge is executed. Return
5261/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005262const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005263 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005264 const SCEV *Step,
5265 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005266 assert(!isKnownNegative(Step) &&
5267 "This code doesn't handle negative strides yet!");
5268
Dan Gohman51f53b72009-06-21 23:46:38 +00005269 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005270 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005271 const SCEV *Diff = getMinusSCEV(End, Start);
5272 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005273
5274 // Add an adjustment to the difference between End and Start so that
5275 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005276 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005277
Dan Gohman1f96e672009-09-17 18:05:20 +00005278 if (!NoWrap) {
5279 // Check Add for unsigned overflow.
5280 // TODO: More sophisticated things could be done here.
5281 const Type *WideTy = IntegerType::get(getContext(),
5282 getTypeSizeInBits(Ty) + 1);
5283 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5284 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5285 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5286 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5287 return getCouldNotCompute();
5288 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005289
5290 return getUDivExpr(Add, Step);
5291}
5292
Chris Lattnerdb25de42005-08-15 23:33:51 +00005293/// HowManyLessThans - Return the number of times a backedge containing the
5294/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005295/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005296ScalarEvolution::BackedgeTakenInfo
5297ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5298 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005299 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005300 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005301
Dan Gohman35738ac2009-05-04 22:30:44 +00005302 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005303 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005304 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005305
Dan Gohman1f96e672009-09-17 18:05:20 +00005306 // Check to see if we have a flag which makes analysis easy.
5307 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5308 AddRec->hasNoUnsignedWrap();
5309
Chris Lattnerdb25de42005-08-15 23:33:51 +00005310 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005311 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005312 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005313
Dan Gohman52fddd32010-01-26 04:40:18 +00005314 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005315 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005316 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005317 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005318 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005319 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005320 // value and past the maximum value for its type in a single step.
5321 // Note that it's not sufficient to check NoWrap here, because even
5322 // though the value after a wrap is undefined, it's not undefined
5323 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005324 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005325 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005326 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005327 if (isSigned) {
5328 APInt Max = APInt::getSignedMaxValue(BitWidth);
5329 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5330 .slt(getSignedRange(RHS).getSignedMax()))
5331 return getCouldNotCompute();
5332 } else {
5333 APInt Max = APInt::getMaxValue(BitWidth);
5334 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5335 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5336 return getCouldNotCompute();
5337 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005338 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005339 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005340 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005341
Dan Gohmana1af7572009-04-30 20:47:05 +00005342 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5343 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5344 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005345 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005346
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005347 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005348 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005349
Dan Gohmana1af7572009-04-30 20:47:05 +00005350 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005351 const SCEV *MinStart = getConstant(isSigned ?
5352 getSignedRange(Start).getSignedMin() :
5353 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005354
Dan Gohmana1af7572009-04-30 20:47:05 +00005355 // If we know that the condition is true in order to enter the loop,
5356 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005357 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5358 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005359 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005360 if (!isLoopEntryGuardedByCond(L,
5361 isSigned ? ICmpInst::ICMP_SLT :
5362 ICmpInst::ICMP_ULT,
5363 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005364 End = isSigned ? getSMaxExpr(RHS, Start)
5365 : getUMaxExpr(RHS, Start);
5366
5367 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005368 const SCEV *MaxEnd = getConstant(isSigned ?
5369 getSignedRange(End).getSignedMax() :
5370 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005371
Dan Gohman52fddd32010-01-26 04:40:18 +00005372 // If MaxEnd is within a step of the maximum integer value in its type,
5373 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005374 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005375 // compute the correct value.
5376 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005377 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005378 MaxEnd = isSigned ?
5379 getSMinExpr(MaxEnd,
5380 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5381 StepMinusOne)) :
5382 getUMinExpr(MaxEnd,
5383 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5384 StepMinusOne));
5385
Dan Gohmana1af7572009-04-30 20:47:05 +00005386 // Finally, we subtract these two values and divide, rounding up, to get
5387 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005388 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005389
5390 // The maximum backedge count is similar, except using the minimum start
5391 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005392 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005393
5394 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005395 }
5396
Dan Gohman1c343752009-06-27 21:21:31 +00005397 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005398}
5399
Chris Lattner53e677a2004-04-02 20:23:17 +00005400/// getNumIterationsInRange - Return the number of iterations of this loop that
5401/// produce values in the specified constant range. Another way of looking at
5402/// this is that it returns the first iteration number where the value is not in
5403/// the condition, thus computing the exit count. If the iteration count can't
5404/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005405const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005406 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005407 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005408 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005409
5410 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005411 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005412 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005413 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005414 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005415 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005416 if (const SCEVAddRecExpr *ShiftedAddRec =
5417 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005418 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005419 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005420 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005421 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005422 }
5423
5424 // The only time we can solve this is when we have all constant indices.
5425 // Otherwise, we cannot determine the overflow conditions.
5426 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5427 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005428 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005429
5430
5431 // Okay at this point we know that all elements of the chrec are constants and
5432 // that the start element is zero.
5433
5434 // First check to see if the range contains zero. If not, the first
5435 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005436 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005437 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005438 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005439
Chris Lattner53e677a2004-04-02 20:23:17 +00005440 if (isAffine()) {
5441 // If this is an affine expression then we have this situation:
5442 // Solve {0,+,A} in Range === Ax in Range
5443
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005444 // We know that zero is in the range. If A is positive then we know that
5445 // the upper value of the range must be the first possible exit value.
5446 // If A is negative then the lower of the range is the last possible loop
5447 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005448 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005449 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5450 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005451
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005452 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005453 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005454 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005455
5456 // Evaluate at the exit value. If we really did fall out of the valid
5457 // range, then we computed our trip count, otherwise wrap around or other
5458 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005459 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005460 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005461 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005462
5463 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005464 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005465 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005466 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005467 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005468 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005469 } else if (isQuadratic()) {
5470 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5471 // quadratic equation to solve it. To do this, we must frame our problem in
5472 // terms of figuring out when zero is crossed, instead of when
5473 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005474 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005475 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005476 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005477
5478 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005479 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005480 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005481 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5482 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005483 if (R1) {
5484 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005485 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005486 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005487 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005488 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005489 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005490
Chris Lattner53e677a2004-04-02 20:23:17 +00005491 // Make sure the root is not off by one. The returned iteration should
5492 // not be in the range, but the previous one should be. When solving
5493 // for "X*X < 5", for example, we should not return a root of 2.
5494 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005495 R1->getValue(),
5496 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005497 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005498 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005499 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005500 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005501
Dan Gohman246b2562007-10-22 18:31:58 +00005502 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005503 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005504 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005505 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005506 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005507
Chris Lattner53e677a2004-04-02 20:23:17 +00005508 // If R1 was not in the range, then it is a good return value. Make
5509 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005510 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005511 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005512 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005513 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005514 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005515 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005516 }
5517 }
5518 }
5519
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005520 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005521}
5522
5523
5524
5525//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005526// SCEVCallbackVH Class Implementation
5527//===----------------------------------------------------------------------===//
5528
Dan Gohman1959b752009-05-19 19:22:47 +00005529void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005530 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005531 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5532 SE->ConstantEvolutionLoopExitValue.erase(PN);
5533 SE->Scalars.erase(getValPtr());
5534 // this now dangles!
5535}
5536
Dan Gohman1959b752009-05-19 19:22:47 +00005537void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005538 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005539
5540 // Forget all the expressions associated with users of the old value,
5541 // so that future queries will recompute the expressions using the new
5542 // value.
5543 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005544 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005545 Value *Old = getValPtr();
5546 bool DeleteOld = false;
5547 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5548 UI != UE; ++UI)
5549 Worklist.push_back(*UI);
5550 while (!Worklist.empty()) {
5551 User *U = Worklist.pop_back_val();
5552 // Deleting the Old value will cause this to dangle. Postpone
5553 // that until everything else is done.
5554 if (U == Old) {
5555 DeleteOld = true;
5556 continue;
5557 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005558 if (!Visited.insert(U))
5559 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005560 if (PHINode *PN = dyn_cast<PHINode>(U))
5561 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005562 SE->Scalars.erase(U);
5563 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5564 UI != UE; ++UI)
5565 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005566 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005567 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005568 if (DeleteOld) {
5569 if (PHINode *PN = dyn_cast<PHINode>(Old))
5570 SE->ConstantEvolutionLoopExitValue.erase(PN);
5571 SE->Scalars.erase(Old);
5572 // this now dangles!
5573 }
5574 // this may dangle!
5575}
5576
Dan Gohman1959b752009-05-19 19:22:47 +00005577ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005578 : CallbackVH(V), SE(se) {}
5579
5580//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005581// ScalarEvolution Class Implementation
5582//===----------------------------------------------------------------------===//
5583
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005584ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005585 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005586}
5587
Chris Lattner53e677a2004-04-02 20:23:17 +00005588bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005589 this->F = &F;
5590 LI = &getAnalysis<LoopInfo>();
5591 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005592 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005593 return false;
5594}
5595
5596void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005597 Scalars.clear();
5598 BackedgeTakenCounts.clear();
5599 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005600 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005601 UniqueSCEVs.clear();
5602 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005603}
5604
5605void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5606 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005607 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005608 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005609}
5610
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005611bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005612 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005613}
5614
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005615static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005616 const Loop *L) {
5617 // Print all inner loops first
5618 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5619 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005620
Dan Gohman30733292010-01-09 18:17:45 +00005621 OS << "Loop ";
5622 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5623 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005624
Dan Gohman5d984912009-12-18 01:14:11 +00005625 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005626 L->getExitBlocks(ExitBlocks);
5627 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005628 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005629
Dan Gohman46bdfb02009-02-24 18:55:53 +00005630 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5631 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005632 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005633 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005634 }
5635
Dan Gohman30733292010-01-09 18:17:45 +00005636 OS << "\n"
5637 "Loop ";
5638 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5639 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005640
5641 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5642 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5643 } else {
5644 OS << "Unpredictable max backedge-taken count. ";
5645 }
5646
5647 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005648}
5649
Dan Gohman5d984912009-12-18 01:14:11 +00005650void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005651 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005652 // out SCEV values of all instructions that are interesting. Doing
5653 // this potentially causes it to create new SCEV objects though,
5654 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005655 // observable from outside the class though, so casting away the
5656 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005657 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005658
Dan Gohman30733292010-01-09 18:17:45 +00005659 OS << "Classifying expressions for: ";
5660 WriteAsOperand(OS, F, /*PrintType=*/false);
5661 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005662 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005663 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005664 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005665 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005666 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005667 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005668
Dan Gohman0c689c52009-06-19 17:49:54 +00005669 const Loop *L = LI->getLoopFor((*I).getParent());
5670
Dan Gohman0bba49c2009-07-07 17:06:11 +00005671 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005672 if (AtUse != SV) {
5673 OS << " --> ";
5674 AtUse->print(OS);
5675 }
5676
5677 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005678 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005679 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005680 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005681 OS << "<<Unknown>>";
5682 } else {
5683 OS << *ExitValue;
5684 }
5685 }
5686
Chris Lattner53e677a2004-04-02 20:23:17 +00005687 OS << "\n";
5688 }
5689
Dan Gohman30733292010-01-09 18:17:45 +00005690 OS << "Determining loop execution counts for: ";
5691 WriteAsOperand(OS, F, /*PrintType=*/false);
5692 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005693 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5694 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005695}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005696