blob: b2395af9243b4facd11fa3e11cf1d17f6645cceb [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 Gohmanc050fd92009-07-13 20:50:19 +0000144 SCEV(FoldingSetNodeID(), 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;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000181 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000182 UniqueSCEVs.InsertNode(S, IP);
183 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman0bba49c2009-07-07 17:06:11 +0000186const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000187 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Dan Gohman0bba49c2009-07-07 17:06:11 +0000190const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000192 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohman6e70e312009-09-27 15:26:03 +0000210bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
212}
213
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000217 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
218 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000229 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
230 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000234void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000241 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
242 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000243 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
Dan Gohmanecb403a2009-05-07 14:00:19 +0000259bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
262 return false;
263 }
264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
270 return false;
271 }
272 return true;
273}
274
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000275bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
277}
278
Dan Gohman6e70e312009-09-27 15:26:03 +0000279bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
281}
282
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000283void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000284 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000285}
286
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294}
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000297 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000298 if (!QueryLoop)
299 return false;
300
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000302 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000303 return false;
304
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
306 // are variant.
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
309 return false;
310
311 // Otherwise it's loop-invariant.
312 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000313}
314
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000315void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316 OS << "{" << *Operands[0];
317 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
318 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000319 OS << "}<";
320 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
321 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322}
Chris Lattner53e677a2004-04-02 20:23:17 +0000323
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000324void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
325 // LLVM struct fields don't have names, so just print the field number.
326 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
327}
328
329void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
330 OS << "sizeof(" << *AllocTy << ")";
331}
332
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000333bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
334 // All non-instruction values are loop invariant. All instructions are loop
335 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000336 // Instructions are never considered invariant in the function body
337 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000339 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000340 return true;
341}
Chris Lattner53e677a2004-04-02 20:23:17 +0000342
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000343bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
344 if (Instruction *I = dyn_cast<Instruction>(getValue()))
345 return DT->dominates(I->getParent(), BB);
346 return true;
347}
348
Dan Gohman6e70e312009-09-27 15:26:03 +0000349bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
350 if (Instruction *I = dyn_cast<Instruction>(getValue()))
351 return DT->properlyDominates(I->getParent(), BB);
352 return true;
353}
354
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000355const Type *SCEVUnknown::getType() const {
356 return V->getType();
357}
Chris Lattner53e677a2004-04-02 20:23:17 +0000358
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000359void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000360 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000361}
362
Chris Lattner8d741b82004-06-20 06:23:15 +0000363//===----------------------------------------------------------------------===//
364// SCEV Utilities
365//===----------------------------------------------------------------------===//
366
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000367static bool CompareTypes(const Type *A, const Type *B) {
368 if (A->getTypeID() != B->getTypeID())
369 return A->getTypeID() < B->getTypeID();
370 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
371 const IntegerType *BI = cast<IntegerType>(B);
372 return AI->getBitWidth() < BI->getBitWidth();
373 }
374 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
375 const PointerType *BI = cast<PointerType>(B);
376 return CompareTypes(AI->getElementType(), BI->getElementType());
377 }
378 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
379 const ArrayType *BI = cast<ArrayType>(B);
380 if (AI->getNumElements() != BI->getNumElements())
381 return AI->getNumElements() < BI->getNumElements();
382 return CompareTypes(AI->getElementType(), BI->getElementType());
383 }
384 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
385 const VectorType *BI = cast<VectorType>(B);
386 if (AI->getNumElements() != BI->getNumElements())
387 return AI->getNumElements() < BI->getNumElements();
388 return CompareTypes(AI->getElementType(), BI->getElementType());
389 }
390 if (const StructType *AI = dyn_cast<StructType>(A)) {
391 const StructType *BI = cast<StructType>(B);
392 if (AI->getNumElements() != BI->getNumElements())
393 return AI->getNumElements() < BI->getNumElements();
394 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
395 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
396 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
397 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
398 }
399 return false;
400}
401
Chris Lattner8d741b82004-06-20 06:23:15 +0000402namespace {
403 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
404 /// than the complexity of the RHS. This comparator is used to canonicalize
405 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000406 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000407 LoopInfo *LI;
408 public:
409 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
410
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000411 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000412 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
413 if (LHS == RHS)
414 return false;
415
Dan Gohman72861302009-05-07 14:39:04 +0000416 // Primarily, sort the SCEVs by their getSCEVType().
417 if (LHS->getSCEVType() != RHS->getSCEVType())
418 return LHS->getSCEVType() < RHS->getSCEVType();
419
420 // Aside from the getSCEVType() ordering, the particular ordering
421 // isn't very important except that it's beneficial to be consistent,
422 // so that (a + b) and (b + a) don't end up as different expressions.
423
424 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
425 // not as complete as it could be.
426 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
427 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
428
Dan Gohman5be18e82009-05-19 02:15:55 +0000429 // Order pointer values after integer values. This helps SCEVExpander
430 // form GEPs.
431 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
432 return false;
433 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
434 return true;
435
Dan Gohman72861302009-05-07 14:39:04 +0000436 // Compare getValueID values.
437 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
438 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
439
440 // Sort arguments by their position.
441 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
442 const Argument *RA = cast<Argument>(RU->getValue());
443 return LA->getArgNo() < RA->getArgNo();
444 }
445
446 // For instructions, compare their loop depth, and their opcode.
447 // This is pretty loose.
448 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
449 Instruction *RV = cast<Instruction>(RU->getValue());
450
451 // Compare loop depths.
452 if (LI->getLoopDepth(LV->getParent()) !=
453 LI->getLoopDepth(RV->getParent()))
454 return LI->getLoopDepth(LV->getParent()) <
455 LI->getLoopDepth(RV->getParent());
456
457 // Compare opcodes.
458 if (LV->getOpcode() != RV->getOpcode())
459 return LV->getOpcode() < RV->getOpcode();
460
461 // Compare the number of operands.
462 if (LV->getNumOperands() != RV->getNumOperands())
463 return LV->getNumOperands() < RV->getNumOperands();
464 }
465
466 return false;
467 }
468
Dan Gohman4dfad292009-06-14 22:51:25 +0000469 // Compare constant values.
470 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
471 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000472 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
473 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000474 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
475 }
476
477 // Compare addrec loop depths.
478 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
479 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
480 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
481 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
482 }
Dan Gohman72861302009-05-07 14:39:04 +0000483
484 // Lexicographically compare n-ary expressions.
485 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
486 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
487 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
488 if (i >= RC->getNumOperands())
489 return false;
490 if (operator()(LC->getOperand(i), RC->getOperand(i)))
491 return true;
492 if (operator()(RC->getOperand(i), LC->getOperand(i)))
493 return false;
494 }
495 return LC->getNumOperands() < RC->getNumOperands();
496 }
497
Dan Gohmana6b35e22009-05-07 19:23:21 +0000498 // Lexicographically compare udiv expressions.
499 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
500 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
501 if (operator()(LC->getLHS(), RC->getLHS()))
502 return true;
503 if (operator()(RC->getLHS(), LC->getLHS()))
504 return false;
505 if (operator()(LC->getRHS(), RC->getRHS()))
506 return true;
507 if (operator()(RC->getRHS(), LC->getRHS()))
508 return false;
509 return false;
510 }
511
Dan Gohman72861302009-05-07 14:39:04 +0000512 // Compare cast expressions by operand.
513 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
514 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
515 return operator()(LC->getOperand(), RC->getOperand());
516 }
517
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000518 // Compare offsetof expressions.
519 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
520 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
521 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
522 CompareTypes(RA->getStructType(), LA->getStructType()))
523 return CompareTypes(LA->getStructType(), RA->getStructType());
524 return LA->getFieldNo() < RA->getFieldNo();
525 }
526
527 // Compare sizeof expressions by the allocation type.
528 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
529 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
530 return CompareTypes(LA->getAllocType(), RA->getAllocType());
531 }
532
Torok Edwinc23197a2009-07-14 16:55:14 +0000533 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000534 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000535 }
536 };
537}
538
539/// GroupByComplexity - Given a list of SCEV objects, order them by their
540/// complexity, and group objects of the same complexity together by value.
541/// When this routine is finished, we know that any duplicates in the vector are
542/// consecutive and that complexity is monotonically increasing.
543///
544/// Note that we go take special precautions to ensure that we get determinstic
545/// results from this routine. In other words, we don't want the results of
546/// this to depend on where the addresses of various SCEV objects happened to
547/// land in memory.
548///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000549static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000550 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000551 if (Ops.size() < 2) return; // Noop
552 if (Ops.size() == 2) {
553 // This is the common case, which also happens to be trivially simple.
554 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000555 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000556 std::swap(Ops[0], Ops[1]);
557 return;
558 }
559
560 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000561 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000562
563 // Now that we are sorted by complexity, group elements of the same
564 // complexity. Note that this is, at worst, N^2, but the vector is likely to
565 // be extremely short in practice. Note that we take this approach because we
566 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000567 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000568 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000569 unsigned Complexity = S->getSCEVType();
570
571 // If there are any objects of the same complexity and same value as this
572 // one, group them.
573 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
574 if (Ops[j] == S) { // Found a duplicate.
575 // Move it to immediately after i'th element.
576 std::swap(Ops[i+1], Ops[j]);
577 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000578 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000579 }
580 }
581 }
582}
583
Chris Lattner53e677a2004-04-02 20:23:17 +0000584
Chris Lattner53e677a2004-04-02 20:23:17 +0000585
586//===----------------------------------------------------------------------===//
587// Simple SCEV method implementations
588//===----------------------------------------------------------------------===//
589
Eli Friedmanb42a6262008-08-04 23:49:06 +0000590/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000591/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000592static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000593 ScalarEvolution &SE,
594 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000595 // Handle the simplest case efficiently.
596 if (K == 1)
597 return SE.getTruncateOrZeroExtend(It, ResultTy);
598
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000599 // We are using the following formula for BC(It, K):
600 //
601 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
602 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000603 // Suppose, W is the bitwidth of the return value. We must be prepared for
604 // overflow. Hence, we must assure that the result of our computation is
605 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
606 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000607 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000608 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000609 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000610 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
611 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000613 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000614 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000615 // This formula is trivially equivalent to the previous formula. However,
616 // this formula can be implemented much more efficiently. The trick is that
617 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
618 // arithmetic. To do exact division in modular arithmetic, all we have
619 // to do is multiply by the inverse. Therefore, this step can be done at
620 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000621 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000622 // The next issue is how to safely do the division by 2^T. The way this
623 // is done is by doing the multiplication step at a width of at least W + T
624 // bits. This way, the bottom W+T bits of the product are accurate. Then,
625 // when we perform the division by 2^T (which is equivalent to a right shift
626 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
627 // truncated out after the division by 2^T.
628 //
629 // In comparison to just directly using the first formula, this technique
630 // is much more efficient; using the first formula requires W * K bits,
631 // but this formula less than W + K bits. Also, the first formula requires
632 // a division step, whereas this formula only requires multiplies and shifts.
633 //
634 // It doesn't matter whether the subtraction step is done in the calculation
635 // width or the input iteration count's width; if the subtraction overflows,
636 // the result must be zero anyway. We prefer here to do it in the width of
637 // the induction variable because it helps a lot for certain cases; CodeGen
638 // isn't smart enough to ignore the overflow, which leads to much less
639 // efficient code if the width of the subtraction is wider than the native
640 // register width.
641 //
642 // (It's possible to not widen at all by pulling out factors of 2 before
643 // the multiplication; for example, K=2 can be calculated as
644 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
645 // extra arithmetic, so it's not an obvious win, and it gets
646 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000647
Eli Friedmanb42a6262008-08-04 23:49:06 +0000648 // Protection from insane SCEVs; this bound is conservative,
649 // but it probably doesn't matter.
650 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000651 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000652
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000653 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000654
Eli Friedmanb42a6262008-08-04 23:49:06 +0000655 // Calculate K! / 2^T and T; we divide out the factors of two before
656 // multiplying for calculating K! / 2^T to avoid overflow.
657 // Other overflow doesn't matter because we only care about the bottom
658 // W bits of the result.
659 APInt OddFactorial(W, 1);
660 unsigned T = 1;
661 for (unsigned i = 3; i <= K; ++i) {
662 APInt Mult(W, i);
663 unsigned TwoFactors = Mult.countTrailingZeros();
664 T += TwoFactors;
665 Mult = Mult.lshr(TwoFactors);
666 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000667 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000668
Eli Friedmanb42a6262008-08-04 23:49:06 +0000669 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000670 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000671
672 // Calcuate 2^T, at width T+W.
673 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
674
675 // Calculate the multiplicative inverse of K! / 2^T;
676 // this multiplication factor will perform the exact division by
677 // K! / 2^T.
678 APInt Mod = APInt::getSignedMinValue(W+1);
679 APInt MultiplyFactor = OddFactorial.zext(W+1);
680 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
681 MultiplyFactor = MultiplyFactor.trunc(W);
682
683 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000684 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
685 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000686 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000687 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000688 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000689 Dividend = SE.getMulExpr(Dividend,
690 SE.getTruncateOrZeroExtend(S, CalculationTy));
691 }
692
693 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000694 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000695
696 // Truncate the result, and divide by K! / 2^T.
697
698 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
699 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000700}
701
Chris Lattner53e677a2004-04-02 20:23:17 +0000702/// evaluateAtIteration - Return the value of this chain of recurrences at
703/// the specified iteration number. We can evaluate this recurrence by
704/// multiplying each element in the chain by the binomial coefficient
705/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
706///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000707/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000708///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000709/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000710///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000711const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000712 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000713 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000714 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000715 // The computation is correct in the face of overflow provided that the
716 // multiplication is performed _after_ the evaluation of the binomial
717 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000718 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000719 if (isa<SCEVCouldNotCompute>(Coeff))
720 return Coeff;
721
722 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000723 }
724 return Result;
725}
726
Chris Lattner53e677a2004-04-02 20:23:17 +0000727//===----------------------------------------------------------------------===//
728// SCEV Expression folder implementations
729//===----------------------------------------------------------------------===//
730
Dan Gohman0bba49c2009-07-07 17:06:11 +0000731const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000732 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000733 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000734 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000735 assert(isSCEVable(Ty) &&
736 "This is not a conversion to a SCEVable type!");
737 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000738
Dan Gohmanc050fd92009-07-13 20:50:19 +0000739 FoldingSetNodeID ID;
740 ID.AddInteger(scTruncate);
741 ID.AddPointer(Op);
742 ID.AddPointer(Ty);
743 void *IP = 0;
744 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
745
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000746 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000747 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000748 return getConstant(
749 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000750
Dan Gohman20900ca2009-04-22 16:20:48 +0000751 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000752 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000753 return getTruncateExpr(ST->getOperand(), Ty);
754
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000755 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000756 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000757 return getTruncateOrSignExtend(SS->getOperand(), Ty);
758
759 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000761 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
762
Dan Gohman6864db62009-06-18 16:24:47 +0000763 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000764 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000765 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000766 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000767 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
768 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000769 }
770
Dan Gohmanc050fd92009-07-13 20:50:19 +0000771 // The cast wasn't folded; create an explicit cast node.
772 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000773 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
774 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000775 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000776 UniqueSCEVs.InsertNode(S, IP);
777 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000778}
779
Dan Gohman0bba49c2009-07-07 17:06:11 +0000780const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000781 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000782 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000783 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000784 assert(isSCEVable(Ty) &&
785 "This is not a conversion to a SCEVable type!");
786 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000787
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000788 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000789 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000790 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000791 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
792 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000793 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000794 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000795
Dan Gohman20900ca2009-04-22 16:20:48 +0000796 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000797 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000798 return getZeroExtendExpr(SZ->getOperand(), Ty);
799
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000800 // Before doing any expensive analysis, check to see if we've already
801 // computed a SCEV for this Op and Ty.
802 FoldingSetNodeID ID;
803 ID.AddInteger(scZeroExtend);
804 ID.AddPointer(Op);
805 ID.AddPointer(Ty);
806 void *IP = 0;
807 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
808
Dan Gohman01ecca22009-04-27 20:16:15 +0000809 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000811 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000812 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000813 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000814 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000815 const SCEV *Start = AR->getStart();
816 const SCEV *Step = AR->getStepRecurrence(*this);
817 unsigned BitWidth = getTypeSizeInBits(AR->getType());
818 const Loop *L = AR->getLoop();
819
Dan Gohmaneb490a72009-07-25 01:22:26 +0000820 // If we have special knowledge that this addrec won't overflow,
821 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000822 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000823 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
824 getZeroExtendExpr(Step, Ty),
825 L);
826
Dan Gohman01ecca22009-04-27 20:16:15 +0000827 // Check whether the backedge-taken count is SCEVCouldNotCompute.
828 // Note that this serves two purposes: It filters out loops that are
829 // simply not analyzable, and it covers the case where this code is
830 // being called from within backedge-taken count analysis, such that
831 // attempting to ask for the backedge-taken count would likely result
832 // in infinite recursion. In the later case, the analysis code will
833 // cope with a conservative value, and it will take care to purge
834 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000835 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000836 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000837 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000838 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000839
840 // Check whether the backedge-taken count can be losslessly casted to
841 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000842 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000843 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000844 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000845 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
846 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000847 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000848 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000849 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000850 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000851 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000852 const SCEV *Add = getAddExpr(Start, ZMul);
853 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000854 getAddExpr(getZeroExtendExpr(Start, WideTy),
855 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
856 getZeroExtendExpr(Step, WideTy)));
857 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000858 // Return the expression with the addrec on the outside.
859 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
860 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000861 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000862
863 // Similar to above, only this time treat the step value as signed.
864 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000865 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000866 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000867 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000868 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000869 OperandExtendedAdd =
870 getAddExpr(getZeroExtendExpr(Start, WideTy),
871 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
872 getSignExtendExpr(Step, WideTy)));
873 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000874 // Return the expression with the addrec on the outside.
875 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
876 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000877 L);
878 }
879
880 // If the backedge is guarded by a comparison with the pre-inc value
881 // the addrec is safe. Also, if the entry is guarded by a comparison
882 // with the start value and the backedge is guarded by a comparison
883 // with the post-inc value, the addrec is safe.
884 if (isKnownPositive(Step)) {
885 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
886 getUnsignedRange(Step).getUnsignedMax());
887 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
888 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
889 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
890 AR->getPostIncExpr(*this), N)))
891 // Return the expression with the addrec on the outside.
892 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
893 getZeroExtendExpr(Step, Ty),
894 L);
895 } else if (isKnownNegative(Step)) {
896 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
897 getSignedRange(Step).getSignedMin());
898 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
899 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
900 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
901 AR->getPostIncExpr(*this), N)))
902 // Return the expression with the addrec on the outside.
903 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
904 getSignExtendExpr(Step, Ty),
905 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000906 }
907 }
908 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000909
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000910 // The cast wasn't folded; create an explicit cast node.
911 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000912 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
913 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000914 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000915 UniqueSCEVs.InsertNode(S, IP);
916 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000917}
918
Dan Gohman0bba49c2009-07-07 17:06:11 +0000919const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000920 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000921 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000922 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000923 assert(isSCEVable(Ty) &&
924 "This is not a conversion to a SCEVable type!");
925 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000926
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000927 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000928 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000929 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000930 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
931 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000932 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000933 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000934
Dan Gohman20900ca2009-04-22 16:20:48 +0000935 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000936 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000937 return getSignExtendExpr(SS->getOperand(), Ty);
938
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000939 // Before doing any expensive analysis, check to see if we've already
940 // computed a SCEV for this Op and Ty.
941 FoldingSetNodeID ID;
942 ID.AddInteger(scSignExtend);
943 ID.AddPointer(Op);
944 ID.AddPointer(Ty);
945 void *IP = 0;
946 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
947
Dan Gohman01ecca22009-04-27 20:16:15 +0000948 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000949 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000950 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000951 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000952 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000953 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000954 const SCEV *Start = AR->getStart();
955 const SCEV *Step = AR->getStepRecurrence(*this);
956 unsigned BitWidth = getTypeSizeInBits(AR->getType());
957 const Loop *L = AR->getLoop();
958
Dan Gohmaneb490a72009-07-25 01:22:26 +0000959 // If we have special knowledge that this addrec won't overflow,
960 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000961 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000962 return getAddRecExpr(getSignExtendExpr(Start, Ty),
963 getSignExtendExpr(Step, Ty),
964 L);
965
Dan Gohman01ecca22009-04-27 20:16:15 +0000966 // Check whether the backedge-taken count is SCEVCouldNotCompute.
967 // Note that this serves two purposes: It filters out loops that are
968 // simply not analyzable, and it covers the case where this code is
969 // being called from within backedge-taken count analysis, such that
970 // attempting to ask for the backedge-taken count would likely result
971 // in infinite recursion. In the later case, the analysis code will
972 // cope with a conservative value, and it will take care to purge
973 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000974 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000975 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000976 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000977 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000978
979 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000980 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000981 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000982 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000983 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000984 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
985 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000986 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000987 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000988 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000989 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000990 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000991 const SCEV *Add = getAddExpr(Start, SMul);
992 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000993 getAddExpr(getSignExtendExpr(Start, WideTy),
994 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
995 getSignExtendExpr(Step, WideTy)));
996 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000997 // Return the expression with the addrec on the outside.
998 return getAddRecExpr(getSignExtendExpr(Start, Ty),
999 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001000 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001001
1002 // Similar to above, only this time treat the step value as unsigned.
1003 // This covers loops that count up with an unsigned step.
1004 const SCEV *UMul =
1005 getMulExpr(CastedMaxBECount,
1006 getTruncateOrZeroExtend(Step, Start->getType()));
1007 Add = getAddExpr(Start, UMul);
1008 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001009 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001010 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1011 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001012 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001013 // Return the expression with the addrec on the outside.
1014 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1015 getZeroExtendExpr(Step, Ty),
1016 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001017 }
1018
1019 // If the backedge is guarded by a comparison with the pre-inc value
1020 // the addrec is safe. Also, if the entry is guarded by a comparison
1021 // with the start value and the backedge is guarded by a comparison
1022 // with the post-inc value, the addrec is safe.
1023 if (isKnownPositive(Step)) {
1024 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1025 getSignedRange(Step).getSignedMax());
1026 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1027 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1028 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1029 AR->getPostIncExpr(*this), N)))
1030 // Return the expression with the addrec on the outside.
1031 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1032 getSignExtendExpr(Step, Ty),
1033 L);
1034 } else if (isKnownNegative(Step)) {
1035 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1036 getSignedRange(Step).getSignedMin());
1037 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1038 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1039 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1040 AR->getPostIncExpr(*this), N)))
1041 // Return the expression with the addrec on the outside.
1042 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1043 getSignExtendExpr(Step, Ty),
1044 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001045 }
1046 }
1047 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001048
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001049 // The cast wasn't folded; create an explicit cast node.
1050 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001051 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1052 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001053 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001054 UniqueSCEVs.InsertNode(S, IP);
1055 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001056}
1057
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001058/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1059/// unspecified bits out to the given type.
1060///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001061const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001062 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001063 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1064 "This is not an extending conversion!");
1065 assert(isSCEVable(Ty) &&
1066 "This is not a conversion to a SCEVable type!");
1067 Ty = getEffectiveSCEVType(Ty);
1068
1069 // Sign-extend negative constants.
1070 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1071 if (SC->getValue()->getValue().isNegative())
1072 return getSignExtendExpr(Op, Ty);
1073
1074 // Peel off a truncate cast.
1075 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001076 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001077 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1078 return getAnyExtendExpr(NewOp, Ty);
1079 return getTruncateOrNoop(NewOp, Ty);
1080 }
1081
1082 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001083 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001084 if (!isa<SCEVZeroExtendExpr>(ZExt))
1085 return ZExt;
1086
1087 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001088 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001089 if (!isa<SCEVSignExtendExpr>(SExt))
1090 return SExt;
1091
Dan Gohmana10756e2010-01-21 02:09:26 +00001092 // Force the cast to be folded into the operands of an addrec.
1093 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1094 SmallVector<const SCEV *, 4> Ops;
1095 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1096 I != E; ++I)
1097 Ops.push_back(getAnyExtendExpr(*I, Ty));
1098 return getAddRecExpr(Ops, AR->getLoop());
1099 }
1100
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001101 // If the expression is obviously signed, use the sext cast value.
1102 if (isa<SCEVSMaxExpr>(Op))
1103 return SExt;
1104
1105 // Absent any other information, use the zext cast value.
1106 return ZExt;
1107}
1108
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001109/// CollectAddOperandsWithScales - Process the given Ops list, which is
1110/// a list of operands to be added under the given scale, update the given
1111/// map. This is a helper function for getAddRecExpr. As an example of
1112/// what it does, given a sequence of operands that would form an add
1113/// expression like this:
1114///
1115/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1116///
1117/// where A and B are constants, update the map with these values:
1118///
1119/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1120///
1121/// and add 13 + A*B*29 to AccumulatedConstant.
1122/// This will allow getAddRecExpr to produce this:
1123///
1124/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1125///
1126/// This form often exposes folding opportunities that are hidden in
1127/// the original operand list.
1128///
1129/// Return true iff it appears that any interesting folding opportunities
1130/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1131/// the common case where no interesting opportunities are present, and
1132/// is also used as a check to avoid infinite recursion.
1133///
1134static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001135CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1136 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001137 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001138 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001139 const APInt &Scale,
1140 ScalarEvolution &SE) {
1141 bool Interesting = false;
1142
1143 // Iterate over the add operands.
1144 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1145 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1146 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1147 APInt NewScale =
1148 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1149 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1150 // A multiplication of a constant with another add; recurse.
1151 Interesting |=
1152 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1153 cast<SCEVAddExpr>(Mul->getOperand(1))
1154 ->getOperands(),
1155 NewScale, SE);
1156 } else {
1157 // A multiplication of a constant with some other value. Update
1158 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001159 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1160 const SCEV *Key = SE.getMulExpr(MulOps);
1161 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001162 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001163 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001164 NewOps.push_back(Pair.first->first);
1165 } else {
1166 Pair.first->second += NewScale;
1167 // The map already had an entry for this value, which may indicate
1168 // a folding opportunity.
1169 Interesting = true;
1170 }
1171 }
1172 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1173 // Pull a buried constant out to the outside.
1174 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1175 Interesting = true;
1176 AccumulatedConstant += Scale * C->getValue()->getValue();
1177 } else {
1178 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001179 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001180 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001181 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001182 NewOps.push_back(Pair.first->first);
1183 } else {
1184 Pair.first->second += Scale;
1185 // The map already had an entry for this value, which may indicate
1186 // a folding opportunity.
1187 Interesting = true;
1188 }
1189 }
1190 }
1191
1192 return Interesting;
1193}
1194
1195namespace {
1196 struct APIntCompare {
1197 bool operator()(const APInt &LHS, const APInt &RHS) const {
1198 return LHS.ult(RHS);
1199 }
1200 };
1201}
1202
Dan Gohman6c0866c2009-05-24 23:45:28 +00001203/// getAddExpr - Get a canonical add expression, or something simpler if
1204/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001205const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1206 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001207 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001208 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001209#ifndef NDEBUG
1210 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1211 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1212 getEffectiveSCEVType(Ops[0]->getType()) &&
1213 "SCEVAddExpr operand types don't match!");
1214#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001215
Dan Gohmana10756e2010-01-21 02:09:26 +00001216 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1217 if (!HasNUW && HasNSW) {
1218 bool All = true;
1219 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1220 if (!isKnownNonNegative(Ops[i])) {
1221 All = false;
1222 break;
1223 }
1224 if (All) HasNUW = true;
1225 }
1226
Chris Lattner53e677a2004-04-02 20:23:17 +00001227 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001228 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001229
1230 // If there are any constants, fold them together.
1231 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001232 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001233 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001234 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001235 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001236 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001237 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1238 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001239 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001240 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001241 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001242 }
1243
1244 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001245 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001246 Ops.erase(Ops.begin());
1247 --Idx;
1248 }
1249 }
1250
Chris Lattner627018b2004-04-07 16:16:11 +00001251 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001252
Chris Lattner53e677a2004-04-02 20:23:17 +00001253 // Okay, check to see if the same value occurs in the operand list twice. If
1254 // so, merge them together into an multiply expression. Since we sorted the
1255 // list, these values are required to be adjacent.
1256 const Type *Ty = Ops[0]->getType();
1257 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1258 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1259 // Found a match, merge the two values into a multiply, and add any
1260 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001261 const SCEV *Two = getIntegerSCEV(2, Ty);
1262 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001263 if (Ops.size() == 2)
1264 return Mul;
1265 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1266 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001267 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001268 }
1269
Dan Gohman728c7f32009-05-08 21:03:19 +00001270 // Check for truncates. If all the operands are truncated from the same
1271 // type, see if factoring out the truncate would permit the result to be
1272 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1273 // if the contents of the resulting outer trunc fold to something simple.
1274 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1275 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1276 const Type *DstType = Trunc->getType();
1277 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001278 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001279 bool Ok = true;
1280 // Check all the operands to see if they can be represented in the
1281 // source type of the truncate.
1282 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1283 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1284 if (T->getOperand()->getType() != SrcType) {
1285 Ok = false;
1286 break;
1287 }
1288 LargeOps.push_back(T->getOperand());
1289 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1290 // This could be either sign or zero extension, but sign extension
1291 // is much more likely to be foldable here.
1292 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1293 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001294 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001295 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1296 if (const SCEVTruncateExpr *T =
1297 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1298 if (T->getOperand()->getType() != SrcType) {
1299 Ok = false;
1300 break;
1301 }
1302 LargeMulOps.push_back(T->getOperand());
1303 } else if (const SCEVConstant *C =
1304 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1305 // This could be either sign or zero extension, but sign extension
1306 // is much more likely to be foldable here.
1307 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1308 } else {
1309 Ok = false;
1310 break;
1311 }
1312 }
1313 if (Ok)
1314 LargeOps.push_back(getMulExpr(LargeMulOps));
1315 } else {
1316 Ok = false;
1317 break;
1318 }
1319 }
1320 if (Ok) {
1321 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001322 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001323 // If it folds to something simple, use it. Otherwise, don't.
1324 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1325 return getTruncateExpr(Fold, DstType);
1326 }
1327 }
1328
1329 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001330 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1331 ++Idx;
1332
1333 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001334 if (Idx < Ops.size()) {
1335 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001336 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001337 // If we have an add, expand the add operands onto the end of the operands
1338 // list.
1339 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1340 Ops.erase(Ops.begin()+Idx);
1341 DeletedAdd = true;
1342 }
1343
1344 // If we deleted at least one add, we added operands to the end of the list,
1345 // and they are not necessarily sorted. Recurse to resort and resimplify
1346 // any operands we just aquired.
1347 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001348 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 }
1350
1351 // Skip over the add expression until we get to a multiply.
1352 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1353 ++Idx;
1354
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001355 // Check to see if there are any folding opportunities present with
1356 // operands multiplied by constant values.
1357 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1358 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001359 DenseMap<const SCEV *, APInt> M;
1360 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001361 APInt AccumulatedConstant(BitWidth, 0);
1362 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1363 Ops, APInt(BitWidth, 1), *this)) {
1364 // Some interesting folding opportunity is present, so its worthwhile to
1365 // re-generate the operands list. Group the operands by constant scale,
1366 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001367 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1368 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001369 E = NewOps.end(); I != E; ++I)
1370 MulOpLists[M.find(*I)->second].push_back(*I);
1371 // Re-generate the operands list.
1372 Ops.clear();
1373 if (AccumulatedConstant != 0)
1374 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001375 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1376 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001377 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001378 Ops.push_back(getMulExpr(getConstant(I->first),
1379 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001380 if (Ops.empty())
1381 return getIntegerSCEV(0, Ty);
1382 if (Ops.size() == 1)
1383 return Ops[0];
1384 return getAddExpr(Ops);
1385 }
1386 }
1387
Chris Lattner53e677a2004-04-02 20:23:17 +00001388 // If we are adding something to a multiply expression, make sure the
1389 // something is not already an operand of the multiply. If so, merge it into
1390 // the multiply.
1391 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001392 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001393 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001394 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001396 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001397 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001398 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001399 if (Mul->getNumOperands() != 2) {
1400 // If the multiply has more than two operands, we must get the
1401 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001402 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001403 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001404 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001405 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001406 const SCEV *One = getIntegerSCEV(1, Ty);
1407 const SCEV *AddOne = getAddExpr(InnerMul, One);
1408 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001409 if (Ops.size() == 2) return OuterMul;
1410 if (AddOp < Idx) {
1411 Ops.erase(Ops.begin()+AddOp);
1412 Ops.erase(Ops.begin()+Idx-1);
1413 } else {
1414 Ops.erase(Ops.begin()+Idx);
1415 Ops.erase(Ops.begin()+AddOp-1);
1416 }
1417 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001418 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001419 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001420
Chris Lattner53e677a2004-04-02 20:23:17 +00001421 // Check this multiply against other multiplies being added together.
1422 for (unsigned OtherMulIdx = Idx+1;
1423 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1424 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001425 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001426 // If MulOp occurs in OtherMul, we can fold the two multiplies
1427 // together.
1428 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1429 OMulOp != e; ++OMulOp)
1430 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1431 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001432 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001433 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001434 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1435 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001436 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001437 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001438 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001439 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001440 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001441 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1442 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001443 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001444 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001445 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001446 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1447 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001448 if (Ops.size() == 2) return OuterMul;
1449 Ops.erase(Ops.begin()+Idx);
1450 Ops.erase(Ops.begin()+OtherMulIdx-1);
1451 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001452 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001453 }
1454 }
1455 }
1456 }
1457
1458 // If there are any add recurrences in the operands list, see if any other
1459 // added values are loop invariant. If so, we can fold them into the
1460 // recurrence.
1461 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1462 ++Idx;
1463
1464 // Scan over all recurrences, trying to fold loop invariants into them.
1465 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1466 // Scan all of the other operands to this add and add them to the vector if
1467 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001468 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001469 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1471 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1472 LIOps.push_back(Ops[i]);
1473 Ops.erase(Ops.begin()+i);
1474 --i; --e;
1475 }
1476
1477 // If we found some loop invariants, fold them into the recurrence.
1478 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001479 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 LIOps.push_back(AddRec->getStart());
1481
Dan Gohman0bba49c2009-07-07 17:06:11 +00001482 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001483 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001484 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001485
Dan Gohman355b4f32009-12-19 01:46:34 +00001486 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001487 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001488 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001489
Chris Lattner53e677a2004-04-02 20:23:17 +00001490 // If all of the other operands were loop invariant, we are done.
1491 if (Ops.size() == 1) return NewRec;
1492
1493 // Otherwise, add the folded AddRec by the non-liv parts.
1494 for (unsigned i = 0;; ++i)
1495 if (Ops[i] == AddRec) {
1496 Ops[i] = NewRec;
1497 break;
1498 }
Dan Gohman246b2562007-10-22 18:31:58 +00001499 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001500 }
1501
1502 // Okay, if there weren't any loop invariants to be folded, check to see if
1503 // there are multiple AddRec's with the same loop induction variable being
1504 // added together. If so, we can fold them.
1505 for (unsigned OtherIdx = Idx+1;
1506 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1507 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001508 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1510 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001511 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1512 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1514 if (i >= NewOps.size()) {
1515 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1516 OtherAddRec->op_end());
1517 break;
1518 }
Dan Gohman246b2562007-10-22 18:31:58 +00001519 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001521 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001522
1523 if (Ops.size() == 2) return NewAddRec;
1524
1525 Ops.erase(Ops.begin()+Idx);
1526 Ops.erase(Ops.begin()+OtherIdx-1);
1527 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001528 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001529 }
1530 }
1531
1532 // Otherwise couldn't fold anything into this recurrence. Move onto the
1533 // next one.
1534 }
1535
1536 // Okay, it looks like we really DO need an add expr. Check to see if we
1537 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001538 FoldingSetNodeID ID;
1539 ID.AddInteger(scAddExpr);
1540 ID.AddInteger(Ops.size());
1541 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1542 ID.AddPointer(Ops[i]);
1543 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001544 SCEVAddExpr *S =
1545 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1546 if (!S) {
1547 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1548 new (S) SCEVAddExpr(ID, Ops);
1549 UniqueSCEVs.InsertNode(S, IP);
1550 }
Dan Gohman3645b012009-10-09 00:10:36 +00001551 if (HasNUW) S->setHasNoUnsignedWrap(true);
1552 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001553 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001554}
1555
Dan Gohman6c0866c2009-05-24 23:45:28 +00001556/// getMulExpr - Get a canonical multiply expression, or something simpler if
1557/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001558const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1559 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001560 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001561 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001562#ifndef NDEBUG
1563 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1564 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1565 getEffectiveSCEVType(Ops[0]->getType()) &&
1566 "SCEVMulExpr operand types don't match!");
1567#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001568
Dan Gohmana10756e2010-01-21 02:09:26 +00001569 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1570 if (!HasNUW && HasNSW) {
1571 bool All = true;
1572 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1573 if (!isKnownNonNegative(Ops[i])) {
1574 All = false;
1575 break;
1576 }
1577 if (All) HasNUW = true;
1578 }
1579
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001581 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001582
1583 // If there are any constants, fold them together.
1584 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001585 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001586
1587 // C1*(C2+V) -> C1*C2 + C1*V
1588 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001589 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 if (Add->getNumOperands() == 2 &&
1591 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001592 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1593 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001594
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001596 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001598 ConstantInt *Fold = ConstantInt::get(getContext(),
1599 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001600 RHSC->getValue()->getValue());
1601 Ops[0] = getConstant(Fold);
1602 Ops.erase(Ops.begin()+1); // Erase the folded element
1603 if (Ops.size() == 1) return Ops[0];
1604 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 }
1606
1607 // If we are left with a constant one being multiplied, strip it off.
1608 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1609 Ops.erase(Ops.begin());
1610 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001611 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001612 // If we have a multiply of zero, it will always be zero.
1613 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001614 } else if (Ops[0]->isAllOnesValue()) {
1615 // If we have a mul by -1 of an add, try distributing the -1 among the
1616 // add operands.
1617 if (Ops.size() == 2)
1618 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1619 SmallVector<const SCEV *, 4> NewOps;
1620 bool AnyFolded = false;
1621 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1622 I != E; ++I) {
1623 const SCEV *Mul = getMulExpr(Ops[0], *I);
1624 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1625 NewOps.push_back(Mul);
1626 }
1627 if (AnyFolded)
1628 return getAddExpr(NewOps);
1629 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 }
1631 }
1632
1633 // Skip over the add expression until we get to a multiply.
1634 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1635 ++Idx;
1636
1637 if (Ops.size() == 1)
1638 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001639
Chris Lattner53e677a2004-04-02 20:23:17 +00001640 // If there are mul operands inline them all into this expression.
1641 if (Idx < Ops.size()) {
1642 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001643 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001644 // If we have an mul, expand the mul operands onto the end of the operands
1645 // list.
1646 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1647 Ops.erase(Ops.begin()+Idx);
1648 DeletedMul = true;
1649 }
1650
1651 // If we deleted at least one mul, we added operands to the end of the list,
1652 // and they are not necessarily sorted. Recurse to resort and resimplify
1653 // any operands we just aquired.
1654 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001655 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 }
1657
1658 // If there are any add recurrences in the operands list, see if any other
1659 // added values are loop invariant. If so, we can fold them into the
1660 // recurrence.
1661 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1662 ++Idx;
1663
1664 // Scan over all recurrences, trying to fold loop invariants into them.
1665 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1666 // Scan all of the other operands to this mul and add them to the vector if
1667 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001668 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001669 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001670 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1671 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1672 LIOps.push_back(Ops[i]);
1673 Ops.erase(Ops.begin()+i);
1674 --i; --e;
1675 }
1676
1677 // If we found some loop invariants, fold them into the recurrence.
1678 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001679 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001680 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001681 NewOps.reserve(AddRec->getNumOperands());
1682 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001683 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001684 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001685 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001686 } else {
1687 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001688 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001689 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001690 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001691 }
1692 }
1693
Dan Gohman355b4f32009-12-19 01:46:34 +00001694 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001695 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001696 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1697 HasNUW && AddRec->hasNoUnsignedWrap(),
1698 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001699
1700 // If all of the other operands were loop invariant, we are done.
1701 if (Ops.size() == 1) return NewRec;
1702
1703 // Otherwise, multiply the folded AddRec by the non-liv parts.
1704 for (unsigned i = 0;; ++i)
1705 if (Ops[i] == AddRec) {
1706 Ops[i] = NewRec;
1707 break;
1708 }
Dan Gohman246b2562007-10-22 18:31:58 +00001709 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001710 }
1711
1712 // Okay, if there weren't any loop invariants to be folded, check to see if
1713 // there are multiple AddRec's with the same loop induction variable being
1714 // multiplied together. If so, we can fold them.
1715 for (unsigned OtherIdx = Idx+1;
1716 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1717 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001718 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001719 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1720 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001721 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001722 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001724 const SCEV *B = F->getStepRecurrence(*this);
1725 const SCEV *D = G->getStepRecurrence(*this);
1726 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001727 getMulExpr(G, B),
1728 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001729 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001730 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001731 if (Ops.size() == 2) return NewAddRec;
1732
1733 Ops.erase(Ops.begin()+Idx);
1734 Ops.erase(Ops.begin()+OtherIdx-1);
1735 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001736 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 }
1738 }
1739
1740 // Otherwise couldn't fold anything into this recurrence. Move onto the
1741 // next one.
1742 }
1743
1744 // Okay, it looks like we really DO need an mul expr. Check to see if we
1745 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001746 FoldingSetNodeID ID;
1747 ID.AddInteger(scMulExpr);
1748 ID.AddInteger(Ops.size());
1749 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1750 ID.AddPointer(Ops[i]);
1751 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001752 SCEVMulExpr *S =
1753 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1754 if (!S) {
1755 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1756 new (S) SCEVMulExpr(ID, Ops);
1757 UniqueSCEVs.InsertNode(S, IP);
1758 }
Dan Gohman3645b012009-10-09 00:10:36 +00001759 if (HasNUW) S->setHasNoUnsignedWrap(true);
1760 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001761 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001762}
1763
Andreas Bolka8a11c982009-08-07 22:55:26 +00001764/// getUDivExpr - Get a canonical unsigned division expression, or something
1765/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001766const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1767 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001768 assert(getEffectiveSCEVType(LHS->getType()) ==
1769 getEffectiveSCEVType(RHS->getType()) &&
1770 "SCEVUDivExpr operand types don't match!");
1771
Dan Gohman622ed672009-05-04 22:02:23 +00001772 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001773 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001774 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001775 if (RHSC->isZero())
1776 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001777
Dan Gohman185cf032009-05-08 20:18:49 +00001778 // Determine if the division can be folded into the operands of
1779 // its operands.
1780 // TODO: Generalize this to non-constants by using known-bits information.
1781 const Type *Ty = LHS->getType();
1782 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1783 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1784 // For non-power-of-two values, effectively round the value up to the
1785 // nearest power of two.
1786 if (!RHSC->getValue()->getValue().isPowerOf2())
1787 ++MaxShiftAmt;
1788 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001789 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001790 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1791 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1792 if (const SCEVConstant *Step =
1793 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1794 if (!Step->getValue()->getValue()
1795 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001796 getZeroExtendExpr(AR, ExtTy) ==
1797 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1798 getZeroExtendExpr(Step, ExtTy),
1799 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001800 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001801 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1802 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1803 return getAddRecExpr(Operands, AR->getLoop());
1804 }
1805 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001806 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001807 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001808 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1809 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1810 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001811 // Find an operand that's safely divisible.
1812 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001813 const SCEV *Op = M->getOperand(i);
1814 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001815 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001816 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1817 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001818 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001819 Operands[i] = Div;
1820 return getMulExpr(Operands);
1821 }
1822 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001823 }
Dan Gohman185cf032009-05-08 20:18:49 +00001824 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001825 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001826 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001827 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1828 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1829 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1830 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001831 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001832 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001833 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1834 break;
1835 Operands.push_back(Op);
1836 }
1837 if (Operands.size() == A->getNumOperands())
1838 return getAddExpr(Operands);
1839 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001840 }
Dan Gohman185cf032009-05-08 20:18:49 +00001841
1842 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001843 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001844 Constant *LHSCV = LHSC->getValue();
1845 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001846 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001847 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001848 }
1849 }
1850
Dan Gohman1c343752009-06-27 21:21:31 +00001851 FoldingSetNodeID ID;
1852 ID.AddInteger(scUDivExpr);
1853 ID.AddPointer(LHS);
1854 ID.AddPointer(RHS);
1855 void *IP = 0;
1856 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1857 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001858 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001859 UniqueSCEVs.InsertNode(S, IP);
1860 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001861}
1862
1863
Dan Gohman6c0866c2009-05-24 23:45:28 +00001864/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1865/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001866const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001867 const SCEV *Step, const Loop *L,
1868 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001869 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001870 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001871 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001872 if (StepChrec->getLoop() == L) {
1873 Operands.insert(Operands.end(), StepChrec->op_begin(),
1874 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001875 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001876 }
1877
1878 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001879 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001880}
1881
Dan Gohman6c0866c2009-05-24 23:45:28 +00001882/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1883/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001884const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001885ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001886 const Loop *L,
1887 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001888 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001889#ifndef NDEBUG
1890 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1891 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1892 getEffectiveSCEVType(Operands[0]->getType()) &&
1893 "SCEVAddRecExpr operand types don't match!");
1894#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001895
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001896 if (Operands.back()->isZero()) {
1897 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001898 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001899 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001900
Dan Gohmana10756e2010-01-21 02:09:26 +00001901 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1902 if (!HasNUW && HasNSW) {
1903 bool All = true;
1904 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1905 if (!isKnownNonNegative(Operands[i])) {
1906 All = false;
1907 break;
1908 }
1909 if (All) HasNUW = true;
1910 }
1911
Dan Gohmand9cc7492008-08-08 18:33:12 +00001912 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001913 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001914 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001915 if (L->contains(NestedLoop->getHeader()) ?
1916 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1917 (!NestedLoop->contains(L->getHeader()) &&
1918 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001919 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001920 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001921 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001922 // AddRecs require their operands be loop-invariant with respect to their
1923 // loops. Don't perform this transformation if it would break this
1924 // requirement.
1925 bool AllInvariant = true;
1926 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1927 if (!Operands[i]->isLoopInvariant(L)) {
1928 AllInvariant = false;
1929 break;
1930 }
1931 if (AllInvariant) {
1932 NestedOperands[0] = getAddRecExpr(Operands, L);
1933 AllInvariant = true;
1934 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1935 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1936 AllInvariant = false;
1937 break;
1938 }
1939 if (AllInvariant)
1940 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00001941 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00001942 }
1943 // Reset Operands to its original state.
1944 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001945 }
1946 }
1947
Dan Gohman67847532010-01-19 22:27:22 +00001948 // Okay, it looks like we really DO need an addrec expr. Check to see if we
1949 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001950 FoldingSetNodeID ID;
1951 ID.AddInteger(scAddRecExpr);
1952 ID.AddInteger(Operands.size());
1953 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1954 ID.AddPointer(Operands[i]);
1955 ID.AddPointer(L);
1956 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001957 SCEVAddRecExpr *S =
1958 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1959 if (!S) {
1960 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1961 new (S) SCEVAddRecExpr(ID, Operands, L);
1962 UniqueSCEVs.InsertNode(S, IP);
1963 }
Dan Gohman3645b012009-10-09 00:10:36 +00001964 if (HasNUW) S->setHasNoUnsignedWrap(true);
1965 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001966 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001967}
1968
Dan Gohman9311ef62009-06-24 14:49:00 +00001969const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1970 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001971 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001972 Ops.push_back(LHS);
1973 Ops.push_back(RHS);
1974 return getSMaxExpr(Ops);
1975}
1976
Dan Gohman0bba49c2009-07-07 17:06:11 +00001977const SCEV *
1978ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001979 assert(!Ops.empty() && "Cannot get empty smax!");
1980 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001981#ifndef NDEBUG
1982 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1983 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1984 getEffectiveSCEVType(Ops[0]->getType()) &&
1985 "SCEVSMaxExpr operand types don't match!");
1986#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001987
1988 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001989 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001990
1991 // If there are any constants, fold them together.
1992 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001993 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001994 ++Idx;
1995 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001996 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001997 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001998 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001999 APIntOps::smax(LHSC->getValue()->getValue(),
2000 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002001 Ops[0] = getConstant(Fold);
2002 Ops.erase(Ops.begin()+1); // Erase the folded element
2003 if (Ops.size() == 1) return Ops[0];
2004 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002005 }
2006
Dan Gohmane5aceed2009-06-24 14:46:22 +00002007 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002008 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2009 Ops.erase(Ops.begin());
2010 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002011 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2012 // If we have an smax with a constant maximum-int, it will always be
2013 // maximum-int.
2014 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002015 }
2016 }
2017
2018 if (Ops.size() == 1) return Ops[0];
2019
2020 // Find the first SMax
2021 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2022 ++Idx;
2023
2024 // Check to see if one of the operands is an SMax. If so, expand its operands
2025 // onto our operand list, and recurse to simplify.
2026 if (Idx < Ops.size()) {
2027 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002028 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002029 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2030 Ops.erase(Ops.begin()+Idx);
2031 DeletedSMax = true;
2032 }
2033
2034 if (DeletedSMax)
2035 return getSMaxExpr(Ops);
2036 }
2037
2038 // Okay, check to see if the same value occurs in the operand list twice. If
2039 // so, delete one. Since we sorted the list, these values are required to
2040 // be adjacent.
2041 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2042 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2043 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2044 --i; --e;
2045 }
2046
2047 if (Ops.size() == 1) return Ops[0];
2048
2049 assert(!Ops.empty() && "Reduced smax down to nothing!");
2050
Nick Lewycky3e630762008-02-20 06:48:22 +00002051 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002052 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002053 FoldingSetNodeID ID;
2054 ID.AddInteger(scSMaxExpr);
2055 ID.AddInteger(Ops.size());
2056 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2057 ID.AddPointer(Ops[i]);
2058 void *IP = 0;
2059 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2060 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002061 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002062 UniqueSCEVs.InsertNode(S, IP);
2063 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002064}
2065
Dan Gohman9311ef62009-06-24 14:49:00 +00002066const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2067 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002068 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002069 Ops.push_back(LHS);
2070 Ops.push_back(RHS);
2071 return getUMaxExpr(Ops);
2072}
2073
Dan Gohman0bba49c2009-07-07 17:06:11 +00002074const SCEV *
2075ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002076 assert(!Ops.empty() && "Cannot get empty umax!");
2077 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002078#ifndef NDEBUG
2079 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2080 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2081 getEffectiveSCEVType(Ops[0]->getType()) &&
2082 "SCEVUMaxExpr operand types don't match!");
2083#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002084
2085 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002086 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002087
2088 // If there are any constants, fold them together.
2089 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002090 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002091 ++Idx;
2092 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002093 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002094 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002095 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002096 APIntOps::umax(LHSC->getValue()->getValue(),
2097 RHSC->getValue()->getValue()));
2098 Ops[0] = getConstant(Fold);
2099 Ops.erase(Ops.begin()+1); // Erase the folded element
2100 if (Ops.size() == 1) return Ops[0];
2101 LHSC = cast<SCEVConstant>(Ops[0]);
2102 }
2103
Dan Gohmane5aceed2009-06-24 14:46:22 +00002104 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002105 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2106 Ops.erase(Ops.begin());
2107 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002108 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2109 // If we have an umax with a constant maximum-int, it will always be
2110 // maximum-int.
2111 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002112 }
2113 }
2114
2115 if (Ops.size() == 1) return Ops[0];
2116
2117 // Find the first UMax
2118 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2119 ++Idx;
2120
2121 // Check to see if one of the operands is a UMax. If so, expand its operands
2122 // onto our operand list, and recurse to simplify.
2123 if (Idx < Ops.size()) {
2124 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002125 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002126 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2127 Ops.erase(Ops.begin()+Idx);
2128 DeletedUMax = true;
2129 }
2130
2131 if (DeletedUMax)
2132 return getUMaxExpr(Ops);
2133 }
2134
2135 // Okay, check to see if the same value occurs in the operand list twice. If
2136 // so, delete one. Since we sorted the list, these values are required to
2137 // be adjacent.
2138 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2139 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2140 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2141 --i; --e;
2142 }
2143
2144 if (Ops.size() == 1) return Ops[0];
2145
2146 assert(!Ops.empty() && "Reduced umax down to nothing!");
2147
2148 // Okay, it looks like we really DO need a umax expr. Check to see if we
2149 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002150 FoldingSetNodeID ID;
2151 ID.AddInteger(scUMaxExpr);
2152 ID.AddInteger(Ops.size());
2153 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2154 ID.AddPointer(Ops[i]);
2155 void *IP = 0;
2156 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2157 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002158 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002159 UniqueSCEVs.InsertNode(S, IP);
2160 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002161}
2162
Dan Gohman9311ef62009-06-24 14:49:00 +00002163const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2164 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002165 // ~smax(~x, ~y) == smin(x, y).
2166 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2167}
2168
Dan Gohman9311ef62009-06-24 14:49:00 +00002169const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2170 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002171 // ~umax(~x, ~y) == umin(x, y)
2172 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2173}
2174
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002175const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2176 unsigned FieldNo) {
2177 // If we have TargetData we can determine the constant offset.
2178 if (TD) {
2179 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2180 const StructLayout &SL = *TD->getStructLayout(STy);
2181 uint64_t Offset = SL.getElementOffset(FieldNo);
2182 return getIntegerSCEV(Offset, IntPtrTy);
2183 }
2184
2185 // Field 0 is always at offset 0.
2186 if (FieldNo == 0) {
2187 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2188 return getIntegerSCEV(0, Ty);
2189 }
2190
2191 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2192 // already have one, otherwise create a new one.
2193 FoldingSetNodeID ID;
2194 ID.AddInteger(scFieldOffset);
2195 ID.AddPointer(STy);
2196 ID.AddInteger(FieldNo);
2197 void *IP = 0;
2198 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2199 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2200 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2201 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2202 UniqueSCEVs.InsertNode(S, IP);
2203 return S;
2204}
2205
2206const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2207 // If we have TargetData we can determine the constant size.
2208 if (TD && AllocTy->isSized()) {
2209 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2210 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2211 }
2212
2213 // Expand an array size into the element size times the number
2214 // of elements.
2215 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2216 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2217 return getMulExpr(
2218 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2219 ATy->getNumElements())));
2220 }
2221
2222 // Expand a vector size into the element size times the number
2223 // of elements.
2224 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2225 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2226 return getMulExpr(
2227 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2228 VTy->getNumElements())));
2229 }
2230
2231 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2232 // already have one, otherwise create a new one.
2233 FoldingSetNodeID ID;
2234 ID.AddInteger(scAllocSize);
2235 ID.AddPointer(AllocTy);
2236 void *IP = 0;
2237 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2238 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2239 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2240 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2241 UniqueSCEVs.InsertNode(S, IP);
2242 return S;
2243}
2244
Dan Gohman0bba49c2009-07-07 17:06:11 +00002245const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002246 // Don't attempt to do anything other than create a SCEVUnknown object
2247 // here. createSCEV only calls getUnknown after checking for all other
2248 // interesting possibilities, and any other code that calls getUnknown
2249 // is doing so in order to hide a value from SCEV canonicalization.
2250
Dan Gohman1c343752009-06-27 21:21:31 +00002251 FoldingSetNodeID ID;
2252 ID.AddInteger(scUnknown);
2253 ID.AddPointer(V);
2254 void *IP = 0;
2255 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2256 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002257 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002258 UniqueSCEVs.InsertNode(S, IP);
2259 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002260}
2261
Chris Lattner53e677a2004-04-02 20:23:17 +00002262//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002263// Basic SCEV Analysis and PHI Idiom Recognition Code
2264//
2265
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002266/// isSCEVable - Test if values of the given type are analyzable within
2267/// the SCEV framework. This primarily includes integer types, and it
2268/// can optionally include pointer types if the ScalarEvolution class
2269/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002270bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002271 // Integers and pointers are always SCEVable.
2272 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002273}
2274
2275/// getTypeSizeInBits - Return the size in bits of the specified type,
2276/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002277uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002278 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2279
2280 // If we have a TargetData, use it!
2281 if (TD)
2282 return TD->getTypeSizeInBits(Ty);
2283
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002284 // Integer types have fixed sizes.
2285 if (Ty->isInteger())
2286 return Ty->getPrimitiveSizeInBits();
2287
2288 // The only other support type is pointer. Without TargetData, conservatively
2289 // assume pointers are 64-bit.
2290 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2291 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002292}
2293
2294/// getEffectiveSCEVType - Return a type with the same bitwidth as
2295/// the given type and which represents how SCEV will treat the given
2296/// type, for which isSCEVable must return true. For pointer types,
2297/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002298const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002299 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2300
2301 if (Ty->isInteger())
2302 return Ty;
2303
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002304 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002305 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002306 if (TD) return TD->getIntPtrType(getContext());
2307
2308 // Without TargetData, conservatively assume pointers are 64-bit.
2309 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002310}
Chris Lattner53e677a2004-04-02 20:23:17 +00002311
Dan Gohman0bba49c2009-07-07 17:06:11 +00002312const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002313 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002314}
2315
Chris Lattner53e677a2004-04-02 20:23:17 +00002316/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2317/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002318const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002319 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002320
Dan Gohman0bba49c2009-07-07 17:06:11 +00002321 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002322 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002323 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002324 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002325 return S;
2326}
2327
Dan Gohman6bbcba12009-06-24 00:54:57 +00002328/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002329/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002330const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002331 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002332 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002333}
2334
2335/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2336///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002337const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002338 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002339 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002340 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002341
2342 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002343 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002344 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002345 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002346}
2347
2348/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002349const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002350 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002351 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002352 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002353
2354 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002355 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002356 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002357 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002358 return getMinusSCEV(AllOnes, V);
2359}
2360
2361/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2362///
Dan Gohman9311ef62009-06-24 14:49:00 +00002363const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2364 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002365 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002366 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002367}
2368
2369/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2370/// input value to the specified type. If the type must be extended, it is zero
2371/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002372const SCEV *
2373ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002374 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002375 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002376 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2377 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002378 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002379 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002380 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002381 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002382 return getTruncateExpr(V, Ty);
2383 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002384}
2385
2386/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2387/// input value to the specified type. If the type must be extended, it is sign
2388/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002389const SCEV *
2390ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002391 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002392 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002393 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2394 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002395 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002396 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002397 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002398 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002399 return getTruncateExpr(V, Ty);
2400 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002401}
2402
Dan Gohman467c4302009-05-13 03:46:30 +00002403/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2404/// input value to the specified type. If the type must be extended, it is zero
2405/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002406const SCEV *
2407ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002408 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002409 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2410 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002411 "Cannot noop or zero extend with non-integer arguments!");
2412 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2413 "getNoopOrZeroExtend cannot truncate!");
2414 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2415 return V; // No conversion
2416 return getZeroExtendExpr(V, Ty);
2417}
2418
2419/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2420/// input value to the specified type. If the type must be extended, it is sign
2421/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002422const SCEV *
2423ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002424 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002425 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2426 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002427 "Cannot noop or sign extend with non-integer arguments!");
2428 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2429 "getNoopOrSignExtend cannot truncate!");
2430 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2431 return V; // No conversion
2432 return getSignExtendExpr(V, Ty);
2433}
2434
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002435/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2436/// the input value to the specified type. If the type must be extended,
2437/// it is extended with unspecified bits. The conversion must not be
2438/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002439const SCEV *
2440ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002441 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002442 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2443 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002444 "Cannot noop or any extend with non-integer arguments!");
2445 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2446 "getNoopOrAnyExtend cannot truncate!");
2447 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2448 return V; // No conversion
2449 return getAnyExtendExpr(V, Ty);
2450}
2451
Dan Gohman467c4302009-05-13 03:46:30 +00002452/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2453/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002454const SCEV *
2455ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002456 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002457 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2458 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002459 "Cannot truncate or noop with non-integer arguments!");
2460 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2461 "getTruncateOrNoop cannot extend!");
2462 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2463 return V; // No conversion
2464 return getTruncateExpr(V, Ty);
2465}
2466
Dan Gohmana334aa72009-06-22 00:31:57 +00002467/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2468/// the types using zero-extension, and then perform a umax operation
2469/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002470const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2471 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002472 const SCEV *PromotedLHS = LHS;
2473 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002474
2475 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2476 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2477 else
2478 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2479
2480 return getUMaxExpr(PromotedLHS, PromotedRHS);
2481}
2482
Dan Gohmanc9759e82009-06-22 15:03:27 +00002483/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2484/// the types using zero-extension, and then perform a umin operation
2485/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002486const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2487 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002488 const SCEV *PromotedLHS = LHS;
2489 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002490
2491 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2492 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2493 else
2494 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2495
2496 return getUMinExpr(PromotedLHS, PromotedRHS);
2497}
2498
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002499/// PushDefUseChildren - Push users of the given Instruction
2500/// onto the given Worklist.
2501static void
2502PushDefUseChildren(Instruction *I,
2503 SmallVectorImpl<Instruction *> &Worklist) {
2504 // Push the def-use children onto the Worklist stack.
2505 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2506 UI != UE; ++UI)
2507 Worklist.push_back(cast<Instruction>(UI));
2508}
2509
2510/// ForgetSymbolicValue - This looks up computed SCEV values for all
2511/// instructions that depend on the given instruction and removes them from
2512/// the Scalars map if they reference SymName. This is used during PHI
2513/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002514void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002515ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2516 SmallVector<Instruction *, 16> Worklist;
2517 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002518
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002519 SmallPtrSet<Instruction *, 8> Visited;
2520 Visited.insert(I);
2521 while (!Worklist.empty()) {
2522 Instruction *I = Worklist.pop_back_val();
2523 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002524
Dan Gohman5d984912009-12-18 01:14:11 +00002525 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002526 Scalars.find(static_cast<Value *>(I));
2527 if (It != Scalars.end()) {
2528 // Short-circuit the def-use traversal if the symbolic name
2529 // ceases to appear in expressions.
2530 if (!It->second->hasOperand(SymName))
2531 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002532
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002533 // SCEVUnknown for a PHI either means that it has an unrecognized
2534 // structure, or it's a PHI that's in the progress of being computed
2535 // by createNodeForPHI. In the former case, additional loop trip
2536 // count information isn't going to change anything. In the later
2537 // case, createNodeForPHI will perform the necessary updates on its
2538 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002539 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2540 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002541 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002542 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002543 }
2544
2545 PushDefUseChildren(I, Worklist);
2546 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002547}
Chris Lattner53e677a2004-04-02 20:23:17 +00002548
2549/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2550/// a loop header, making it a potential recurrence, or it doesn't.
2551///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002552const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002553 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002554 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002555 if (L->getHeader() == PN->getParent()) {
2556 // If it lives in the loop header, it has two incoming values, one
2557 // from outside the loop, and one from inside.
2558 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2559 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002560
Chris Lattner53e677a2004-04-02 20:23:17 +00002561 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002562 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 assert(Scalars.find(PN) == Scalars.end() &&
2564 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002565 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002566
2567 // Using this symbolic name for the PHI, analyze the value coming around
2568 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002569 Value *BEValueV = PN->getIncomingValue(BackEdge);
2570 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002571
2572 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2573 // has a special value for the first iteration of the loop.
2574
2575 // If the value coming around the backedge is an add with the symbolic
2576 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002577 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002578 // If there is a single occurrence of the symbolic value, replace it
2579 // with a recurrence.
2580 unsigned FoundIndex = Add->getNumOperands();
2581 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2582 if (Add->getOperand(i) == SymbolicName)
2583 if (FoundIndex == e) {
2584 FoundIndex = i;
2585 break;
2586 }
2587
2588 if (FoundIndex != Add->getNumOperands()) {
2589 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002590 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002591 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2592 if (i != FoundIndex)
2593 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002594 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002595
2596 // This is not a valid addrec if the step amount is varying each
2597 // loop iteration, but is not itself an addrec in this loop.
2598 if (Accum->isLoopInvariant(L) ||
2599 (isa<SCEVAddRecExpr>(Accum) &&
2600 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002601 bool HasNUW = false;
2602 bool HasNSW = false;
2603
2604 // If the increment doesn't overflow, then neither the addrec nor
2605 // the post-increment will overflow.
2606 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2607 if (OBO->hasNoUnsignedWrap())
2608 HasNUW = true;
2609 if (OBO->hasNoSignedWrap())
2610 HasNSW = true;
2611 }
2612
Dan Gohman64a845e2009-06-24 04:48:43 +00002613 const SCEV *StartVal =
2614 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002615 const SCEV *PHISCEV =
2616 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002617
Dan Gohmana10756e2010-01-21 02:09:26 +00002618 // Since the no-wrap flags are on the increment, they apply to the
2619 // post-incremented value as well.
2620 if (Accum->isLoopInvariant(L))
2621 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2622 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002623
2624 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002625 // to be symbolic. We now need to go back and purge all of the
2626 // entries for the scalars that use the symbolic expression.
2627 ForgetSymbolicName(PN, SymbolicName);
2628 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002629 return PHISCEV;
2630 }
2631 }
Dan Gohman622ed672009-05-04 22:02:23 +00002632 } else if (const SCEVAddRecExpr *AddRec =
2633 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002634 // Otherwise, this could be a loop like this:
2635 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2636 // In this case, j = {1,+,1} and BEValue is j.
2637 // Because the other in-value of i (0) fits the evolution of BEValue
2638 // i really is an addrec evolution.
2639 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002640 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002641
2642 // If StartVal = j.start - j.stride, we can use StartVal as the
2643 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002644 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002645 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002646 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002647 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002648
2649 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002650 // to be symbolic. We now need to go back and purge all of the
2651 // entries for the scalars that use the symbolic expression.
2652 ForgetSymbolicName(PN, SymbolicName);
2653 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002654 return PHISCEV;
2655 }
2656 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002657 }
2658
2659 return SymbolicName;
2660 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002661
Dan Gohmana653fc52009-07-14 14:06:25 +00002662 // It's tempting to recognize PHIs with a unique incoming value, however
2663 // this leads passes like indvars to break LCSSA form. Fortunately, such
2664 // PHIs are rare, as instcombine zaps them.
2665
Chris Lattner53e677a2004-04-02 20:23:17 +00002666 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002667 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002668}
2669
Dan Gohman26466c02009-05-08 20:26:55 +00002670/// createNodeForGEP - Expand GEP instructions into add and multiply
2671/// operations. This allows them to be analyzed by regular SCEV code.
2672///
Dan Gohmand281ed22009-12-18 02:09:29 +00002673const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002674
Dan Gohmand281ed22009-12-18 02:09:29 +00002675 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002676 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002677 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002678 // Don't attempt to analyze GEPs over unsized objects.
2679 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2680 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002681 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002682 gep_type_iterator GTI = gep_type_begin(GEP);
2683 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2684 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002685 I != E; ++I) {
2686 Value *Index = *I;
2687 // Compute the (potentially symbolic) offset in bytes for this index.
2688 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2689 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002690 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002691 TotalOffset = getAddExpr(TotalOffset,
Dan Gohmand281ed22009-12-18 02:09:29 +00002692 getFieldOffsetExpr(STy, FieldNo),
2693 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002694 } else {
2695 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002696 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002697 if (!isa<PointerType>(LocalOffset->getType()))
2698 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002699 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002700 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohmand281ed22009-12-18 02:09:29 +00002701 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI),
2702 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2703 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2704 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002705 }
2706 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002707 return getAddExpr(getSCEV(Base), TotalOffset,
2708 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002709}
2710
Nick Lewycky83bb0052007-11-22 07:59:40 +00002711/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2712/// guaranteed to end in (at every loop iteration). It is, at the same time,
2713/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2714/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002715uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002716ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002717 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002718 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002719
Dan Gohman622ed672009-05-04 22:02:23 +00002720 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002721 return std::min(GetMinTrailingZeros(T->getOperand()),
2722 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002723
Dan Gohman622ed672009-05-04 22:02:23 +00002724 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(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 SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002731 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2732 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2733 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002734 }
2735
Dan Gohman622ed672009-05-04 22:02:23 +00002736 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002737 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002738 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002739 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002740 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002741 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002742 }
2743
Dan Gohman622ed672009-05-04 22:02:23 +00002744 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002745 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002746 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2747 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002748 for (unsigned i = 1, e = M->getNumOperands();
2749 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002750 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002751 BitWidth);
2752 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002753 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002754
Dan Gohman622ed672009-05-04 22:02:23 +00002755 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002756 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002757 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002758 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002759 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002760 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002761 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002762
Dan Gohman622ed672009-05-04 22:02:23 +00002763 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002764 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002765 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002766 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002767 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002768 return MinOpRes;
2769 }
2770
Dan Gohman622ed672009-05-04 22:02:23 +00002771 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002772 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002773 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002774 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002775 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002776 return MinOpRes;
2777 }
2778
Dan Gohman2c364ad2009-06-19 23:29:04 +00002779 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2780 // For a SCEVUnknown, ask ValueTracking.
2781 unsigned BitWidth = getTypeSizeInBits(U->getType());
2782 APInt Mask = APInt::getAllOnesValue(BitWidth);
2783 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2784 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2785 return Zeros.countTrailingOnes();
2786 }
2787
2788 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002789 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002790}
Chris Lattner53e677a2004-04-02 20:23:17 +00002791
Dan Gohman85b05a22009-07-13 21:35:55 +00002792/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2793///
2794ConstantRange
2795ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002796
2797 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002798 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002799
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002800 unsigned BitWidth = getTypeSizeInBits(S->getType());
2801 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2802
2803 // If the value has known zeros, the maximum unsigned value will have those
2804 // known zeros as well.
2805 uint32_t TZ = GetMinTrailingZeros(S);
2806 if (TZ != 0)
2807 ConservativeResult =
2808 ConstantRange(APInt::getMinValue(BitWidth),
2809 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2810
Dan Gohman85b05a22009-07-13 21:35:55 +00002811 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2812 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2813 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2814 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002815 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002816 }
2817
2818 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2819 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2820 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2821 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002822 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002823 }
2824
2825 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2826 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2827 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2828 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002829 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002830 }
2831
2832 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2833 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2834 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2835 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002836 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002837 }
2838
2839 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2840 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2841 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002842 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002843 }
2844
2845 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2846 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002847 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002848 }
2849
2850 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2851 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002852 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002853 }
2854
2855 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2856 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002857 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002858 }
2859
Dan Gohman85b05a22009-07-13 21:35:55 +00002860 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002861 // If there's no unsigned wrap, the value will never be less than its
2862 // initial value.
2863 if (AddRec->hasNoUnsignedWrap())
2864 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2865 ConservativeResult =
2866 ConstantRange(C->getValue()->getValue(),
2867 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002868
2869 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002870 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002871 const Type *Ty = AddRec->getType();
2872 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002873 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2874 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002875 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2876
2877 const SCEV *Start = AddRec->getStart();
2878 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2879
2880 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002881 if (!AddRec->hasNoUnsignedWrap())
2882 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002883
2884 ConstantRange StartRange = getUnsignedRange(Start);
2885 ConstantRange EndRange = getUnsignedRange(End);
2886 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2887 EndRange.getUnsignedMin());
2888 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2889 EndRange.getUnsignedMax());
2890 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002891 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002892 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002893 }
2894 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002895
2896 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002897 }
2898
2899 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2900 // For a SCEVUnknown, ask ValueTracking.
2901 unsigned BitWidth = getTypeSizeInBits(U->getType());
2902 APInt Mask = APInt::getAllOnesValue(BitWidth);
2903 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2904 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002905 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002906 return ConservativeResult;
2907 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002908 }
2909
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002910 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002911}
2912
Dan Gohman85b05a22009-07-13 21:35:55 +00002913/// getSignedRange - Determine the signed range for a particular SCEV.
2914///
2915ConstantRange
2916ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002917
Dan Gohman85b05a22009-07-13 21:35:55 +00002918 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2919 return ConstantRange(C->getValue()->getValue());
2920
Dan Gohman52fddd32010-01-26 04:40:18 +00002921 unsigned BitWidth = getTypeSizeInBits(S->getType());
2922 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2923
2924 // If the value has known zeros, the maximum signed value will have those
2925 // known zeros as well.
2926 uint32_t TZ = GetMinTrailingZeros(S);
2927 if (TZ != 0)
2928 ConservativeResult =
2929 ConstantRange(APInt::getSignedMinValue(BitWidth),
2930 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2931
Dan Gohman85b05a22009-07-13 21:35:55 +00002932 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2933 ConstantRange X = getSignedRange(Add->getOperand(0));
2934 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2935 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002936 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002937 }
2938
Dan Gohman85b05a22009-07-13 21:35:55 +00002939 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2940 ConstantRange X = getSignedRange(Mul->getOperand(0));
2941 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2942 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002943 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002944 }
2945
Dan Gohman85b05a22009-07-13 21:35:55 +00002946 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2947 ConstantRange X = getSignedRange(SMax->getOperand(0));
2948 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2949 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002950 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002951 }
Dan Gohman62849c02009-06-24 01:05:09 +00002952
Dan Gohman85b05a22009-07-13 21:35:55 +00002953 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2954 ConstantRange X = getSignedRange(UMax->getOperand(0));
2955 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2956 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002957 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002958 }
Dan Gohman62849c02009-06-24 01:05:09 +00002959
Dan Gohman85b05a22009-07-13 21:35:55 +00002960 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2961 ConstantRange X = getSignedRange(UDiv->getLHS());
2962 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00002963 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002964 }
Dan Gohman62849c02009-06-24 01:05:09 +00002965
Dan Gohman85b05a22009-07-13 21:35:55 +00002966 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2967 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002968 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002969 }
2970
2971 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2972 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002973 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002974 }
2975
2976 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2977 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002978 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002979 }
2980
Dan Gohman85b05a22009-07-13 21:35:55 +00002981 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002982 // If there's no signed wrap, and all the operands have the same sign or
2983 // zero, the value won't ever change sign.
2984 if (AddRec->hasNoSignedWrap()) {
2985 bool AllNonNeg = true;
2986 bool AllNonPos = true;
2987 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
2988 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
2989 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
2990 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002991 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00002992 ConservativeResult = ConservativeResult.intersectWith(
2993 ConstantRange(APInt(BitWidth, 0),
2994 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00002995 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00002996 ConservativeResult = ConservativeResult.intersectWith(
2997 ConstantRange(APInt::getSignedMinValue(BitWidth),
2998 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00002999 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003000
3001 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003002 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003003 const Type *Ty = AddRec->getType();
3004 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003005 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3006 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003007 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3008
3009 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003010 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3011
3012 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003013 if (!AddRec->hasNoSignedWrap())
3014 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003015
3016 ConstantRange StartRange = getSignedRange(Start);
3017 ConstantRange EndRange = getSignedRange(End);
3018 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3019 EndRange.getSignedMin());
3020 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3021 EndRange.getSignedMax());
3022 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003023 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003024 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003025 }
Dan Gohman62849c02009-06-24 01:05:09 +00003026 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003027
3028 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003029 }
3030
Dan Gohman2c364ad2009-06-19 23:29:04 +00003031 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3032 // For a SCEVUnknown, ask ValueTracking.
Dan Gohmana10756e2010-01-21 02:09:26 +00003033 if (!U->getValue()->getType()->isInteger() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003034 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003035 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3036 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003037 return ConservativeResult;
3038 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003039 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003040 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003041 }
3042
Dan Gohman52fddd32010-01-26 04:40:18 +00003043 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003044}
3045
Chris Lattner53e677a2004-04-02 20:23:17 +00003046/// createSCEV - We know that there is no SCEV for the specified value.
3047/// Analyze the expression.
3048///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003049const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003050 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003051 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003052
Dan Gohman6c459a22008-06-22 19:56:46 +00003053 unsigned Opcode = Instruction::UserOp1;
3054 if (Instruction *I = dyn_cast<Instruction>(V))
3055 Opcode = I->getOpcode();
3056 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3057 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003058 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3059 return getConstant(CI);
3060 else if (isa<ConstantPointerNull>(V))
3061 return getIntegerSCEV(0, V->getType());
3062 else if (isa<UndefValue>(V))
3063 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003064 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3065 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003066 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003067 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003068
Dan Gohmanca178902009-07-17 20:47:02 +00003069 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003070 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003071 case Instruction::Add:
3072 // Don't transfer the NSW and NUW bits from the Add instruction to the
3073 // Add expression, because the Instruction may be guarded by control
3074 // flow and the no-overflow bits may not be valid for the expression in
3075 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003076 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003077 getSCEV(U->getOperand(1)));
3078 case Instruction::Mul:
3079 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3080 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003081 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003082 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003083 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003084 return getUDivExpr(getSCEV(U->getOperand(0)),
3085 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003086 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003087 return getMinusSCEV(getSCEV(U->getOperand(0)),
3088 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003089 case Instruction::And:
3090 // For an expression like x&255 that merely masks off the high bits,
3091 // use zext(trunc(x)) as the SCEV expression.
3092 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003093 if (CI->isNullValue())
3094 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003095 if (CI->isAllOnesValue())
3096 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003097 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003098
3099 // Instcombine's ShrinkDemandedConstant may strip bits out of
3100 // constants, obscuring what would otherwise be a low-bits mask.
3101 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3102 // knew about to reconstruct a low-bits mask value.
3103 unsigned LZ = A.countLeadingZeros();
3104 unsigned BitWidth = A.getBitWidth();
3105 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3106 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3107 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3108
3109 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3110
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003111 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003112 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003113 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003114 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003115 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003116 }
3117 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003118
Dan Gohman6c459a22008-06-22 19:56:46 +00003119 case Instruction::Or:
3120 // If the RHS of the Or is a constant, we may have something like:
3121 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3122 // optimizations will transparently handle this case.
3123 //
3124 // In order for this transformation to be safe, the LHS must be of the
3125 // form X*(2^n) and the Or constant must be less than 2^n.
3126 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003127 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003128 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003129 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003130 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3131 // Build a plain add SCEV.
3132 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3133 // If the LHS of the add was an addrec and it has no-wrap flags,
3134 // transfer the no-wrap flags, since an or won't introduce a wrap.
3135 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3136 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3137 if (OldAR->hasNoUnsignedWrap())
3138 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3139 if (OldAR->hasNoSignedWrap())
3140 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3141 }
3142 return S;
3143 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003144 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003145 break;
3146 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003147 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003148 // If the RHS of the xor is a signbit, then this is just an add.
3149 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003150 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003151 return getAddExpr(getSCEV(U->getOperand(0)),
3152 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003153
3154 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003155 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003156 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003157
3158 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3159 // This is a variant of the check for xor with -1, and it handles
3160 // the case where instcombine has trimmed non-demanded bits out
3161 // of an xor with -1.
3162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3163 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3164 if (BO->getOpcode() == Instruction::And &&
3165 LCI->getValue() == CI->getValue())
3166 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003167 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003168 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003169 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003170 const Type *Z0Ty = Z0->getType();
3171 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3172
3173 // If C is a low-bits mask, the zero extend is zerving to
3174 // mask off the high bits. Complement the operand and
3175 // re-apply the zext.
3176 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3177 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3178
3179 // If C is a single bit, it may be in the sign-bit position
3180 // before the zero-extend. In this case, represent the xor
3181 // using an add, which is equivalent, and re-apply the zext.
3182 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3183 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3184 Trunc.isSignBit())
3185 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3186 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003187 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003188 }
3189 break;
3190
3191 case Instruction::Shl:
3192 // Turn shift left of a constant amount into a multiply.
3193 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3194 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003195 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003196 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003197 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003198 }
3199 break;
3200
Nick Lewycky01eaf802008-07-07 06:15:49 +00003201 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003202 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003203 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3204 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003205 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003206 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003207 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003208 }
3209 break;
3210
Dan Gohman4ee29af2009-04-21 02:26:00 +00003211 case Instruction::AShr:
3212 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3213 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3214 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3215 if (L->getOpcode() == Instruction::Shl &&
3216 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003217 unsigned BitWidth = getTypeSizeInBits(U->getType());
3218 uint64_t Amt = BitWidth - CI->getZExtValue();
3219 if (Amt == BitWidth)
3220 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3221 if (Amt > BitWidth)
3222 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003223 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003224 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003225 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003226 U->getType());
3227 }
3228 break;
3229
Dan Gohman6c459a22008-06-22 19:56:46 +00003230 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003231 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003232
3233 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003234 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003235
3236 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003237 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003238
3239 case Instruction::BitCast:
3240 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003241 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003242 return getSCEV(U->getOperand(0));
3243 break;
3244
Dan Gohmanf2411742009-07-20 17:43:30 +00003245 // It's tempting to handle inttoptr and ptrtoint, however this can
3246 // lead to pointer expressions which cannot be expanded to GEPs
3247 // (because they may overflow). For now, the only pointer-typed
3248 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00003249
Dan Gohman26466c02009-05-08 20:26:55 +00003250 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003251 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003252
Dan Gohman6c459a22008-06-22 19:56:46 +00003253 case Instruction::PHI:
3254 return createNodeForPHI(cast<PHINode>(U));
3255
3256 case Instruction::Select:
3257 // This could be a smax or umax that was lowered earlier.
3258 // Try to recover it.
3259 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3260 Value *LHS = ICI->getOperand(0);
3261 Value *RHS = ICI->getOperand(1);
3262 switch (ICI->getPredicate()) {
3263 case ICmpInst::ICMP_SLT:
3264 case ICmpInst::ICMP_SLE:
3265 std::swap(LHS, RHS);
3266 // fall through
3267 case ICmpInst::ICMP_SGT:
3268 case ICmpInst::ICMP_SGE:
3269 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003270 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003271 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003272 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003273 break;
3274 case ICmpInst::ICMP_ULT:
3275 case ICmpInst::ICMP_ULE:
3276 std::swap(LHS, RHS);
3277 // fall through
3278 case ICmpInst::ICMP_UGT:
3279 case ICmpInst::ICMP_UGE:
3280 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003281 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003282 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003283 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003284 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003285 case ICmpInst::ICMP_NE:
3286 // n != 0 ? n : 1 -> umax(n, 1)
3287 if (LHS == U->getOperand(1) &&
3288 isa<ConstantInt>(U->getOperand(2)) &&
3289 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3290 isa<ConstantInt>(RHS) &&
3291 cast<ConstantInt>(RHS)->isZero())
3292 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3293 break;
3294 case ICmpInst::ICMP_EQ:
3295 // n == 0 ? 1 : n -> umax(n, 1)
3296 if (LHS == U->getOperand(2) &&
3297 isa<ConstantInt>(U->getOperand(1)) &&
3298 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3299 isa<ConstantInt>(RHS) &&
3300 cast<ConstantInt>(RHS)->isZero())
3301 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3302 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003303 default:
3304 break;
3305 }
3306 }
3307
3308 default: // We cannot analyze this expression.
3309 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003310 }
3311
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003312 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003313}
3314
3315
3316
3317//===----------------------------------------------------------------------===//
3318// Iteration Count Computation Code
3319//
3320
Dan Gohman46bdfb02009-02-24 18:55:53 +00003321/// getBackedgeTakenCount - If the specified loop has a predictable
3322/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3323/// object. The backedge-taken count is the number of times the loop header
3324/// will be branched to from within the loop. This is one less than the
3325/// trip count of the loop, since it doesn't count the first iteration,
3326/// when the header is branched to from outside the loop.
3327///
3328/// Note that it is not valid to call this method on a loop without a
3329/// loop-invariant backedge-taken count (see
3330/// hasLoopInvariantBackedgeTakenCount).
3331///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003332const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003333 return getBackedgeTakenInfo(L).Exact;
3334}
3335
3336/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3337/// return the least SCEV value that is known never to be less than the
3338/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003339const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003340 return getBackedgeTakenInfo(L).Max;
3341}
3342
Dan Gohman59ae6b92009-07-08 19:23:34 +00003343/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3344/// onto the given Worklist.
3345static void
3346PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3347 BasicBlock *Header = L->getHeader();
3348
3349 // Push all Loop-header PHIs onto the Worklist stack.
3350 for (BasicBlock::iterator I = Header->begin();
3351 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3352 Worklist.push_back(PN);
3353}
3354
Dan Gohmana1af7572009-04-30 20:47:05 +00003355const ScalarEvolution::BackedgeTakenInfo &
3356ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003357 // Initially insert a CouldNotCompute for this loop. If the insertion
3358 // succeeds, procede to actually compute a backedge-taken count and
3359 // update the value. The temporary CouldNotCompute value tells SCEV
3360 // code elsewhere that it shouldn't attempt to request a new
3361 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003362 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003363 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3364 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003365 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3366 if (BECount.Exact != getCouldNotCompute()) {
3367 assert(BECount.Exact->isLoopInvariant(L) &&
3368 BECount.Max->isLoopInvariant(L) &&
3369 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003370 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003371
Dan Gohman01ecca22009-04-27 20:16:15 +00003372 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003373 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003374 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003375 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003376 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003377 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003378 if (isa<PHINode>(L->getHeader()->begin()))
3379 // Only count loops that have phi nodes as not being computable.
3380 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003381 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003382
3383 // Now that we know more about the trip count for this loop, forget any
3384 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003385 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003386 // information. This is similar to the code in forgetLoop, except that
3387 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003388 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003389 SmallVector<Instruction *, 16> Worklist;
3390 PushLoopPHIs(L, Worklist);
3391
3392 SmallPtrSet<Instruction *, 8> Visited;
3393 while (!Worklist.empty()) {
3394 Instruction *I = Worklist.pop_back_val();
3395 if (!Visited.insert(I)) continue;
3396
Dan Gohman5d984912009-12-18 01:14:11 +00003397 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003398 Scalars.find(static_cast<Value *>(I));
3399 if (It != Scalars.end()) {
3400 // SCEVUnknown for a PHI either means that it has an unrecognized
3401 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003402 // by createNodeForPHI. In the former case, additional loop trip
3403 // count information isn't going to change anything. In the later
3404 // case, createNodeForPHI will perform the necessary updates on its
3405 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003406 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3407 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003408 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003409 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003410 if (PHINode *PN = dyn_cast<PHINode>(I))
3411 ConstantEvolutionLoopExitValue.erase(PN);
3412 }
3413
3414 PushDefUseChildren(I, Worklist);
3415 }
3416 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003417 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003418 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003419}
3420
Dan Gohman4c7279a2009-10-31 15:04:55 +00003421/// forgetLoop - This method should be called by the client when it has
3422/// changed a loop in a way that may effect ScalarEvolution's ability to
3423/// compute a trip count, or if the loop is deleted.
3424void ScalarEvolution::forgetLoop(const Loop *L) {
3425 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003426 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003427
Dan Gohman4c7279a2009-10-31 15:04:55 +00003428 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003429 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003430 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003431
Dan Gohman59ae6b92009-07-08 19:23:34 +00003432 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003433 while (!Worklist.empty()) {
3434 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003435 if (!Visited.insert(I)) continue;
3436
Dan Gohman5d984912009-12-18 01:14:11 +00003437 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003438 Scalars.find(static_cast<Value *>(I));
3439 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003440 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003441 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003442 if (PHINode *PN = dyn_cast<PHINode>(I))
3443 ConstantEvolutionLoopExitValue.erase(PN);
3444 }
3445
3446 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003447 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003448}
3449
Dan Gohman46bdfb02009-02-24 18:55:53 +00003450/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3451/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003452ScalarEvolution::BackedgeTakenInfo
3453ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003454 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003455 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003456
Dan Gohmana334aa72009-06-22 00:31:57 +00003457 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003458 const SCEV *BECount = getCouldNotCompute();
3459 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003460 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003461 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3462 BackedgeTakenInfo NewBTI =
3463 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003464
Dan Gohman1c343752009-06-27 21:21:31 +00003465 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003466 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003467 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003468 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003469 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003470 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003471 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003472 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003473 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003474 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003475 }
Dan Gohman1c343752009-06-27 21:21:31 +00003476 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003477 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003478 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003479 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003480 }
3481
3482 return BackedgeTakenInfo(BECount, MaxBECount);
3483}
3484
3485/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3486/// of the specified loop will execute if it exits via the specified block.
3487ScalarEvolution::BackedgeTakenInfo
3488ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3489 BasicBlock *ExitingBlock) {
3490
3491 // Okay, we've chosen an exiting block. See what condition causes us to
3492 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003493 //
3494 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003495 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003496 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003497 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003498
Chris Lattner8b0e3602007-01-07 02:24:26 +00003499 // At this point, we know we have a conditional branch that determines whether
3500 // the loop is exited. However, we don't know if the branch is executed each
3501 // time through the loop. If not, then the execution count of the branch will
3502 // not be equal to the trip count of the loop.
3503 //
3504 // Currently we check for this by checking to see if the Exit branch goes to
3505 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003506 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003507 // loop header. This is common for un-rotated loops.
3508 //
3509 // If both of those tests fail, walk up the unique predecessor chain to the
3510 // header, stopping if there is an edge that doesn't exit the loop. If the
3511 // header is reached, the execution count of the branch will be equal to the
3512 // trip count of the loop.
3513 //
3514 // More extensive analysis could be done to handle more cases here.
3515 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003516 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003517 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003518 ExitBr->getParent() != L->getHeader()) {
3519 // The simple checks failed, try climbing the unique predecessor chain
3520 // up to the header.
3521 bool Ok = false;
3522 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3523 BasicBlock *Pred = BB->getUniquePredecessor();
3524 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003525 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003526 TerminatorInst *PredTerm = Pred->getTerminator();
3527 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3528 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3529 if (PredSucc == BB)
3530 continue;
3531 // If the predecessor has a successor that isn't BB and isn't
3532 // outside the loop, assume the worst.
3533 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003534 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003535 }
3536 if (Pred == L->getHeader()) {
3537 Ok = true;
3538 break;
3539 }
3540 BB = Pred;
3541 }
3542 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003543 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003544 }
3545
3546 // Procede to the next level to examine the exit condition expression.
3547 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3548 ExitBr->getSuccessor(0),
3549 ExitBr->getSuccessor(1));
3550}
3551
3552/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3553/// backedge of the specified loop will execute if its exit condition
3554/// were a conditional branch of ExitCond, TBB, and FBB.
3555ScalarEvolution::BackedgeTakenInfo
3556ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3557 Value *ExitCond,
3558 BasicBlock *TBB,
3559 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003560 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003561 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3562 if (BO->getOpcode() == Instruction::And) {
3563 // Recurse on the operands of the and.
3564 BackedgeTakenInfo BTI0 =
3565 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3566 BackedgeTakenInfo BTI1 =
3567 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
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 if (L->contains(TBB)) {
3571 // Both conditions must be true for the loop to continue executing.
3572 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003573 if (BTI0.Exact == getCouldNotCompute() ||
3574 BTI1.Exact == getCouldNotCompute())
3575 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003576 else
3577 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003578 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003579 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003580 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003581 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003582 else
3583 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003584 } else {
3585 // Both conditions must be true for the loop to exit.
3586 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003587 if (BTI0.Exact != getCouldNotCompute() &&
3588 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003589 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003590 if (BTI0.Max != getCouldNotCompute() &&
3591 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003592 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3593 }
3594
3595 return BackedgeTakenInfo(BECount, MaxBECount);
3596 }
3597 if (BO->getOpcode() == Instruction::Or) {
3598 // Recurse on the operands of the or.
3599 BackedgeTakenInfo BTI0 =
3600 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3601 BackedgeTakenInfo BTI1 =
3602 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003603 const SCEV *BECount = getCouldNotCompute();
3604 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003605 if (L->contains(FBB)) {
3606 // Both conditions must be false for the loop to continue executing.
3607 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003608 if (BTI0.Exact == getCouldNotCompute() ||
3609 BTI1.Exact == getCouldNotCompute())
3610 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003611 else
3612 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003613 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003614 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003615 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003616 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003617 else
3618 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003619 } else {
3620 // Both conditions must be false for the loop to exit.
3621 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003622 if (BTI0.Exact != getCouldNotCompute() &&
3623 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003624 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003625 if (BTI0.Max != getCouldNotCompute() &&
3626 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003627 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3628 }
3629
3630 return BackedgeTakenInfo(BECount, MaxBECount);
3631 }
3632 }
3633
3634 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3635 // Procede to the next level to examine the icmp.
3636 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3637 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638
Eli Friedman361e54d2009-05-09 12:32:42 +00003639 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003640 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3641}
3642
3643/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3644/// backedge of the specified loop will execute if its exit condition
3645/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3646ScalarEvolution::BackedgeTakenInfo
3647ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3648 ICmpInst *ExitCond,
3649 BasicBlock *TBB,
3650 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003651
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 // If the condition was exit on true, convert the condition to exit on false
3653 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003654 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003656 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003658
3659 // Handle common loops like: for (X = "string"; *X; ++X)
3660 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3661 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003662 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003663 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003664 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3665 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3666 return BackedgeTakenInfo(ItCnt,
3667 isa<SCEVConstant>(ItCnt) ? ItCnt :
3668 getConstant(APInt::getMaxValue(BitWidth)-1));
3669 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003670 }
3671
Dan Gohman0bba49c2009-07-07 17:06:11 +00003672 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3673 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003674
3675 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003676 LHS = getSCEVAtScope(LHS, L);
3677 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003678
Dan Gohman64a845e2009-06-24 04:48:43 +00003679 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003681 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3682 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003683 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003685 }
3686
Chris Lattner53e677a2004-04-02 20:23:17 +00003687 // If we have a comparison of a chrec against a constant, try to use value
3688 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003689 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3690 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003691 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003692 // Form the constant range.
3693 ConstantRange CompRange(
3694 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003695
Dan Gohman0bba49c2009-07-07 17:06:11 +00003696 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003697 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003698 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003699
Chris Lattner53e677a2004-04-02 20:23:17 +00003700 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003702 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003703 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003705 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003707 case ICmpInst::ICMP_EQ: { // while (X == Y)
3708 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003709 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003711 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712 }
3713 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003714 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3715 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003716 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 }
3718 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003719 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3720 getNotSCEV(RHS), L, true);
3721 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003722 break;
3723 }
3724 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003725 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3726 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003727 break;
3728 }
3729 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003730 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3731 getNotSCEV(RHS), L, false);
3732 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003733 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003734 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003735 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003736#if 0
David Greene25e0e872009-12-23 22:18:14 +00003737 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003738 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003739 dbgs() << "[unsigned] ";
3740 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003741 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003742 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003743#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003744 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003745 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003746 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003747 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003748}
3749
Chris Lattner673e02b2004-10-12 01:49:27 +00003750static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003751EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3752 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003753 const SCEV *InVal = SE.getConstant(C);
3754 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003755 assert(isa<SCEVConstant>(Val) &&
3756 "Evaluation of SCEV at constant didn't fold correctly?");
3757 return cast<SCEVConstant>(Val)->getValue();
3758}
3759
3760/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3761/// and a GEP expression (missing the pointer index) indexing into it, return
3762/// the addressed element of the initializer or null if the index expression is
3763/// invalid.
3764static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003765GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003766 const std::vector<ConstantInt*> &Indices) {
3767 Constant *Init = GV->getInitializer();
3768 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003769 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003770 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3771 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3772 Init = cast<Constant>(CS->getOperand(Idx));
3773 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3774 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3775 Init = cast<Constant>(CA->getOperand(Idx));
3776 } else if (isa<ConstantAggregateZero>(Init)) {
3777 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3778 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003779 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003780 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3781 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003782 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003783 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003784 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003785 }
3786 return 0;
3787 } else {
3788 return 0; // Unknown initializer type
3789 }
3790 }
3791 return Init;
3792}
3793
Dan Gohman46bdfb02009-02-24 18:55:53 +00003794/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3795/// 'icmp op load X, cst', try to see if we can compute the backedge
3796/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003797const SCEV *
3798ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3799 LoadInst *LI,
3800 Constant *RHS,
3801 const Loop *L,
3802 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003803 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003804
3805 // Check to see if the loaded pointer is a getelementptr of a global.
3806 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003807 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003808
3809 // Make sure that it is really a constant global we are gepping, with an
3810 // initializer, and make sure the first IDX is really 0.
3811 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003812 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003813 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3814 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003815 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003816
3817 // Okay, we allow one non-constant index into the GEP instruction.
3818 Value *VarIdx = 0;
3819 std::vector<ConstantInt*> Indexes;
3820 unsigned VarIdxNum = 0;
3821 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3822 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3823 Indexes.push_back(CI);
3824 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003825 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003826 VarIdx = GEP->getOperand(i);
3827 VarIdxNum = i-2;
3828 Indexes.push_back(0);
3829 }
3830
3831 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3832 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003833 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003834 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003835
3836 // We can only recognize very limited forms of loop index expressions, in
3837 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003838 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003839 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3840 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3841 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003842 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003843
3844 unsigned MaxSteps = MaxBruteForceIterations;
3845 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003846 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003847 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003848 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003849
3850 // Form the GEP offset.
3851 Indexes[VarIdxNum] = Val;
3852
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003853 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003854 if (Result == 0) break; // Cannot compute!
3855
3856 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003857 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003858 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003859 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003860#if 0
David Greene25e0e872009-12-23 22:18:14 +00003861 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003862 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3863 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003864#endif
3865 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003866 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003867 }
3868 }
Dan Gohman1c343752009-06-27 21:21:31 +00003869 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003870}
3871
3872
Chris Lattner3221ad02004-04-17 22:58:41 +00003873/// CanConstantFold - Return true if we can constant fold an instruction of the
3874/// specified type, assuming that all operands were constants.
3875static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003876 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003877 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3878 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003879
Chris Lattner3221ad02004-04-17 22:58:41 +00003880 if (const CallInst *CI = dyn_cast<CallInst>(I))
3881 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003882 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003883 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003884}
3885
Chris Lattner3221ad02004-04-17 22:58:41 +00003886/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3887/// in the loop that V is derived from. We allow arbitrary operations along the
3888/// way, but the operands of an operation must either be constants or a value
3889/// derived from a constant PHI. If this expression does not fit with these
3890/// constraints, return null.
3891static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3892 // If this is not an instruction, or if this is an instruction outside of the
3893 // loop, it can't be derived from a loop PHI.
3894 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003895 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003896
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003897 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003898 if (L->getHeader() == I->getParent())
3899 return PN;
3900 else
3901 // We don't currently keep track of the control flow needed to evaluate
3902 // PHIs, so we cannot handle PHIs inside of loops.
3903 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003904 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003905
3906 // If we won't be able to constant fold this expression even if the operands
3907 // are constants, return early.
3908 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003909
Chris Lattner3221ad02004-04-17 22:58:41 +00003910 // Otherwise, we can evaluate this instruction if all of its operands are
3911 // constant or derived from a PHI node themselves.
3912 PHINode *PHI = 0;
3913 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3914 if (!(isa<Constant>(I->getOperand(Op)) ||
3915 isa<GlobalValue>(I->getOperand(Op)))) {
3916 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3917 if (P == 0) return 0; // Not evolving from PHI
3918 if (PHI == 0)
3919 PHI = P;
3920 else if (PHI != P)
3921 return 0; // Evolving from multiple different PHIs.
3922 }
3923
3924 // This is a expression evolving from a constant PHI!
3925 return PHI;
3926}
3927
3928/// EvaluateExpression - Given an expression that passes the
3929/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3930/// in the loop has the value PHIVal. If we can't fold this expression for some
3931/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003932static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
3933 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003934 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003935 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003936 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003937 Instruction *I = cast<Instruction>(V);
3938
3939 std::vector<Constant*> Operands;
3940 Operands.resize(I->getNumOperands());
3941
3942 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003943 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003944 if (Operands[i] == 0) return 0;
3945 }
3946
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003947 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00003948 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003949 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00003950 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003951 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003952}
3953
3954/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3955/// in the header of its containing loop, we know the loop executes a
3956/// constant number of times, and the PHI node is just a recurrence
3957/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003958Constant *
3959ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00003960 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00003961 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003962 std::map<PHINode*, Constant*>::iterator I =
3963 ConstantEvolutionLoopExitValue.find(PN);
3964 if (I != ConstantEvolutionLoopExitValue.end())
3965 return I->second;
3966
Dan Gohman46bdfb02009-02-24 18:55:53 +00003967 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003968 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3969
3970 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3971
3972 // Since the loop is canonicalized, the PHI node must have two entries. One
3973 // entry must be a constant (coming in from outside of the loop), and the
3974 // second must be derived from the same PHI.
3975 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3976 Constant *StartCST =
3977 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3978 if (StartCST == 0)
3979 return RetVal = 0; // Must be a constant.
3980
3981 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3982 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3983 if (PN2 != PN)
3984 return RetVal = 0; // Not derived from same PHI.
3985
3986 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003987 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003988 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003989
Dan Gohman46bdfb02009-02-24 18:55:53 +00003990 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003991 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003992 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3993 if (IterationNum == NumIterations)
3994 return RetVal = PHIVal; // Got exit value!
3995
3996 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003997 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003998 if (NextPHI == PHIVal)
3999 return RetVal = NextPHI; // Stopped evolving!
4000 if (NextPHI == 0)
4001 return 0; // Couldn't evaluate!
4002 PHIVal = NextPHI;
4003 }
4004}
4005
Dan Gohman07ad19b2009-07-27 16:09:48 +00004006/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004007/// constant number of times (the condition evolves only from constants),
4008/// try to evaluate a few iterations of the loop until we get the exit
4009/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004010/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004011const SCEV *
4012ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4013 Value *Cond,
4014 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004015 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004016 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004017
4018 // Since the loop is canonicalized, the PHI node must have two entries. One
4019 // entry must be a constant (coming in from outside of the loop), and the
4020 // second must be derived from the same PHI.
4021 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4022 Constant *StartCST =
4023 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004024 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004025
4026 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4027 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004028 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004029
4030 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4031 // the loop symbolically to determine when the condition gets a value of
4032 // "ExitWhen".
4033 unsigned IterationNum = 0;
4034 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4035 for (Constant *PHIVal = StartCST;
4036 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004037 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004038 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004039
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004040 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004041 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004042
Reid Spencere8019bb2007-03-01 07:25:48 +00004043 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004044 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004045 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004046 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004047
Chris Lattner3221ad02004-04-17 22:58:41 +00004048 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004049 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004050 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004051 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004052 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004053 }
4054
4055 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004056 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004057}
4058
Dan Gohmane7125f42009-09-03 15:00:26 +00004059/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004060/// at the specified scope in the program. The L value specifies a loop
4061/// nest to evaluate the expression at, where null is the top-level or a
4062/// specified loop is immediately inside of the loop.
4063///
4064/// This method can be used to compute the exit value for a variable defined
4065/// in a loop by querying what the value will hold in the parent loop.
4066///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004067/// In the case that a relevant loop exit value cannot be computed, the
4068/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004069const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004070 // Check to see if we've folded this expression at this loop before.
4071 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4072 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4073 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4074 if (!Pair.second)
4075 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004076
Dan Gohman42214892009-08-31 21:15:23 +00004077 // Otherwise compute it.
4078 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004079 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004080 return C;
4081}
4082
4083const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004084 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004085
Nick Lewycky3e630762008-02-20 06:48:22 +00004086 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004087 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004088 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004089 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004090 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004091 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4092 if (PHINode *PN = dyn_cast<PHINode>(I))
4093 if (PN->getParent() == LI->getHeader()) {
4094 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004095 // to see if the loop that contains it has a known backedge-taken
4096 // count. If so, we may be able to force computation of the exit
4097 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004098 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004099 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004100 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004101 // Okay, we know how many times the containing loop executes. If
4102 // this is a constant evolving PHI node, get the final value at
4103 // the specified iteration number.
4104 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004105 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004106 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004107 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004108 }
4109 }
4110
Reid Spencer09906f32006-12-04 21:33:23 +00004111 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004112 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004113 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004114 // result. This is particularly useful for computing loop exit values.
4115 if (CanConstantFold(I)) {
4116 std::vector<Constant*> Operands;
4117 Operands.reserve(I->getNumOperands());
4118 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4119 Value *Op = I->getOperand(i);
4120 if (Constant *C = dyn_cast<Constant>(Op)) {
4121 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004122 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004123 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004124 // non-integer and non-pointer, don't even try to analyze them
4125 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004126 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004127 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004128
Dan Gohman5d984912009-12-18 01:14:11 +00004129 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004131 Constant *C = SC->getValue();
4132 if (C->getType() != Op->getType())
4133 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4134 Op->getType(),
4135 false),
4136 C, Op->getType());
4137 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004138 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004139 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4140 if (C->getType() != Op->getType())
4141 C =
4142 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4143 Op->getType(),
4144 false),
4145 C, Op->getType());
4146 Operands.push_back(C);
4147 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004148 return V;
4149 } else {
4150 return V;
4151 }
4152 }
4153 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004154
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004155 Constant *C;
4156 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4157 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004158 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004159 else
4160 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004161 &Operands[0], Operands.size(), TD);
Dan Gohman09987962009-06-29 21:31:18 +00004162 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004163 }
4164 }
4165
4166 // This is some other type of SCEVUnknown, just return it.
4167 return V;
4168 }
4169
Dan Gohman622ed672009-05-04 22:02:23 +00004170 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004171 // Avoid performing the look-up in the common case where the specified
4172 // expression has no loop-variant portions.
4173 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004174 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004175 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004176 // Okay, at least one of these operands is loop variant but might be
4177 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004178 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4179 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004180 NewOps.push_back(OpAtScope);
4181
4182 for (++i; i != e; ++i) {
4183 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004184 NewOps.push_back(OpAtScope);
4185 }
4186 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004187 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004188 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004189 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004190 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004191 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004192 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004193 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004194 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004195 }
4196 }
4197 // If we got here, all operands are loop invariant.
4198 return Comm;
4199 }
4200
Dan Gohman622ed672009-05-04 22:02:23 +00004201 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004202 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4203 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004204 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4205 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004206 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004207 }
4208
4209 // If this is a loop recurrence for a loop that does not contain L, then we
4210 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004211 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004212 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004213 // To evaluate this recurrence, we need to know how many times the AddRec
4214 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004215 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004216 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004217
Eli Friedmanb42a6262008-08-04 23:49:06 +00004218 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004219 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004220 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004221 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004222 }
4223
Dan Gohman622ed672009-05-04 22:02:23 +00004224 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004225 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004226 if (Op == Cast->getOperand())
4227 return Cast; // must be loop invariant
4228 return getZeroExtendExpr(Op, Cast->getType());
4229 }
4230
Dan Gohman622ed672009-05-04 22:02:23 +00004231 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004232 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004233 if (Op == Cast->getOperand())
4234 return Cast; // must be loop invariant
4235 return getSignExtendExpr(Op, Cast->getType());
4236 }
4237
Dan Gohman622ed672009-05-04 22:02:23 +00004238 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004239 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004240 if (Op == Cast->getOperand())
4241 return Cast; // must be loop invariant
4242 return getTruncateExpr(Op, Cast->getType());
4243 }
4244
Dan Gohmanc40f17b2009-08-18 16:46:41 +00004245 if (isa<SCEVTargetDataConstant>(V))
4246 return V;
4247
Torok Edwinc23197a2009-07-14 16:55:14 +00004248 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004249 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004250}
4251
Dan Gohman66a7e852009-05-08 20:38:54 +00004252/// getSCEVAtScope - This is a convenience function which does
4253/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004254const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004255 return getSCEVAtScope(getSCEV(V), L);
4256}
4257
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004258/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4259/// following equation:
4260///
4261/// A * X = B (mod N)
4262///
4263/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4264/// A and B isn't important.
4265///
4266/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004267static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004268 ScalarEvolution &SE) {
4269 uint32_t BW = A.getBitWidth();
4270 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4271 assert(A != 0 && "A must be non-zero.");
4272
4273 // 1. D = gcd(A, N)
4274 //
4275 // The gcd of A and N may have only one prime factor: 2. The number of
4276 // trailing zeros in A is its multiplicity
4277 uint32_t Mult2 = A.countTrailingZeros();
4278 // D = 2^Mult2
4279
4280 // 2. Check if B is divisible by D.
4281 //
4282 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4283 // is not less than multiplicity of this prime factor for D.
4284 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004285 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004286
4287 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4288 // modulo (N / D).
4289 //
4290 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4291 // bit width during computations.
4292 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4293 APInt Mod(BW + 1, 0);
4294 Mod.set(BW - Mult2); // Mod = N / D
4295 APInt I = AD.multiplicativeInverse(Mod);
4296
4297 // 4. Compute the minimum unsigned root of the equation:
4298 // I * (B / D) mod (N / D)
4299 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4300
4301 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4302 // bits.
4303 return SE.getConstant(Result.trunc(BW));
4304}
Chris Lattner53e677a2004-04-02 20:23:17 +00004305
4306/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4307/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4308/// might be the same) or two SCEVCouldNotCompute objects.
4309///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004310static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004311SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004312 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004313 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4314 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4315 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004316
Chris Lattner53e677a2004-04-02 20:23:17 +00004317 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004318 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004319 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004320 return std::make_pair(CNC, CNC);
4321 }
4322
Reid Spencere8019bb2007-03-01 07:25:48 +00004323 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004324 const APInt &L = LC->getValue()->getValue();
4325 const APInt &M = MC->getValue()->getValue();
4326 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004327 APInt Two(BitWidth, 2);
4328 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004329
Dan Gohman64a845e2009-06-24 04:48:43 +00004330 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004331 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004332 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004333 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4334 // The B coefficient is M-N/2
4335 APInt B(M);
4336 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004337
Reid Spencere8019bb2007-03-01 07:25:48 +00004338 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004339 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004340
Reid Spencere8019bb2007-03-01 07:25:48 +00004341 // Compute the B^2-4ac term.
4342 APInt SqrtTerm(B);
4343 SqrtTerm *= B;
4344 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004345
Reid Spencere8019bb2007-03-01 07:25:48 +00004346 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4347 // integer value or else APInt::sqrt() will assert.
4348 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004349
Dan Gohman64a845e2009-06-24 04:48:43 +00004350 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004351 // The divisions must be performed as signed divisions.
4352 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004353 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004354 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004355 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004356 return std::make_pair(CNC, CNC);
4357 }
4358
Owen Andersone922c022009-07-22 00:24:57 +00004359 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004360
4361 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004362 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004363 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004364 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004365
Dan Gohman64a845e2009-06-24 04:48:43 +00004366 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004367 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004368 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004369}
4370
4371/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004372/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004373const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004374 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004375 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004376 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004377 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004378 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004379 }
4380
Dan Gohman35738ac2009-05-04 22:30:44 +00004381 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004382 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004383 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004384
4385 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004386 // If this is an affine expression, the execution count of this branch is
4387 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004388 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004389 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004390 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004391 // equivalent to:
4392 //
4393 // Step*N = -Start (mod 2^BW)
4394 //
4395 // where BW is the common bit width of Start and Step.
4396
Chris Lattner53e677a2004-04-02 20:23:17 +00004397 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004398 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4399 L->getParentLoop());
4400 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4401 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004402
Dan Gohman622ed672009-05-04 22:02:23 +00004403 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004404 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004405
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004406 // First, handle unitary steps.
4407 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004408 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004409 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4410 return Start; // N = Start (as unsigned)
4411
4412 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004413 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004414 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004415 -StartC->getValue()->getValue(),
4416 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004417 }
Chris Lattner42a75512007-01-15 02:27:26 +00004418 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004419 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4420 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004421 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004422 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004423 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4424 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004425 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004426#if 0
David Greene25e0e872009-12-23 22:18:14 +00004427 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004428 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004429#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004430 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004431 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004432 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004433 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004434 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004435 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004436
Chris Lattner53e677a2004-04-02 20:23:17 +00004437 // We can only use this value if the chrec ends up with an exact zero
4438 // value at this index. When solving for "X*X != 5", for example, we
4439 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004440 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004441 if (Val->isZero())
4442 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004443 }
4444 }
4445 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004446
Dan Gohman1c343752009-06-27 21:21:31 +00004447 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004448}
4449
4450/// HowFarToNonZero - Return the number of times a backedge checking the
4451/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004452/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004453const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004454 // Loops that look like: while (X == 0) are very strange indeed. We don't
4455 // handle them yet except for the trivial case. This could be expanded in the
4456 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004457
Chris Lattner53e677a2004-04-02 20:23:17 +00004458 // If the value is a constant, check to see if it is known to be non-zero
4459 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004460 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004461 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004462 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004463 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004464 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004465
Chris Lattner53e677a2004-04-02 20:23:17 +00004466 // We could implement others, but I really doubt anyone writes loops like
4467 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004468 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004469}
4470
Dan Gohman859b4822009-05-18 15:36:09 +00004471/// getLoopPredecessor - If the given loop's header has exactly one unique
4472/// predecessor outside the loop, return it. Otherwise return null.
4473///
4474BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4475 BasicBlock *Header = L->getHeader();
4476 BasicBlock *Pred = 0;
4477 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4478 PI != E; ++PI)
4479 if (!L->contains(*PI)) {
4480 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4481 Pred = *PI;
4482 }
4483 return Pred;
4484}
4485
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004486/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4487/// (which may not be an immediate predecessor) which has exactly one
4488/// successor from which BB is reachable, or null if no such block is
4489/// found.
4490///
4491BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004492ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004493 // If the block has a unique predecessor, then there is no path from the
4494 // predecessor to the block that does not go through the direct edge
4495 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004496 if (BasicBlock *Pred = BB->getSinglePredecessor())
4497 return Pred;
4498
4499 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004500 // If the header has a unique predecessor outside the loop, it must be
4501 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004502 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004503 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004504
4505 return 0;
4506}
4507
Dan Gohman763bad12009-06-20 00:35:32 +00004508/// HasSameValue - SCEV structural equivalence is usually sufficient for
4509/// testing whether two expressions are equal, however for the purposes of
4510/// looking for a condition guarding a loop, it can be useful to be a little
4511/// more general, since a front-end may have replicated the controlling
4512/// expression.
4513///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004514static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004515 // Quick check to see if they are the same SCEV.
4516 if (A == B) return true;
4517
4518 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4519 // two different instructions with the same value. Check for this case.
4520 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4521 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4522 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4523 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004524 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004525 return true;
4526
4527 // Otherwise assume they may have a different value.
4528 return false;
4529}
4530
Dan Gohman85b05a22009-07-13 21:35:55 +00004531bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4532 return getSignedRange(S).getSignedMax().isNegative();
4533}
4534
4535bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4536 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4537}
4538
4539bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4540 return !getSignedRange(S).getSignedMin().isNegative();
4541}
4542
4543bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4544 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4545}
4546
4547bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4548 return isKnownNegative(S) || isKnownPositive(S);
4549}
4550
4551bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4552 const SCEV *LHS, const SCEV *RHS) {
4553
4554 if (HasSameValue(LHS, RHS))
4555 return ICmpInst::isTrueWhenEqual(Pred);
4556
4557 switch (Pred) {
4558 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004559 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004560 break;
4561 case ICmpInst::ICMP_SGT:
4562 Pred = ICmpInst::ICMP_SLT;
4563 std::swap(LHS, RHS);
4564 case ICmpInst::ICMP_SLT: {
4565 ConstantRange LHSRange = getSignedRange(LHS);
4566 ConstantRange RHSRange = getSignedRange(RHS);
4567 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4568 return true;
4569 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4570 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004571 break;
4572 }
4573 case ICmpInst::ICMP_SGE:
4574 Pred = ICmpInst::ICMP_SLE;
4575 std::swap(LHS, RHS);
4576 case ICmpInst::ICMP_SLE: {
4577 ConstantRange LHSRange = getSignedRange(LHS);
4578 ConstantRange RHSRange = getSignedRange(RHS);
4579 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4580 return true;
4581 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4582 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004583 break;
4584 }
4585 case ICmpInst::ICMP_UGT:
4586 Pred = ICmpInst::ICMP_ULT;
4587 std::swap(LHS, RHS);
4588 case ICmpInst::ICMP_ULT: {
4589 ConstantRange LHSRange = getUnsignedRange(LHS);
4590 ConstantRange RHSRange = getUnsignedRange(RHS);
4591 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4592 return true;
4593 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4594 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004595 break;
4596 }
4597 case ICmpInst::ICMP_UGE:
4598 Pred = ICmpInst::ICMP_ULE;
4599 std::swap(LHS, RHS);
4600 case ICmpInst::ICMP_ULE: {
4601 ConstantRange LHSRange = getUnsignedRange(LHS);
4602 ConstantRange RHSRange = getUnsignedRange(RHS);
4603 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4604 return true;
4605 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4606 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004607 break;
4608 }
4609 case ICmpInst::ICMP_NE: {
4610 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4611 return true;
4612 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4613 return true;
4614
4615 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4616 if (isKnownNonZero(Diff))
4617 return true;
4618 break;
4619 }
4620 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004621 // The check at the top of the function catches the case where
4622 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004623 break;
4624 }
4625 return false;
4626}
4627
4628/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4629/// protected by a conditional between LHS and RHS. This is used to
4630/// to eliminate casts.
4631bool
4632ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4633 ICmpInst::Predicate Pred,
4634 const SCEV *LHS, const SCEV *RHS) {
4635 // Interpret a null as meaning no loop, where there is obviously no guard
4636 // (interprocedural conditions notwithstanding).
4637 if (!L) return true;
4638
4639 BasicBlock *Latch = L->getLoopLatch();
4640 if (!Latch)
4641 return false;
4642
4643 BranchInst *LoopContinuePredicate =
4644 dyn_cast<BranchInst>(Latch->getTerminator());
4645 if (!LoopContinuePredicate ||
4646 LoopContinuePredicate->isUnconditional())
4647 return false;
4648
Dan Gohman0f4b2852009-07-21 23:03:19 +00004649 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4650 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004651}
4652
4653/// isLoopGuardedByCond - Test whether entry to the loop is protected
4654/// by a conditional between LHS and RHS. This is used to help avoid max
4655/// expressions in loop trip counts, and to eliminate casts.
4656bool
4657ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4658 ICmpInst::Predicate Pred,
4659 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004660 // Interpret a null as meaning no loop, where there is obviously no guard
4661 // (interprocedural conditions notwithstanding).
4662 if (!L) return false;
4663
Dan Gohman859b4822009-05-18 15:36:09 +00004664 BasicBlock *Predecessor = getLoopPredecessor(L);
4665 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004666
Dan Gohman859b4822009-05-18 15:36:09 +00004667 // Starting at the loop predecessor, climb up the predecessor chain, as long
4668 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004669 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004670 for (; Predecessor;
4671 PredecessorDest = Predecessor,
4672 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004673
4674 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004675 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004676 if (!LoopEntryPredicate ||
4677 LoopEntryPredicate->isUnconditional())
4678 continue;
4679
Dan Gohman0f4b2852009-07-21 23:03:19 +00004680 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4681 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004682 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004683 }
4684
Dan Gohman38372182008-08-12 20:17:31 +00004685 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004686}
4687
Dan Gohman0f4b2852009-07-21 23:03:19 +00004688/// isImpliedCond - Test whether the condition described by Pred, LHS,
4689/// and RHS is true whenever the given Cond value evaluates to true.
4690bool ScalarEvolution::isImpliedCond(Value *CondValue,
4691 ICmpInst::Predicate Pred,
4692 const SCEV *LHS, const SCEV *RHS,
4693 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004694 // Recursivly handle And and Or conditions.
4695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4696 if (BO->getOpcode() == Instruction::And) {
4697 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004698 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4699 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004700 } else if (BO->getOpcode() == Instruction::Or) {
4701 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004702 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4703 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004704 }
4705 }
4706
4707 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4708 if (!ICI) return false;
4709
Dan Gohman85b05a22009-07-13 21:35:55 +00004710 // Bail if the ICmp's operands' types are wider than the needed type
4711 // before attempting to call getSCEV on them. This avoids infinite
4712 // recursion, since the analysis of widening casts can require loop
4713 // exit condition information for overflow checking, which would
4714 // lead back here.
4715 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004716 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004717 return false;
4718
Dan Gohman0f4b2852009-07-21 23:03:19 +00004719 // Now that we found a conditional branch that dominates the loop, check to
4720 // see if it is the comparison we are looking for.
4721 ICmpInst::Predicate FoundPred;
4722 if (Inverse)
4723 FoundPred = ICI->getInversePredicate();
4724 else
4725 FoundPred = ICI->getPredicate();
4726
4727 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4728 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004729
4730 // Balance the types. The case where FoundLHS' type is wider than
4731 // LHS' type is checked for above.
4732 if (getTypeSizeInBits(LHS->getType()) >
4733 getTypeSizeInBits(FoundLHS->getType())) {
4734 if (CmpInst::isSigned(Pred)) {
4735 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4736 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4737 } else {
4738 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4739 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4740 }
4741 }
4742
Dan Gohman0f4b2852009-07-21 23:03:19 +00004743 // Canonicalize the query to match the way instcombine will have
4744 // canonicalized the comparison.
4745 // First, put a constant operand on the right.
4746 if (isa<SCEVConstant>(LHS)) {
4747 std::swap(LHS, RHS);
4748 Pred = ICmpInst::getSwappedPredicate(Pred);
4749 }
4750 // Then, canonicalize comparisons with boundary cases.
4751 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4752 const APInt &RA = RC->getValue()->getValue();
4753 switch (Pred) {
4754 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4755 case ICmpInst::ICMP_EQ:
4756 case ICmpInst::ICMP_NE:
4757 break;
4758 case ICmpInst::ICMP_UGE:
4759 if ((RA - 1).isMinValue()) {
4760 Pred = ICmpInst::ICMP_NE;
4761 RHS = getConstant(RA - 1);
4762 break;
4763 }
4764 if (RA.isMaxValue()) {
4765 Pred = ICmpInst::ICMP_EQ;
4766 break;
4767 }
4768 if (RA.isMinValue()) return true;
4769 break;
4770 case ICmpInst::ICMP_ULE:
4771 if ((RA + 1).isMaxValue()) {
4772 Pred = ICmpInst::ICMP_NE;
4773 RHS = getConstant(RA + 1);
4774 break;
4775 }
4776 if (RA.isMinValue()) {
4777 Pred = ICmpInst::ICMP_EQ;
4778 break;
4779 }
4780 if (RA.isMaxValue()) return true;
4781 break;
4782 case ICmpInst::ICMP_SGE:
4783 if ((RA - 1).isMinSignedValue()) {
4784 Pred = ICmpInst::ICMP_NE;
4785 RHS = getConstant(RA - 1);
4786 break;
4787 }
4788 if (RA.isMaxSignedValue()) {
4789 Pred = ICmpInst::ICMP_EQ;
4790 break;
4791 }
4792 if (RA.isMinSignedValue()) return true;
4793 break;
4794 case ICmpInst::ICMP_SLE:
4795 if ((RA + 1).isMaxSignedValue()) {
4796 Pred = ICmpInst::ICMP_NE;
4797 RHS = getConstant(RA + 1);
4798 break;
4799 }
4800 if (RA.isMinSignedValue()) {
4801 Pred = ICmpInst::ICMP_EQ;
4802 break;
4803 }
4804 if (RA.isMaxSignedValue()) return true;
4805 break;
4806 case ICmpInst::ICMP_UGT:
4807 if (RA.isMinValue()) {
4808 Pred = ICmpInst::ICMP_NE;
4809 break;
4810 }
4811 if ((RA + 1).isMaxValue()) {
4812 Pred = ICmpInst::ICMP_EQ;
4813 RHS = getConstant(RA + 1);
4814 break;
4815 }
4816 if (RA.isMaxValue()) return false;
4817 break;
4818 case ICmpInst::ICMP_ULT:
4819 if (RA.isMaxValue()) {
4820 Pred = ICmpInst::ICMP_NE;
4821 break;
4822 }
4823 if ((RA - 1).isMinValue()) {
4824 Pred = ICmpInst::ICMP_EQ;
4825 RHS = getConstant(RA - 1);
4826 break;
4827 }
4828 if (RA.isMinValue()) return false;
4829 break;
4830 case ICmpInst::ICMP_SGT:
4831 if (RA.isMinSignedValue()) {
4832 Pred = ICmpInst::ICMP_NE;
4833 break;
4834 }
4835 if ((RA + 1).isMaxSignedValue()) {
4836 Pred = ICmpInst::ICMP_EQ;
4837 RHS = getConstant(RA + 1);
4838 break;
4839 }
4840 if (RA.isMaxSignedValue()) return false;
4841 break;
4842 case ICmpInst::ICMP_SLT:
4843 if (RA.isMaxSignedValue()) {
4844 Pred = ICmpInst::ICMP_NE;
4845 break;
4846 }
4847 if ((RA - 1).isMinSignedValue()) {
4848 Pred = ICmpInst::ICMP_EQ;
4849 RHS = getConstant(RA - 1);
4850 break;
4851 }
4852 if (RA.isMinSignedValue()) return false;
4853 break;
4854 }
4855 }
4856
4857 // Check to see if we can make the LHS or RHS match.
4858 if (LHS == FoundRHS || RHS == FoundLHS) {
4859 if (isa<SCEVConstant>(RHS)) {
4860 std::swap(FoundLHS, FoundRHS);
4861 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4862 } else {
4863 std::swap(LHS, RHS);
4864 Pred = ICmpInst::getSwappedPredicate(Pred);
4865 }
4866 }
4867
4868 // Check whether the found predicate is the same as the desired predicate.
4869 if (FoundPred == Pred)
4870 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4871
4872 // Check whether swapping the found predicate makes it the same as the
4873 // desired predicate.
4874 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4875 if (isa<SCEVConstant>(RHS))
4876 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4877 else
4878 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4879 RHS, LHS, FoundLHS, FoundRHS);
4880 }
4881
4882 // Check whether the actual condition is beyond sufficient.
4883 if (FoundPred == ICmpInst::ICMP_EQ)
4884 if (ICmpInst::isTrueWhenEqual(Pred))
4885 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4886 return true;
4887 if (Pred == ICmpInst::ICMP_NE)
4888 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4889 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4890 return true;
4891
4892 // Otherwise assume the worst.
4893 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004894}
4895
Dan Gohman0f4b2852009-07-21 23:03:19 +00004896/// isImpliedCondOperands - Test whether the condition described by Pred,
4897/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4898/// and FoundRHS is true.
4899bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4900 const SCEV *LHS, const SCEV *RHS,
4901 const SCEV *FoundLHS,
4902 const SCEV *FoundRHS) {
4903 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4904 FoundLHS, FoundRHS) ||
4905 // ~x < ~y --> x > y
4906 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4907 getNotSCEV(FoundRHS),
4908 getNotSCEV(FoundLHS));
4909}
4910
4911/// isImpliedCondOperandsHelper - Test whether the condition described by
4912/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4913/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004914bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004915ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4916 const SCEV *LHS, const SCEV *RHS,
4917 const SCEV *FoundLHS,
4918 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004919 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004920 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4921 case ICmpInst::ICMP_EQ:
4922 case ICmpInst::ICMP_NE:
4923 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4924 return true;
4925 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004926 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004927 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004928 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4929 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4930 return true;
4931 break;
4932 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004933 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004934 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4935 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4936 return true;
4937 break;
4938 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004939 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004940 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4941 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4942 return true;
4943 break;
4944 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004945 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004946 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4947 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4948 return true;
4949 break;
4950 }
4951
4952 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004953}
4954
Dan Gohman51f53b72009-06-21 23:46:38 +00004955/// getBECount - Subtract the end and start values and divide by the step,
4956/// rounding up, to get the number of times the backedge is executed. Return
4957/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004958const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004959 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00004960 const SCEV *Step,
4961 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00004962 assert(!isKnownNegative(Step) &&
4963 "This code doesn't handle negative strides yet!");
4964
Dan Gohman51f53b72009-06-21 23:46:38 +00004965 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004966 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4967 const SCEV *Diff = getMinusSCEV(End, Start);
4968 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004969
4970 // Add an adjustment to the difference between End and Start so that
4971 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004972 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004973
Dan Gohman1f96e672009-09-17 18:05:20 +00004974 if (!NoWrap) {
4975 // Check Add for unsigned overflow.
4976 // TODO: More sophisticated things could be done here.
4977 const Type *WideTy = IntegerType::get(getContext(),
4978 getTypeSizeInBits(Ty) + 1);
4979 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4980 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4981 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4982 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4983 return getCouldNotCompute();
4984 }
Dan Gohman51f53b72009-06-21 23:46:38 +00004985
4986 return getUDivExpr(Add, Step);
4987}
4988
Chris Lattnerdb25de42005-08-15 23:33:51 +00004989/// HowManyLessThans - Return the number of times a backedge containing the
4990/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004991/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004992ScalarEvolution::BackedgeTakenInfo
4993ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4994 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004995 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004996 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004997
Dan Gohman35738ac2009-05-04 22:30:44 +00004998 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004999 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005000 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005001
Dan Gohman1f96e672009-09-17 18:05:20 +00005002 // Check to see if we have a flag which makes analysis easy.
5003 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5004 AddRec->hasNoUnsignedWrap();
5005
Chris Lattnerdb25de42005-08-15 23:33:51 +00005006 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005007 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005008 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005009
Dan Gohman52fddd32010-01-26 04:40:18 +00005010 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005011 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005012 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005013 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005014 } else if (isKnownPositive(Step)) {
5015 // Test whether a positive iteration iteration can step past the limit
5016 // value and past the maximum value for its type in a single step.
5017 // Note that it's not sufficient to check NoWrap here, because even
5018 // though the value after a wrap is undefined, it's not undefined
5019 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005020 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005021 // iterate at least until the iteration where the wrapping occurs.
5022 const SCEV *One = getIntegerSCEV(1, Step->getType());
5023 if (isSigned) {
5024 APInt Max = APInt::getSignedMaxValue(BitWidth);
5025 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5026 .slt(getSignedRange(RHS).getSignedMax()))
5027 return getCouldNotCompute();
5028 } else {
5029 APInt Max = APInt::getMaxValue(BitWidth);
5030 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5031 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5032 return getCouldNotCompute();
5033 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005034 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005035 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005036 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005037
Dan Gohmana1af7572009-04-30 20:47:05 +00005038 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5039 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5040 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005041 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005042
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005043 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005044 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005045
Dan Gohmana1af7572009-04-30 20:47:05 +00005046 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005047 const SCEV *MinStart = getConstant(isSigned ?
5048 getSignedRange(Start).getSignedMin() :
5049 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005050
Dan Gohmana1af7572009-04-30 20:47:05 +00005051 // If we know that the condition is true in order to enter the loop,
5052 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005053 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5054 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005055 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005056 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005057 isSigned ? ICmpInst::ICMP_SLT :
5058 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005059 getMinusSCEV(Start, Step), RHS))
5060 End = isSigned ? getSMaxExpr(RHS, Start)
5061 : getUMaxExpr(RHS, Start);
5062
5063 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005064 const SCEV *MaxEnd = getConstant(isSigned ?
5065 getSignedRange(End).getSignedMax() :
5066 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005067
Dan Gohman52fddd32010-01-26 04:40:18 +00005068 // If MaxEnd is within a step of the maximum integer value in its type,
5069 // adjust it down to the minimum value which would produce the same effect.
5070 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5071 // compute the correct value.
5072 const SCEV *StepMinusOne = getMinusSCEV(Step,
5073 getIntegerSCEV(1, Step->getType()));
5074 MaxEnd = isSigned ?
5075 getSMinExpr(MaxEnd,
5076 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5077 StepMinusOne)) :
5078 getUMinExpr(MaxEnd,
5079 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5080 StepMinusOne));
5081
Dan Gohmana1af7572009-04-30 20:47:05 +00005082 // Finally, we subtract these two values and divide, rounding up, to get
5083 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005084 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005085
5086 // The maximum backedge count is similar, except using the minimum start
5087 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005088 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005089
5090 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005091 }
5092
Dan Gohman1c343752009-06-27 21:21:31 +00005093 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005094}
5095
Chris Lattner53e677a2004-04-02 20:23:17 +00005096/// getNumIterationsInRange - Return the number of iterations of this loop that
5097/// produce values in the specified constant range. Another way of looking at
5098/// this is that it returns the first iteration number where the value is not in
5099/// the condition, thus computing the exit count. If the iteration count can't
5100/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005101const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005102 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005103 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005104 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005105
5106 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005107 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005108 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005109 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005110 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005111 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005112 if (const SCEVAddRecExpr *ShiftedAddRec =
5113 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005114 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005115 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005116 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005117 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005118 }
5119
5120 // The only time we can solve this is when we have all constant indices.
5121 // Otherwise, we cannot determine the overflow conditions.
5122 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5123 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005124 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005125
5126
5127 // Okay at this point we know that all elements of the chrec are constants and
5128 // that the start element is zero.
5129
5130 // First check to see if the range contains zero. If not, the first
5131 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005132 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005133 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005134 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005135
Chris Lattner53e677a2004-04-02 20:23:17 +00005136 if (isAffine()) {
5137 // If this is an affine expression then we have this situation:
5138 // Solve {0,+,A} in Range === Ax in Range
5139
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005140 // We know that zero is in the range. If A is positive then we know that
5141 // the upper value of the range must be the first possible exit value.
5142 // If A is negative then the lower of the range is the last possible loop
5143 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005144 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005145 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5146 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005147
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005148 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005149 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005150 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005151
5152 // Evaluate at the exit value. If we really did fall out of the valid
5153 // range, then we computed our trip count, otherwise wrap around or other
5154 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005155 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005156 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005157 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005158
5159 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005160 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005161 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005162 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005163 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005164 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005165 } else if (isQuadratic()) {
5166 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5167 // quadratic equation to solve it. To do this, we must frame our problem in
5168 // terms of figuring out when zero is crossed, instead of when
5169 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005170 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005171 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005172 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005173
5174 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005175 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005176 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005177 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5178 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005179 if (R1) {
5180 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005181 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005182 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005183 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005184 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005185 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005186
Chris Lattner53e677a2004-04-02 20:23:17 +00005187 // Make sure the root is not off by one. The returned iteration should
5188 // not be in the range, but the previous one should be. When solving
5189 // for "X*X < 5", for example, we should not return a root of 2.
5190 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005191 R1->getValue(),
5192 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005193 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005194 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005195 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005196 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005197
Dan Gohman246b2562007-10-22 18:31:58 +00005198 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005199 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005200 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005201 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005202 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005203
Chris Lattner53e677a2004-04-02 20:23:17 +00005204 // If R1 was not in the range, then it is a good return value. Make
5205 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005206 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005207 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005208 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005209 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005210 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005211 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005212 }
5213 }
5214 }
5215
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005216 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005217}
5218
5219
5220
5221//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005222// SCEVCallbackVH Class Implementation
5223//===----------------------------------------------------------------------===//
5224
Dan Gohman1959b752009-05-19 19:22:47 +00005225void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005226 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005227 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5228 SE->ConstantEvolutionLoopExitValue.erase(PN);
5229 SE->Scalars.erase(getValPtr());
5230 // this now dangles!
5231}
5232
Dan Gohman1959b752009-05-19 19:22:47 +00005233void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005234 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005235
5236 // Forget all the expressions associated with users of the old value,
5237 // so that future queries will recompute the expressions using the new
5238 // value.
5239 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005240 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005241 Value *Old = getValPtr();
5242 bool DeleteOld = false;
5243 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5244 UI != UE; ++UI)
5245 Worklist.push_back(*UI);
5246 while (!Worklist.empty()) {
5247 User *U = Worklist.pop_back_val();
5248 // Deleting the Old value will cause this to dangle. Postpone
5249 // that until everything else is done.
5250 if (U == Old) {
5251 DeleteOld = true;
5252 continue;
5253 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005254 if (!Visited.insert(U))
5255 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005256 if (PHINode *PN = dyn_cast<PHINode>(U))
5257 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005258 SE->Scalars.erase(U);
5259 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5260 UI != UE; ++UI)
5261 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005262 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005263 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005264 if (DeleteOld) {
5265 if (PHINode *PN = dyn_cast<PHINode>(Old))
5266 SE->ConstantEvolutionLoopExitValue.erase(PN);
5267 SE->Scalars.erase(Old);
5268 // this now dangles!
5269 }
5270 // this may dangle!
5271}
5272
Dan Gohman1959b752009-05-19 19:22:47 +00005273ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005274 : CallbackVH(V), SE(se) {}
5275
5276//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005277// ScalarEvolution Class Implementation
5278//===----------------------------------------------------------------------===//
5279
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005280ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005281 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005282}
5283
Chris Lattner53e677a2004-04-02 20:23:17 +00005284bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005285 this->F = &F;
5286 LI = &getAnalysis<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005287 DT = &getAnalysis<DominatorTree>();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005288 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005289 return false;
5290}
5291
5292void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005293 Scalars.clear();
5294 BackedgeTakenCounts.clear();
5295 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005296 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005297 UniqueSCEVs.clear();
5298 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005299}
5300
5301void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5302 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005303 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005304 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005305}
5306
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005307bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005308 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005309}
5310
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005311static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005312 const Loop *L) {
5313 // Print all inner loops first
5314 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5315 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005316
Dan Gohman30733292010-01-09 18:17:45 +00005317 OS << "Loop ";
5318 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5319 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005320
Dan Gohman5d984912009-12-18 01:14:11 +00005321 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005322 L->getExitBlocks(ExitBlocks);
5323 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005324 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005325
Dan Gohman46bdfb02009-02-24 18:55:53 +00005326 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5327 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005328 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005329 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005330 }
5331
Dan Gohman30733292010-01-09 18:17:45 +00005332 OS << "\n"
5333 "Loop ";
5334 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5335 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005336
5337 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5338 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5339 } else {
5340 OS << "Unpredictable max backedge-taken count. ";
5341 }
5342
5343 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005344}
5345
Dan Gohman5d984912009-12-18 01:14:11 +00005346void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005347 // ScalarEvolution's implementaiton of the print method is to print
5348 // out SCEV values of all instructions that are interesting. Doing
5349 // this potentially causes it to create new SCEV objects though,
5350 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005351 // observable from outside the class though, so casting away the
5352 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005353 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005354
Dan Gohman30733292010-01-09 18:17:45 +00005355 OS << "Classifying expressions for: ";
5356 WriteAsOperand(OS, F, /*PrintType=*/false);
5357 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005358 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005359 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005360 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005361 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005362 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005363 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005364
Dan Gohman0c689c52009-06-19 17:49:54 +00005365 const Loop *L = LI->getLoopFor((*I).getParent());
5366
Dan Gohman0bba49c2009-07-07 17:06:11 +00005367 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005368 if (AtUse != SV) {
5369 OS << " --> ";
5370 AtUse->print(OS);
5371 }
5372
5373 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005374 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005375 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005376 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005377 OS << "<<Unknown>>";
5378 } else {
5379 OS << *ExitValue;
5380 }
5381 }
5382
Chris Lattner53e677a2004-04-02 20:23:17 +00005383 OS << "\n";
5384 }
5385
Dan Gohman30733292010-01-09 18:17:45 +00005386 OS << "Determining loop execution counts for: ";
5387 WriteAsOperand(OS, F, /*PrintType=*/false);
5388 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005389 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5390 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005391}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005392