blob: ca2cdca673cab6704face70e52a620f644bbddd7 [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"
Chris Lattner53e677a2004-04-02 20:23:17 +000066#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000067#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000068#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000069#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000070#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000071#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000074#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000075#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000078#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000079#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000080#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000081#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000085#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000086#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000087using namespace llvm;
88
Chris Lattner3b27d682006-12-19 22:30:33 +000089STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman844731a2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000101 "symbolically execute a constant "
102 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000103 cl::init(100));
104
Dan Gohman844731a2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000107char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000116
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000118
Chris Lattner53e677a2004-04-02 20:23:17 +0000119void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000120 print(errs());
121 errs() << '\n';
122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohman70a1fe72009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Chris Lattner53e677a2004-04-02 20:23:17 +0000135
Dan Gohman4d289bf2009-06-24 00:30:26 +0000136bool SCEV::isAllOnesValue() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isAllOnesValue();
139 return false;
140}
141
Owen Anderson753ad612009-06-22 21:57:23 +0000142SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000143 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000144
Chris Lattner53e677a2004-04-02 20:23:17 +0000145bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000146 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000151 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000152 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000153}
154
155bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000156 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000157 return false;
158}
159
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000160bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
161 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
162 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000163}
164
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000165void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000166 OS << "***COULDNOTCOMPUTE***";
167}
168
169bool SCEVCouldNotCompute::classof(const SCEV *S) {
170 return S->getSCEVType() == scCouldNotCompute;
171}
172
Dan Gohman0bba49c2009-07-07 17:06:11 +0000173const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000174 FoldingSetNodeID ID;
175 ID.AddInteger(scConstant);
176 ID.AddPointer(V);
177 void *IP = 0;
178 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
179 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000180 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000181 UniqueSCEVs.InsertNode(S, IP);
182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000186 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Dan Gohman0bba49c2009-07-07 17:06:11 +0000189const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000191 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000192 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000193}
194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Dan Gohmanc050fd92009-07-13 20:50:19 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
202 unsigned SCEVTy, const SCEV *op, const Type *ty)
203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000204
Dan Gohman84923602009-04-21 01:25:57 +0000205bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
207}
208
Dan Gohmanc050fd92009-07-13 20:50:19 +0000209SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
210 const SCEV *op, const Type *ty)
211 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000217void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000218 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
220
Dan Gohmanc050fd92009-07-13 20:50:19 +0000221SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
222 const SCEV *op, const Type *ty)
223 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000224 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
225 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000226 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000229void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000230 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmanc050fd92009-07-13 20:50:19 +0000233SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
234 const SCEV *op, const Type *ty)
235 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000236 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
237 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000238 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000239}
240
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000241void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000242 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000243}
244
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000245void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
247 const char *OpStr = getOperationStr();
248 OS << "(" << *Operands[0];
249 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
250 OS << OpStr << *Operands[i];
251 OS << ")";
252}
253
Dan Gohmanecb403a2009-05-07 14:00:19 +0000254bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000255 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
256 if (!getOperand(i)->dominates(BB, DT))
257 return false;
258 }
259 return true;
260}
261
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000262bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
263 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
264}
265
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000266void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000267 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000268}
269
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000270const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000271 // In most cases the types of LHS and RHS will be the same, but in some
272 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
273 // depend on the type for correctness, but handling types carefully can
274 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
275 // a pointer type than the RHS, so use the RHS' type here.
276 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000277}
278
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000279bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000280 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000281 if (!QueryLoop)
282 return false;
283
284 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
285 if (QueryLoop->contains(L->getHeader()))
286 return false;
287
288 // This recurrence is variant w.r.t. QueryLoop if any of its operands
289 // are variant.
290 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
291 if (!getOperand(i)->isLoopInvariant(QueryLoop))
292 return false;
293
294 // Otherwise it's loop-invariant.
295 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000296}
297
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000298void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000299 OS << "{" << *Operands[0];
300 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
301 OS << ",+," << *Operands[i];
302 OS << "}<" << L->getHeader()->getName() + ">";
303}
Chris Lattner53e677a2004-04-02 20:23:17 +0000304
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000305void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
306 // LLVM struct fields don't have names, so just print the field number.
307 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
308}
309
310void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
311 OS << "sizeof(" << *AllocTy << ")";
312}
313
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
315 // All non-instruction values are loop invariant. All instructions are loop
316 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000317 // Instructions are never considered invariant in the function body
318 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000319 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000320 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000321 return true;
322}
Chris Lattner53e677a2004-04-02 20:23:17 +0000323
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000324bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
325 if (Instruction *I = dyn_cast<Instruction>(getValue()))
326 return DT->dominates(I->getParent(), BB);
327 return true;
328}
329
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330const Type *SCEVUnknown::getType() const {
331 return V->getType();
332}
Chris Lattner53e677a2004-04-02 20:23:17 +0000333
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000334void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000335 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000336}
337
Chris Lattner8d741b82004-06-20 06:23:15 +0000338//===----------------------------------------------------------------------===//
339// SCEV Utilities
340//===----------------------------------------------------------------------===//
341
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000342static bool CompareTypes(const Type *A, const Type *B) {
343 if (A->getTypeID() != B->getTypeID())
344 return A->getTypeID() < B->getTypeID();
345 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
346 const IntegerType *BI = cast<IntegerType>(B);
347 return AI->getBitWidth() < BI->getBitWidth();
348 }
349 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
350 const PointerType *BI = cast<PointerType>(B);
351 return CompareTypes(AI->getElementType(), BI->getElementType());
352 }
353 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
354 const ArrayType *BI = cast<ArrayType>(B);
355 if (AI->getNumElements() != BI->getNumElements())
356 return AI->getNumElements() < BI->getNumElements();
357 return CompareTypes(AI->getElementType(), BI->getElementType());
358 }
359 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
360 const VectorType *BI = cast<VectorType>(B);
361 if (AI->getNumElements() != BI->getNumElements())
362 return AI->getNumElements() < BI->getNumElements();
363 return CompareTypes(AI->getElementType(), BI->getElementType());
364 }
365 if (const StructType *AI = dyn_cast<StructType>(A)) {
366 const StructType *BI = cast<StructType>(B);
367 if (AI->getNumElements() != BI->getNumElements())
368 return AI->getNumElements() < BI->getNumElements();
369 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
370 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
371 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
372 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
373 }
374 return false;
375}
376
Chris Lattner8d741b82004-06-20 06:23:15 +0000377namespace {
378 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
379 /// than the complexity of the RHS. This comparator is used to canonicalize
380 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000381 class VISIBILITY_HIDDEN SCEVComplexityCompare {
382 LoopInfo *LI;
383 public:
384 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
385
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000386 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000387 // Primarily, sort the SCEVs by their getSCEVType().
388 if (LHS->getSCEVType() != RHS->getSCEVType())
389 return LHS->getSCEVType() < RHS->getSCEVType();
390
391 // Aside from the getSCEVType() ordering, the particular ordering
392 // isn't very important except that it's beneficial to be consistent,
393 // so that (a + b) and (b + a) don't end up as different expressions.
394
395 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
396 // not as complete as it could be.
397 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
398 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
399
Dan Gohman5be18e82009-05-19 02:15:55 +0000400 // Order pointer values after integer values. This helps SCEVExpander
401 // form GEPs.
402 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
403 return false;
404 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
405 return true;
406
Dan Gohman72861302009-05-07 14:39:04 +0000407 // Compare getValueID values.
408 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
409 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
410
411 // Sort arguments by their position.
412 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
413 const Argument *RA = cast<Argument>(RU->getValue());
414 return LA->getArgNo() < RA->getArgNo();
415 }
416
417 // For instructions, compare their loop depth, and their opcode.
418 // This is pretty loose.
419 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
420 Instruction *RV = cast<Instruction>(RU->getValue());
421
422 // Compare loop depths.
423 if (LI->getLoopDepth(LV->getParent()) !=
424 LI->getLoopDepth(RV->getParent()))
425 return LI->getLoopDepth(LV->getParent()) <
426 LI->getLoopDepth(RV->getParent());
427
428 // Compare opcodes.
429 if (LV->getOpcode() != RV->getOpcode())
430 return LV->getOpcode() < RV->getOpcode();
431
432 // Compare the number of operands.
433 if (LV->getNumOperands() != RV->getNumOperands())
434 return LV->getNumOperands() < RV->getNumOperands();
435 }
436
437 return false;
438 }
439
Dan Gohman4dfad292009-06-14 22:51:25 +0000440 // Compare constant values.
441 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
442 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000443 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
444 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000445 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
446 }
447
448 // Compare addrec loop depths.
449 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
450 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
451 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
452 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
453 }
Dan Gohman72861302009-05-07 14:39:04 +0000454
455 // Lexicographically compare n-ary expressions.
456 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
457 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
458 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
459 if (i >= RC->getNumOperands())
460 return false;
461 if (operator()(LC->getOperand(i), RC->getOperand(i)))
462 return true;
463 if (operator()(RC->getOperand(i), LC->getOperand(i)))
464 return false;
465 }
466 return LC->getNumOperands() < RC->getNumOperands();
467 }
468
Dan Gohmana6b35e22009-05-07 19:23:21 +0000469 // Lexicographically compare udiv expressions.
470 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
471 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
472 if (operator()(LC->getLHS(), RC->getLHS()))
473 return true;
474 if (operator()(RC->getLHS(), LC->getLHS()))
475 return false;
476 if (operator()(LC->getRHS(), RC->getRHS()))
477 return true;
478 if (operator()(RC->getRHS(), LC->getRHS()))
479 return false;
480 return false;
481 }
482
Dan Gohman72861302009-05-07 14:39:04 +0000483 // Compare cast expressions by operand.
484 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
485 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
486 return operator()(LC->getOperand(), RC->getOperand());
487 }
488
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000489 // Compare offsetof expressions.
490 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
491 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
492 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
493 CompareTypes(RA->getStructType(), LA->getStructType()))
494 return CompareTypes(LA->getStructType(), RA->getStructType());
495 return LA->getFieldNo() < RA->getFieldNo();
496 }
497
498 // Compare sizeof expressions by the allocation type.
499 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
500 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
501 return CompareTypes(LA->getAllocType(), RA->getAllocType());
502 }
503
Torok Edwinc23197a2009-07-14 16:55:14 +0000504 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000505 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000506 }
507 };
508}
509
510/// GroupByComplexity - Given a list of SCEV objects, order them by their
511/// complexity, and group objects of the same complexity together by value.
512/// When this routine is finished, we know that any duplicates in the vector are
513/// consecutive and that complexity is monotonically increasing.
514///
515/// Note that we go take special precautions to ensure that we get determinstic
516/// results from this routine. In other words, we don't want the results of
517/// this to depend on where the addresses of various SCEV objects happened to
518/// land in memory.
519///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000520static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000521 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000522 if (Ops.size() < 2) return; // Noop
523 if (Ops.size() == 2) {
524 // This is the common case, which also happens to be trivially simple.
525 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000526 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000527 std::swap(Ops[0], Ops[1]);
528 return;
529 }
530
531 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000532 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000533
534 // Now that we are sorted by complexity, group elements of the same
535 // complexity. Note that this is, at worst, N^2, but the vector is likely to
536 // be extremely short in practice. Note that we take this approach because we
537 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000538 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000539 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000540 unsigned Complexity = S->getSCEVType();
541
542 // If there are any objects of the same complexity and same value as this
543 // one, group them.
544 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
545 if (Ops[j] == S) { // Found a duplicate.
546 // Move it to immediately after i'th element.
547 std::swap(Ops[i+1], Ops[j]);
548 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000549 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000550 }
551 }
552 }
553}
554
Chris Lattner53e677a2004-04-02 20:23:17 +0000555
Chris Lattner53e677a2004-04-02 20:23:17 +0000556
557//===----------------------------------------------------------------------===//
558// Simple SCEV method implementations
559//===----------------------------------------------------------------------===//
560
Eli Friedmanb42a6262008-08-04 23:49:06 +0000561/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000562/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000563static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000564 ScalarEvolution &SE,
565 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000566 // Handle the simplest case efficiently.
567 if (K == 1)
568 return SE.getTruncateOrZeroExtend(It, ResultTy);
569
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000570 // We are using the following formula for BC(It, K):
571 //
572 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
573 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000574 // Suppose, W is the bitwidth of the return value. We must be prepared for
575 // overflow. Hence, we must assure that the result of our computation is
576 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
577 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000578 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000579 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000580 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000581 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
582 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000583 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000584 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000585 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586 // This formula is trivially equivalent to the previous formula. However,
587 // this formula can be implemented much more efficiently. The trick is that
588 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
589 // arithmetic. To do exact division in modular arithmetic, all we have
590 // to do is multiply by the inverse. Therefore, this step can be done at
591 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000592 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000593 // The next issue is how to safely do the division by 2^T. The way this
594 // is done is by doing the multiplication step at a width of at least W + T
595 // bits. This way, the bottom W+T bits of the product are accurate. Then,
596 // when we perform the division by 2^T (which is equivalent to a right shift
597 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
598 // truncated out after the division by 2^T.
599 //
600 // In comparison to just directly using the first formula, this technique
601 // is much more efficient; using the first formula requires W * K bits,
602 // but this formula less than W + K bits. Also, the first formula requires
603 // a division step, whereas this formula only requires multiplies and shifts.
604 //
605 // It doesn't matter whether the subtraction step is done in the calculation
606 // width or the input iteration count's width; if the subtraction overflows,
607 // the result must be zero anyway. We prefer here to do it in the width of
608 // the induction variable because it helps a lot for certain cases; CodeGen
609 // isn't smart enough to ignore the overflow, which leads to much less
610 // efficient code if the width of the subtraction is wider than the native
611 // register width.
612 //
613 // (It's possible to not widen at all by pulling out factors of 2 before
614 // the multiplication; for example, K=2 can be calculated as
615 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
616 // extra arithmetic, so it's not an obvious win, and it gets
617 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000618
Eli Friedmanb42a6262008-08-04 23:49:06 +0000619 // Protection from insane SCEVs; this bound is conservative,
620 // but it probably doesn't matter.
621 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000622 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000623
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000624 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000625
Eli Friedmanb42a6262008-08-04 23:49:06 +0000626 // Calculate K! / 2^T and T; we divide out the factors of two before
627 // multiplying for calculating K! / 2^T to avoid overflow.
628 // Other overflow doesn't matter because we only care about the bottom
629 // W bits of the result.
630 APInt OddFactorial(W, 1);
631 unsigned T = 1;
632 for (unsigned i = 3; i <= K; ++i) {
633 APInt Mult(W, i);
634 unsigned TwoFactors = Mult.countTrailingZeros();
635 T += TwoFactors;
636 Mult = Mult.lshr(TwoFactors);
637 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000638 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000639
Eli Friedmanb42a6262008-08-04 23:49:06 +0000640 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000641 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000642
643 // Calcuate 2^T, at width T+W.
644 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
645
646 // Calculate the multiplicative inverse of K! / 2^T;
647 // this multiplication factor will perform the exact division by
648 // K! / 2^T.
649 APInt Mod = APInt::getSignedMinValue(W+1);
650 APInt MultiplyFactor = OddFactorial.zext(W+1);
651 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
652 MultiplyFactor = MultiplyFactor.trunc(W);
653
654 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000655 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
656 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000657 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000658 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000659 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000660 Dividend = SE.getMulExpr(Dividend,
661 SE.getTruncateOrZeroExtend(S, CalculationTy));
662 }
663
664 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000665 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000666
667 // Truncate the result, and divide by K! / 2^T.
668
669 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
670 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000671}
672
Chris Lattner53e677a2004-04-02 20:23:17 +0000673/// evaluateAtIteration - Return the value of this chain of recurrences at
674/// the specified iteration number. We can evaluate this recurrence by
675/// multiplying each element in the chain by the binomial coefficient
676/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
677///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000678/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000679///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000680/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000681///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000682const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000683 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000684 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000685 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000686 // The computation is correct in the face of overflow provided that the
687 // multiplication is performed _after_ the evaluation of the binomial
688 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000689 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000690 if (isa<SCEVCouldNotCompute>(Coeff))
691 return Coeff;
692
693 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000694 }
695 return Result;
696}
697
Chris Lattner53e677a2004-04-02 20:23:17 +0000698//===----------------------------------------------------------------------===//
699// SCEV Expression folder implementations
700//===----------------------------------------------------------------------===//
701
Dan Gohman0bba49c2009-07-07 17:06:11 +0000702const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000703 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000704 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000705 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000706 assert(isSCEVable(Ty) &&
707 "This is not a conversion to a SCEVable type!");
708 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000709
Dan Gohmanc050fd92009-07-13 20:50:19 +0000710 FoldingSetNodeID ID;
711 ID.AddInteger(scTruncate);
712 ID.AddPointer(Op);
713 ID.AddPointer(Ty);
714 void *IP = 0;
715 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
716
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000717 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000718 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000719 return getConstant(
720 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000721
Dan Gohman20900ca2009-04-22 16:20:48 +0000722 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000723 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000724 return getTruncateExpr(ST->getOperand(), Ty);
725
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000726 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000727 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000728 return getTruncateOrSignExtend(SS->getOperand(), Ty);
729
730 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000731 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000732 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
733
Dan Gohman6864db62009-06-18 16:24:47 +0000734 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000735 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000736 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000737 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000738 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
739 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000740 }
741
Dan Gohmanc050fd92009-07-13 20:50:19 +0000742 // The cast wasn't folded; create an explicit cast node.
743 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000744 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
745 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000746 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000747 UniqueSCEVs.InsertNode(S, IP);
748 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000749}
750
Dan Gohman0bba49c2009-07-07 17:06:11 +0000751const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000752 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000753 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000754 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000755 assert(isSCEVable(Ty) &&
756 "This is not a conversion to a SCEVable type!");
757 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000758
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000759 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000761 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000762 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
763 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000764 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000765 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000766
Dan Gohman20900ca2009-04-22 16:20:48 +0000767 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000769 return getZeroExtendExpr(SZ->getOperand(), Ty);
770
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000771 // Before doing any expensive analysis, check to see if we've already
772 // computed a SCEV for this Op and Ty.
773 FoldingSetNodeID ID;
774 ID.AddInteger(scZeroExtend);
775 ID.AddPointer(Op);
776 ID.AddPointer(Ty);
777 void *IP = 0;
778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
779
Dan Gohman01ecca22009-04-27 20:16:15 +0000780 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000781 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000782 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000783 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000784 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000785 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000786 const SCEV *Start = AR->getStart();
787 const SCEV *Step = AR->getStepRecurrence(*this);
788 unsigned BitWidth = getTypeSizeInBits(AR->getType());
789 const Loop *L = AR->getLoop();
790
Dan Gohmaneb490a72009-07-25 01:22:26 +0000791 // If we have special knowledge that this addrec won't overflow,
792 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000793 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000794 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
795 getZeroExtendExpr(Step, Ty),
796 L);
797
Dan Gohman01ecca22009-04-27 20:16:15 +0000798 // Check whether the backedge-taken count is SCEVCouldNotCompute.
799 // Note that this serves two purposes: It filters out loops that are
800 // simply not analyzable, and it covers the case where this code is
801 // being called from within backedge-taken count analysis, such that
802 // attempting to ask for the backedge-taken count would likely result
803 // in infinite recursion. In the later case, the analysis code will
804 // cope with a conservative value, and it will take care to purge
805 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000806 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000807 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000808 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000809 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000810
811 // Check whether the backedge-taken count can be losslessly casted to
812 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000813 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000814 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000815 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000816 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
817 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000818 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000819 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000820 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000821 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000822 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000823 const SCEV *Add = getAddExpr(Start, ZMul);
824 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000825 getAddExpr(getZeroExtendExpr(Start, WideTy),
826 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
827 getZeroExtendExpr(Step, WideTy)));
828 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000829 // Return the expression with the addrec on the outside.
830 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
831 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000832 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000833
834 // Similar to above, only this time treat the step value as signed.
835 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000836 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000837 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000838 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000839 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000840 OperandExtendedAdd =
841 getAddExpr(getZeroExtendExpr(Start, WideTy),
842 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
843 getSignExtendExpr(Step, WideTy)));
844 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000845 // Return the expression with the addrec on the outside.
846 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
847 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000848 L);
849 }
850
851 // If the backedge is guarded by a comparison with the pre-inc value
852 // the addrec is safe. Also, if the entry is guarded by a comparison
853 // with the start value and the backedge is guarded by a comparison
854 // with the post-inc value, the addrec is safe.
855 if (isKnownPositive(Step)) {
856 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
857 getUnsignedRange(Step).getUnsignedMax());
858 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
859 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
860 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
861 AR->getPostIncExpr(*this), N)))
862 // Return the expression with the addrec on the outside.
863 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
864 getZeroExtendExpr(Step, Ty),
865 L);
866 } else if (isKnownNegative(Step)) {
867 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
868 getSignedRange(Step).getSignedMin());
869 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
870 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
871 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
872 AR->getPostIncExpr(*this), N)))
873 // Return the expression with the addrec on the outside.
874 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
875 getSignExtendExpr(Step, Ty),
876 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000877 }
878 }
879 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000880
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000881 // The cast wasn't folded; create an explicit cast node.
882 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000883 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
884 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000885 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000886 UniqueSCEVs.InsertNode(S, IP);
887 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000888}
889
Dan Gohman0bba49c2009-07-07 17:06:11 +0000890const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000891 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000892 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000893 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000894 assert(isSCEVable(Ty) &&
895 "This is not a conversion to a SCEVable type!");
896 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000897
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000898 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000899 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000900 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000901 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
902 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000903 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000904 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000905
Dan Gohman20900ca2009-04-22 16:20:48 +0000906 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000907 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000908 return getSignExtendExpr(SS->getOperand(), Ty);
909
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000910 // Before doing any expensive analysis, check to see if we've already
911 // computed a SCEV for this Op and Ty.
912 FoldingSetNodeID ID;
913 ID.AddInteger(scSignExtend);
914 ID.AddPointer(Op);
915 ID.AddPointer(Ty);
916 void *IP = 0;
917 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
918
Dan Gohman01ecca22009-04-27 20:16:15 +0000919 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000920 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000921 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000922 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000924 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000925 const SCEV *Start = AR->getStart();
926 const SCEV *Step = AR->getStepRecurrence(*this);
927 unsigned BitWidth = getTypeSizeInBits(AR->getType());
928 const Loop *L = AR->getLoop();
929
Dan Gohmaneb490a72009-07-25 01:22:26 +0000930 // If we have special knowledge that this addrec won't overflow,
931 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000932 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000933 return getAddRecExpr(getSignExtendExpr(Start, Ty),
934 getSignExtendExpr(Step, Ty),
935 L);
936
Dan Gohman01ecca22009-04-27 20:16:15 +0000937 // Check whether the backedge-taken count is SCEVCouldNotCompute.
938 // Note that this serves two purposes: It filters out loops that are
939 // simply not analyzable, and it covers the case where this code is
940 // being called from within backedge-taken count analysis, such that
941 // attempting to ask for the backedge-taken count would likely result
942 // in infinite recursion. In the later case, the analysis code will
943 // cope with a conservative value, and it will take care to purge
944 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000945 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000946 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000947 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000948 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000949
950 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000951 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000952 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000953 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000954 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000955 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
956 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000957 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000958 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000959 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000960 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000961 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000962 const SCEV *Add = getAddExpr(Start, SMul);
963 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000964 getAddExpr(getSignExtendExpr(Start, WideTy),
965 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
966 getSignExtendExpr(Step, WideTy)));
967 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000968 // Return the expression with the addrec on the outside.
969 return getAddRecExpr(getSignExtendExpr(Start, Ty),
970 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000971 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000972
973 // Similar to above, only this time treat the step value as unsigned.
974 // This covers loops that count up with an unsigned step.
975 const SCEV *UMul =
976 getMulExpr(CastedMaxBECount,
977 getTruncateOrZeroExtend(Step, Start->getType()));
978 Add = getAddExpr(Start, UMul);
979 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +0000980 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +0000981 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
982 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +0000983 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +0000984 // Return the expression with the addrec on the outside.
985 return getAddRecExpr(getSignExtendExpr(Start, Ty),
986 getZeroExtendExpr(Step, Ty),
987 L);
Dan Gohman85b05a22009-07-13 21:35:55 +0000988 }
989
990 // If the backedge is guarded by a comparison with the pre-inc value
991 // the addrec is safe. Also, if the entry is guarded by a comparison
992 // with the start value and the backedge is guarded by a comparison
993 // with the post-inc value, the addrec is safe.
994 if (isKnownPositive(Step)) {
995 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
996 getSignedRange(Step).getSignedMax());
997 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
998 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
999 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1000 AR->getPostIncExpr(*this), N)))
1001 // Return the expression with the addrec on the outside.
1002 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1003 getSignExtendExpr(Step, Ty),
1004 L);
1005 } else if (isKnownNegative(Step)) {
1006 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1007 getSignedRange(Step).getSignedMin());
1008 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1009 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1010 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1011 AR->getPostIncExpr(*this), N)))
1012 // Return the expression with the addrec on the outside.
1013 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1014 getSignExtendExpr(Step, Ty),
1015 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001016 }
1017 }
1018 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001019
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001020 // The cast wasn't folded; create an explicit cast node.
1021 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001022 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1023 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001024 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001025 UniqueSCEVs.InsertNode(S, IP);
1026 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001027}
1028
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001029/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1030/// unspecified bits out to the given type.
1031///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001032const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001033 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001034 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1035 "This is not an extending conversion!");
1036 assert(isSCEVable(Ty) &&
1037 "This is not a conversion to a SCEVable type!");
1038 Ty = getEffectiveSCEVType(Ty);
1039
1040 // Sign-extend negative constants.
1041 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1042 if (SC->getValue()->getValue().isNegative())
1043 return getSignExtendExpr(Op, Ty);
1044
1045 // Peel off a truncate cast.
1046 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001047 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001048 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1049 return getAnyExtendExpr(NewOp, Ty);
1050 return getTruncateOrNoop(NewOp, Ty);
1051 }
1052
1053 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001054 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001055 if (!isa<SCEVZeroExtendExpr>(ZExt))
1056 return ZExt;
1057
1058 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001059 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001060 if (!isa<SCEVSignExtendExpr>(SExt))
1061 return SExt;
1062
1063 // If the expression is obviously signed, use the sext cast value.
1064 if (isa<SCEVSMaxExpr>(Op))
1065 return SExt;
1066
1067 // Absent any other information, use the zext cast value.
1068 return ZExt;
1069}
1070
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001071/// CollectAddOperandsWithScales - Process the given Ops list, which is
1072/// a list of operands to be added under the given scale, update the given
1073/// map. This is a helper function for getAddRecExpr. As an example of
1074/// what it does, given a sequence of operands that would form an add
1075/// expression like this:
1076///
1077/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1078///
1079/// where A and B are constants, update the map with these values:
1080///
1081/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1082///
1083/// and add 13 + A*B*29 to AccumulatedConstant.
1084/// This will allow getAddRecExpr to produce this:
1085///
1086/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1087///
1088/// This form often exposes folding opportunities that are hidden in
1089/// the original operand list.
1090///
1091/// Return true iff it appears that any interesting folding opportunities
1092/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1093/// the common case where no interesting opportunities are present, and
1094/// is also used as a check to avoid infinite recursion.
1095///
1096static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001097CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1098 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001099 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001100 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001101 const APInt &Scale,
1102 ScalarEvolution &SE) {
1103 bool Interesting = false;
1104
1105 // Iterate over the add operands.
1106 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1107 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1108 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1109 APInt NewScale =
1110 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1111 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1112 // A multiplication of a constant with another add; recurse.
1113 Interesting |=
1114 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1115 cast<SCEVAddExpr>(Mul->getOperand(1))
1116 ->getOperands(),
1117 NewScale, SE);
1118 } else {
1119 // A multiplication of a constant with some other value. Update
1120 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001121 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1122 const SCEV *Key = SE.getMulExpr(MulOps);
1123 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001124 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001125 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001126 NewOps.push_back(Pair.first->first);
1127 } else {
1128 Pair.first->second += NewScale;
1129 // The map already had an entry for this value, which may indicate
1130 // a folding opportunity.
1131 Interesting = true;
1132 }
1133 }
1134 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1135 // Pull a buried constant out to the outside.
1136 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1137 Interesting = true;
1138 AccumulatedConstant += Scale * C->getValue()->getValue();
1139 } else {
1140 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001141 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001142 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001143 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001144 NewOps.push_back(Pair.first->first);
1145 } else {
1146 Pair.first->second += Scale;
1147 // The map already had an entry for this value, which may indicate
1148 // a folding opportunity.
1149 Interesting = true;
1150 }
1151 }
1152 }
1153
1154 return Interesting;
1155}
1156
1157namespace {
1158 struct APIntCompare {
1159 bool operator()(const APInt &LHS, const APInt &RHS) const {
1160 return LHS.ult(RHS);
1161 }
1162 };
1163}
1164
Dan Gohman6c0866c2009-05-24 23:45:28 +00001165/// getAddExpr - Get a canonical add expression, or something simpler if
1166/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001167const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001168 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001169 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001170#ifndef NDEBUG
1171 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1172 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1173 getEffectiveSCEVType(Ops[0]->getType()) &&
1174 "SCEVAddExpr operand types don't match!");
1175#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001176
1177 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001178 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001179
1180 // If there are any constants, fold them together.
1181 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001182 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001183 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001184 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001185 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001186 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001187 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1188 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001189 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001190 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001191 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001192 }
1193
1194 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001195 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001196 Ops.erase(Ops.begin());
1197 --Idx;
1198 }
1199 }
1200
Chris Lattner627018b2004-04-07 16:16:11 +00001201 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001202
Chris Lattner53e677a2004-04-02 20:23:17 +00001203 // Okay, check to see if the same value occurs in the operand list twice. If
1204 // so, merge them together into an multiply expression. Since we sorted the
1205 // list, these values are required to be adjacent.
1206 const Type *Ty = Ops[0]->getType();
1207 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1208 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1209 // Found a match, merge the two values into a multiply, and add any
1210 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001211 const SCEV *Two = getIntegerSCEV(2, Ty);
1212 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001213 if (Ops.size() == 2)
1214 return Mul;
1215 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1216 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001217 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001218 }
1219
Dan Gohman728c7f32009-05-08 21:03:19 +00001220 // Check for truncates. If all the operands are truncated from the same
1221 // type, see if factoring out the truncate would permit the result to be
1222 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1223 // if the contents of the resulting outer trunc fold to something simple.
1224 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1225 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1226 const Type *DstType = Trunc->getType();
1227 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001228 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001229 bool Ok = true;
1230 // Check all the operands to see if they can be represented in the
1231 // source type of the truncate.
1232 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1233 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1234 if (T->getOperand()->getType() != SrcType) {
1235 Ok = false;
1236 break;
1237 }
1238 LargeOps.push_back(T->getOperand());
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // This could be either sign or zero extension, but sign extension
1241 // is much more likely to be foldable here.
1242 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1243 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001244 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001245 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1246 if (const SCEVTruncateExpr *T =
1247 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1248 if (T->getOperand()->getType() != SrcType) {
1249 Ok = false;
1250 break;
1251 }
1252 LargeMulOps.push_back(T->getOperand());
1253 } else if (const SCEVConstant *C =
1254 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1255 // This could be either sign or zero extension, but sign extension
1256 // is much more likely to be foldable here.
1257 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1258 } else {
1259 Ok = false;
1260 break;
1261 }
1262 }
1263 if (Ok)
1264 LargeOps.push_back(getMulExpr(LargeMulOps));
1265 } else {
1266 Ok = false;
1267 break;
1268 }
1269 }
1270 if (Ok) {
1271 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001272 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001273 // If it folds to something simple, use it. Otherwise, don't.
1274 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1275 return getTruncateExpr(Fold, DstType);
1276 }
1277 }
1278
1279 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001280 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1281 ++Idx;
1282
1283 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001284 if (Idx < Ops.size()) {
1285 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001286 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001287 // If we have an add, expand the add operands onto the end of the operands
1288 // list.
1289 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1290 Ops.erase(Ops.begin()+Idx);
1291 DeletedAdd = true;
1292 }
1293
1294 // If we deleted at least one add, we added operands to the end of the list,
1295 // and they are not necessarily sorted. Recurse to resort and resimplify
1296 // any operands we just aquired.
1297 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001298 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001299 }
1300
1301 // Skip over the add expression until we get to a multiply.
1302 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1303 ++Idx;
1304
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001305 // Check to see if there are any folding opportunities present with
1306 // operands multiplied by constant values.
1307 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1308 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001309 DenseMap<const SCEV *, APInt> M;
1310 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001311 APInt AccumulatedConstant(BitWidth, 0);
1312 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1313 Ops, APInt(BitWidth, 1), *this)) {
1314 // Some interesting folding opportunity is present, so its worthwhile to
1315 // re-generate the operands list. Group the operands by constant scale,
1316 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001317 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1318 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001319 E = NewOps.end(); I != E; ++I)
1320 MulOpLists[M.find(*I)->second].push_back(*I);
1321 // Re-generate the operands list.
1322 Ops.clear();
1323 if (AccumulatedConstant != 0)
1324 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001325 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1326 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001327 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001328 Ops.push_back(getMulExpr(getConstant(I->first),
1329 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001330 if (Ops.empty())
1331 return getIntegerSCEV(0, Ty);
1332 if (Ops.size() == 1)
1333 return Ops[0];
1334 return getAddExpr(Ops);
1335 }
1336 }
1337
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 // If we are adding something to a multiply expression, make sure the
1339 // something is not already an operand of the multiply. If so, merge it into
1340 // the multiply.
1341 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001342 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001343 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001344 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001345 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001346 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001347 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001348 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 if (Mul->getNumOperands() != 2) {
1350 // If the multiply has more than two operands, we must get the
1351 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001352 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001353 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001354 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001356 const SCEV *One = getIntegerSCEV(1, Ty);
1357 const SCEV *AddOne = getAddExpr(InnerMul, One);
1358 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001359 if (Ops.size() == 2) return OuterMul;
1360 if (AddOp < Idx) {
1361 Ops.erase(Ops.begin()+AddOp);
1362 Ops.erase(Ops.begin()+Idx-1);
1363 } else {
1364 Ops.erase(Ops.begin()+Idx);
1365 Ops.erase(Ops.begin()+AddOp-1);
1366 }
1367 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001368 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001369 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001370
Chris Lattner53e677a2004-04-02 20:23:17 +00001371 // Check this multiply against other multiplies being added together.
1372 for (unsigned OtherMulIdx = Idx+1;
1373 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1374 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001375 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001376 // If MulOp occurs in OtherMul, we can fold the two multiplies
1377 // together.
1378 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1379 OMulOp != e; ++OMulOp)
1380 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1381 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001382 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001383 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001384 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1385 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001387 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001388 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001389 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001390 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001391 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1392 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001393 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001394 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001396 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1397 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001398 if (Ops.size() == 2) return OuterMul;
1399 Ops.erase(Ops.begin()+Idx);
1400 Ops.erase(Ops.begin()+OtherMulIdx-1);
1401 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001402 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001403 }
1404 }
1405 }
1406 }
1407
1408 // If there are any add recurrences in the operands list, see if any other
1409 // added values are loop invariant. If so, we can fold them into the
1410 // recurrence.
1411 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1412 ++Idx;
1413
1414 // Scan over all recurrences, trying to fold loop invariants into them.
1415 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1416 // Scan all of the other operands to this add and add them to the vector if
1417 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001418 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001419 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001420 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1421 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1422 LIOps.push_back(Ops[i]);
1423 Ops.erase(Ops.begin()+i);
1424 --i; --e;
1425 }
1426
1427 // If we found some loop invariants, fold them into the recurrence.
1428 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001429 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 LIOps.push_back(AddRec->getStart());
1431
Dan Gohman0bba49c2009-07-07 17:06:11 +00001432 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001433 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001434 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001435
Dan Gohman0bba49c2009-07-07 17:06:11 +00001436 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 // If all of the other operands were loop invariant, we are done.
1438 if (Ops.size() == 1) return NewRec;
1439
1440 // Otherwise, add the folded AddRec by the non-liv parts.
1441 for (unsigned i = 0;; ++i)
1442 if (Ops[i] == AddRec) {
1443 Ops[i] = NewRec;
1444 break;
1445 }
Dan Gohman246b2562007-10-22 18:31:58 +00001446 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001447 }
1448
1449 // Okay, if there weren't any loop invariants to be folded, check to see if
1450 // there are multiple AddRec's with the same loop induction variable being
1451 // added together. If so, we can fold them.
1452 for (unsigned OtherIdx = Idx+1;
1453 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1454 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001455 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001456 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1457 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001458 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1459 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1461 if (i >= NewOps.size()) {
1462 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1463 OtherAddRec->op_end());
1464 break;
1465 }
Dan Gohman246b2562007-10-22 18:31:58 +00001466 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001468 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001469
1470 if (Ops.size() == 2) return NewAddRec;
1471
1472 Ops.erase(Ops.begin()+Idx);
1473 Ops.erase(Ops.begin()+OtherIdx-1);
1474 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001475 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 }
1477 }
1478
1479 // Otherwise couldn't fold anything into this recurrence. Move onto the
1480 // next one.
1481 }
1482
1483 // Okay, it looks like we really DO need an add expr. Check to see if we
1484 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001485 FoldingSetNodeID ID;
1486 ID.AddInteger(scAddExpr);
1487 ID.AddInteger(Ops.size());
1488 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1489 ID.AddPointer(Ops[i]);
1490 void *IP = 0;
1491 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1492 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001493 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001494 UniqueSCEVs.InsertNode(S, IP);
1495 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001496}
1497
1498
Dan Gohman6c0866c2009-05-24 23:45:28 +00001499/// getMulExpr - Get a canonical multiply expression, or something simpler if
1500/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001501const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001502 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001503#ifndef NDEBUG
1504 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1505 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1506 getEffectiveSCEVType(Ops[0]->getType()) &&
1507 "SCEVMulExpr operand types don't match!");
1508#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001509
1510 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001511 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001512
1513 // If there are any constants, fold them together.
1514 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001515 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001516
1517 // C1*(C2+V) -> C1*C2 + C1*V
1518 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001519 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 if (Add->getNumOperands() == 2 &&
1521 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001522 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1523 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001524
1525
1526 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001527 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001528 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001529 ConstantInt *Fold = ConstantInt::get(getContext(),
1530 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001531 RHSC->getValue()->getValue());
1532 Ops[0] = getConstant(Fold);
1533 Ops.erase(Ops.begin()+1); // Erase the folded element
1534 if (Ops.size() == 1) return Ops[0];
1535 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 }
1537
1538 // If we are left with a constant one being multiplied, strip it off.
1539 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1540 Ops.erase(Ops.begin());
1541 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001542 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 // If we have a multiply of zero, it will always be zero.
1544 return Ops[0];
1545 }
1546 }
1547
1548 // Skip over the add expression until we get to a multiply.
1549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1550 ++Idx;
1551
1552 if (Ops.size() == 1)
1553 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001554
Chris Lattner53e677a2004-04-02 20:23:17 +00001555 // If there are mul operands inline them all into this expression.
1556 if (Idx < Ops.size()) {
1557 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001558 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001559 // If we have an mul, expand the mul operands onto the end of the operands
1560 // list.
1561 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1562 Ops.erase(Ops.begin()+Idx);
1563 DeletedMul = true;
1564 }
1565
1566 // If we deleted at least one mul, we added operands to the end of the list,
1567 // and they are not necessarily sorted. Recurse to resort and resimplify
1568 // any operands we just aquired.
1569 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001570 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001571 }
1572
1573 // If there are any add recurrences in the operands list, see if any other
1574 // added values are loop invariant. If so, we can fold them into the
1575 // recurrence.
1576 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1577 ++Idx;
1578
1579 // Scan over all recurrences, trying to fold loop invariants into them.
1580 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1581 // Scan all of the other operands to this mul and add them to the vector if
1582 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001583 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001584 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001585 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1586 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1587 LIOps.push_back(Ops[i]);
1588 Ops.erase(Ops.begin()+i);
1589 --i; --e;
1590 }
1591
1592 // If we found some loop invariants, fold them into the recurrence.
1593 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001594 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001595 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 NewOps.reserve(AddRec->getNumOperands());
1597 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001598 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001599 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001600 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001601 } else {
1602 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001603 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001604 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001605 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001606 }
1607 }
1608
Dan Gohman0bba49c2009-07-07 17:06:11 +00001609 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001610
1611 // If all of the other operands were loop invariant, we are done.
1612 if (Ops.size() == 1) return NewRec;
1613
1614 // Otherwise, multiply the folded AddRec by the non-liv parts.
1615 for (unsigned i = 0;; ++i)
1616 if (Ops[i] == AddRec) {
1617 Ops[i] = NewRec;
1618 break;
1619 }
Dan Gohman246b2562007-10-22 18:31:58 +00001620 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001621 }
1622
1623 // Okay, if there weren't any loop invariants to be folded, check to see if
1624 // there are multiple AddRec's with the same loop induction variable being
1625 // multiplied together. If so, we can fold them.
1626 for (unsigned OtherIdx = Idx+1;
1627 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1628 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001629 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1631 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001632 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001633 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001634 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001635 const SCEV *B = F->getStepRecurrence(*this);
1636 const SCEV *D = G->getStepRecurrence(*this);
1637 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001638 getMulExpr(G, B),
1639 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001640 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001641 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001642 if (Ops.size() == 2) return NewAddRec;
1643
1644 Ops.erase(Ops.begin()+Idx);
1645 Ops.erase(Ops.begin()+OtherIdx-1);
1646 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001647 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001648 }
1649 }
1650
1651 // Otherwise couldn't fold anything into this recurrence. Move onto the
1652 // next one.
1653 }
1654
1655 // Okay, it looks like we really DO need an mul expr. Check to see if we
1656 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001657 FoldingSetNodeID ID;
1658 ID.AddInteger(scMulExpr);
1659 ID.AddInteger(Ops.size());
1660 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1661 ID.AddPointer(Ops[i]);
1662 void *IP = 0;
1663 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1664 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001665 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001666 UniqueSCEVs.InsertNode(S, IP);
1667 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001668}
1669
Andreas Bolka8a11c982009-08-07 22:55:26 +00001670/// getUDivExpr - Get a canonical unsigned division expression, or something
1671/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001672const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1673 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001674 assert(getEffectiveSCEVType(LHS->getType()) ==
1675 getEffectiveSCEVType(RHS->getType()) &&
1676 "SCEVUDivExpr operand types don't match!");
1677
Dan Gohman622ed672009-05-04 22:02:23 +00001678 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001679 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001680 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001681 if (RHSC->isZero())
1682 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001683
Dan Gohman185cf032009-05-08 20:18:49 +00001684 // Determine if the division can be folded into the operands of
1685 // its operands.
1686 // TODO: Generalize this to non-constants by using known-bits information.
1687 const Type *Ty = LHS->getType();
1688 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1689 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1690 // For non-power-of-two values, effectively round the value up to the
1691 // nearest power of two.
1692 if (!RHSC->getValue()->getValue().isPowerOf2())
1693 ++MaxShiftAmt;
1694 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001695 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001696 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1697 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1698 if (const SCEVConstant *Step =
1699 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1700 if (!Step->getValue()->getValue()
1701 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001702 getZeroExtendExpr(AR, ExtTy) ==
1703 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1704 getZeroExtendExpr(Step, ExtTy),
1705 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001706 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001707 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1708 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1709 return getAddRecExpr(Operands, AR->getLoop());
1710 }
1711 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001712 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001713 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001714 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1715 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1716 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001717 // Find an operand that's safely divisible.
1718 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001719 const SCEV *Op = M->getOperand(i);
1720 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001721 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001722 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1723 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001724 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001725 Operands[i] = Div;
1726 return getMulExpr(Operands);
1727 }
1728 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001729 }
Dan Gohman185cf032009-05-08 20:18:49 +00001730 // (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 +00001731 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001732 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001733 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1734 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1735 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1736 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001737 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001738 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001739 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1740 break;
1741 Operands.push_back(Op);
1742 }
1743 if (Operands.size() == A->getNumOperands())
1744 return getAddExpr(Operands);
1745 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001746 }
Dan Gohman185cf032009-05-08 20:18:49 +00001747
1748 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001749 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001750 Constant *LHSCV = LHSC->getValue();
1751 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001752 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001753 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001754 }
1755 }
1756
Dan Gohman1c343752009-06-27 21:21:31 +00001757 FoldingSetNodeID ID;
1758 ID.AddInteger(scUDivExpr);
1759 ID.AddPointer(LHS);
1760 ID.AddPointer(RHS);
1761 void *IP = 0;
1762 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1763 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001764 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001765 UniqueSCEVs.InsertNode(S, IP);
1766 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001767}
1768
1769
Dan Gohman6c0866c2009-05-24 23:45:28 +00001770/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1771/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001772const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohmand1e5db62009-07-24 01:03:59 +00001773 const SCEV *Step, const Loop *L) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001774 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001775 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001776 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 if (StepChrec->getLoop() == L) {
1778 Operands.insert(Operands.end(), StepChrec->op_begin(),
1779 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001780 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001781 }
1782
1783 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001784 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001785}
1786
Dan Gohman6c0866c2009-05-24 23:45:28 +00001787/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1788/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001789const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001790ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001791 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001792 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001793#ifndef NDEBUG
1794 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1795 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1796 getEffectiveSCEVType(Operands[0]->getType()) &&
1797 "SCEVAddRecExpr operand types don't match!");
1798#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001799
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001800 if (Operands.back()->isZero()) {
1801 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001802 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001803 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001804
Dan Gohmand9cc7492008-08-08 18:33:12 +00001805 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001806 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001807 const Loop* NestedLoop = NestedAR->getLoop();
1808 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001809 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001810 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001811 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001812 // AddRecs require their operands be loop-invariant with respect to their
1813 // loops. Don't perform this transformation if it would break this
1814 // requirement.
1815 bool AllInvariant = true;
1816 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1817 if (!Operands[i]->isLoopInvariant(L)) {
1818 AllInvariant = false;
1819 break;
1820 }
1821 if (AllInvariant) {
1822 NestedOperands[0] = getAddRecExpr(Operands, L);
1823 AllInvariant = true;
1824 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1825 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1826 AllInvariant = false;
1827 break;
1828 }
1829 if (AllInvariant)
1830 // Ok, both add recurrences are valid after the transformation.
1831 return getAddRecExpr(NestedOperands, NestedLoop);
1832 }
1833 // Reset Operands to its original state.
1834 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001835 }
1836 }
1837
Dan Gohman1c343752009-06-27 21:21:31 +00001838 FoldingSetNodeID ID;
1839 ID.AddInteger(scAddRecExpr);
1840 ID.AddInteger(Operands.size());
1841 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1842 ID.AddPointer(Operands[i]);
1843 ID.AddPointer(L);
1844 void *IP = 0;
1845 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1846 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001847 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001848 UniqueSCEVs.InsertNode(S, IP);
1849 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001850}
1851
Dan Gohman9311ef62009-06-24 14:49:00 +00001852const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1853 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001854 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001855 Ops.push_back(LHS);
1856 Ops.push_back(RHS);
1857 return getSMaxExpr(Ops);
1858}
1859
Dan Gohman0bba49c2009-07-07 17:06:11 +00001860const SCEV *
1861ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001862 assert(!Ops.empty() && "Cannot get empty smax!");
1863 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001864#ifndef NDEBUG
1865 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1866 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1867 getEffectiveSCEVType(Ops[0]->getType()) &&
1868 "SCEVSMaxExpr operand types don't match!");
1869#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001870
1871 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001872 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001873
1874 // If there are any constants, fold them together.
1875 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001876 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001877 ++Idx;
1878 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001879 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001880 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001881 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001882 APIntOps::smax(LHSC->getValue()->getValue(),
1883 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001884 Ops[0] = getConstant(Fold);
1885 Ops.erase(Ops.begin()+1); // Erase the folded element
1886 if (Ops.size() == 1) return Ops[0];
1887 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001888 }
1889
Dan Gohmane5aceed2009-06-24 14:46:22 +00001890 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001891 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1892 Ops.erase(Ops.begin());
1893 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001894 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1895 // If we have an smax with a constant maximum-int, it will always be
1896 // maximum-int.
1897 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001898 }
1899 }
1900
1901 if (Ops.size() == 1) return Ops[0];
1902
1903 // Find the first SMax
1904 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1905 ++Idx;
1906
1907 // Check to see if one of the operands is an SMax. If so, expand its operands
1908 // onto our operand list, and recurse to simplify.
1909 if (Idx < Ops.size()) {
1910 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001911 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001912 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1913 Ops.erase(Ops.begin()+Idx);
1914 DeletedSMax = true;
1915 }
1916
1917 if (DeletedSMax)
1918 return getSMaxExpr(Ops);
1919 }
1920
1921 // Okay, check to see if the same value occurs in the operand list twice. If
1922 // so, delete one. Since we sorted the list, these values are required to
1923 // be adjacent.
1924 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1925 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1926 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1927 --i; --e;
1928 }
1929
1930 if (Ops.size() == 1) return Ops[0];
1931
1932 assert(!Ops.empty() && "Reduced smax down to nothing!");
1933
Nick Lewycky3e630762008-02-20 06:48:22 +00001934 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001935 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001936 FoldingSetNodeID ID;
1937 ID.AddInteger(scSMaxExpr);
1938 ID.AddInteger(Ops.size());
1939 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1940 ID.AddPointer(Ops[i]);
1941 void *IP = 0;
1942 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1943 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001944 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001945 UniqueSCEVs.InsertNode(S, IP);
1946 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001947}
1948
Dan Gohman9311ef62009-06-24 14:49:00 +00001949const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1950 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001951 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001952 Ops.push_back(LHS);
1953 Ops.push_back(RHS);
1954 return getUMaxExpr(Ops);
1955}
1956
Dan Gohman0bba49c2009-07-07 17:06:11 +00001957const SCEV *
1958ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001959 assert(!Ops.empty() && "Cannot get empty umax!");
1960 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001961#ifndef NDEBUG
1962 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1963 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1964 getEffectiveSCEVType(Ops[0]->getType()) &&
1965 "SCEVUMaxExpr operand types don't match!");
1966#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001967
1968 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001969 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001970
1971 // If there are any constants, fold them together.
1972 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001973 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001974 ++Idx;
1975 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001976 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001977 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001978 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00001979 APIntOps::umax(LHSC->getValue()->getValue(),
1980 RHSC->getValue()->getValue()));
1981 Ops[0] = getConstant(Fold);
1982 Ops.erase(Ops.begin()+1); // Erase the folded element
1983 if (Ops.size() == 1) return Ops[0];
1984 LHSC = cast<SCEVConstant>(Ops[0]);
1985 }
1986
Dan Gohmane5aceed2009-06-24 14:46:22 +00001987 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001988 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1989 Ops.erase(Ops.begin());
1990 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001991 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1992 // If we have an umax with a constant maximum-int, it will always be
1993 // maximum-int.
1994 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001995 }
1996 }
1997
1998 if (Ops.size() == 1) return Ops[0];
1999
2000 // Find the first UMax
2001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2002 ++Idx;
2003
2004 // Check to see if one of the operands is a UMax. If so, expand its operands
2005 // onto our operand list, and recurse to simplify.
2006 if (Idx < Ops.size()) {
2007 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002008 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002009 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2010 Ops.erase(Ops.begin()+Idx);
2011 DeletedUMax = true;
2012 }
2013
2014 if (DeletedUMax)
2015 return getUMaxExpr(Ops);
2016 }
2017
2018 // Okay, check to see if the same value occurs in the operand list twice. If
2019 // so, delete one. Since we sorted the list, these values are required to
2020 // be adjacent.
2021 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2022 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2023 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2024 --i; --e;
2025 }
2026
2027 if (Ops.size() == 1) return Ops[0];
2028
2029 assert(!Ops.empty() && "Reduced umax down to nothing!");
2030
2031 // Okay, it looks like we really DO need a umax expr. Check to see if we
2032 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002033 FoldingSetNodeID ID;
2034 ID.AddInteger(scUMaxExpr);
2035 ID.AddInteger(Ops.size());
2036 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2037 ID.AddPointer(Ops[i]);
2038 void *IP = 0;
2039 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2040 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002041 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002042 UniqueSCEVs.InsertNode(S, IP);
2043 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002044}
2045
Dan Gohman9311ef62009-06-24 14:49:00 +00002046const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2047 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002048 // ~smax(~x, ~y) == smin(x, y).
2049 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2050}
2051
Dan Gohman9311ef62009-06-24 14:49:00 +00002052const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2053 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002054 // ~umax(~x, ~y) == umin(x, y)
2055 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2056}
2057
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002058const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2059 unsigned FieldNo) {
2060 // If we have TargetData we can determine the constant offset.
2061 if (TD) {
2062 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2063 const StructLayout &SL = *TD->getStructLayout(STy);
2064 uint64_t Offset = SL.getElementOffset(FieldNo);
2065 return getIntegerSCEV(Offset, IntPtrTy);
2066 }
2067
2068 // Field 0 is always at offset 0.
2069 if (FieldNo == 0) {
2070 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2071 return getIntegerSCEV(0, Ty);
2072 }
2073
2074 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2075 // already have one, otherwise create a new one.
2076 FoldingSetNodeID ID;
2077 ID.AddInteger(scFieldOffset);
2078 ID.AddPointer(STy);
2079 ID.AddInteger(FieldNo);
2080 void *IP = 0;
2081 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2082 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2083 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2084 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2085 UniqueSCEVs.InsertNode(S, IP);
2086 return S;
2087}
2088
2089const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2090 // If we have TargetData we can determine the constant size.
2091 if (TD && AllocTy->isSized()) {
2092 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2093 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2094 }
2095
2096 // Expand an array size into the element size times the number
2097 // of elements.
2098 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2099 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2100 return getMulExpr(
2101 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2102 ATy->getNumElements())));
2103 }
2104
2105 // Expand a vector size into the element size times the number
2106 // of elements.
2107 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2108 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2109 return getMulExpr(
2110 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2111 VTy->getNumElements())));
2112 }
2113
2114 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2115 // already have one, otherwise create a new one.
2116 FoldingSetNodeID ID;
2117 ID.AddInteger(scAllocSize);
2118 ID.AddPointer(AllocTy);
2119 void *IP = 0;
2120 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2121 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2122 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2123 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2124 UniqueSCEVs.InsertNode(S, IP);
2125 return S;
2126}
2127
Dan Gohman0bba49c2009-07-07 17:06:11 +00002128const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002129 // Don't attempt to do anything other than create a SCEVUnknown object
2130 // here. createSCEV only calls getUnknown after checking for all other
2131 // interesting possibilities, and any other code that calls getUnknown
2132 // is doing so in order to hide a value from SCEV canonicalization.
2133
Dan Gohman1c343752009-06-27 21:21:31 +00002134 FoldingSetNodeID ID;
2135 ID.AddInteger(scUnknown);
2136 ID.AddPointer(V);
2137 void *IP = 0;
2138 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2139 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002140 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002141 UniqueSCEVs.InsertNode(S, IP);
2142 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002143}
2144
Chris Lattner53e677a2004-04-02 20:23:17 +00002145//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002146// Basic SCEV Analysis and PHI Idiom Recognition Code
2147//
2148
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002149/// isSCEVable - Test if values of the given type are analyzable within
2150/// the SCEV framework. This primarily includes integer types, and it
2151/// can optionally include pointer types if the ScalarEvolution class
2152/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002153bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002154 // Integers and pointers are always SCEVable.
2155 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002156}
2157
2158/// getTypeSizeInBits - Return the size in bits of the specified type,
2159/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002160uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002161 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2162
2163 // If we have a TargetData, use it!
2164 if (TD)
2165 return TD->getTypeSizeInBits(Ty);
2166
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002167 // Integer types have fixed sizes.
2168 if (Ty->isInteger())
2169 return Ty->getPrimitiveSizeInBits();
2170
2171 // The only other support type is pointer. Without TargetData, conservatively
2172 // assume pointers are 64-bit.
2173 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2174 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002175}
2176
2177/// getEffectiveSCEVType - Return a type with the same bitwidth as
2178/// the given type and which represents how SCEV will treat the given
2179/// type, for which isSCEVable must return true. For pointer types,
2180/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002181const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002182 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2183
2184 if (Ty->isInteger())
2185 return Ty;
2186
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002187 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002188 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002189 if (TD) return TD->getIntPtrType(getContext());
2190
2191 // Without TargetData, conservatively assume pointers are 64-bit.
2192 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002193}
Chris Lattner53e677a2004-04-02 20:23:17 +00002194
Dan Gohman0bba49c2009-07-07 17:06:11 +00002195const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002196 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002197}
2198
Chris Lattner53e677a2004-04-02 20:23:17 +00002199/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2200/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002201const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002202 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002203
Dan Gohman0bba49c2009-07-07 17:06:11 +00002204 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002205 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002206 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002207 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002208 return S;
2209}
2210
Dan Gohman6bbcba12009-06-24 00:54:57 +00002211/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002212/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002213const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002214 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002215 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002216}
2217
2218/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2219///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002220const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002221 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002222 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002223 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002224
2225 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002226 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002227 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002228 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002229}
2230
2231/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002232const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002233 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002234 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002235 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002236
2237 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002238 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002239 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002240 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002241 return getMinusSCEV(AllOnes, V);
2242}
2243
2244/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2245///
Dan Gohman9311ef62009-06-24 14:49:00 +00002246const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2247 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002248 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002249 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002250}
2251
2252/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2253/// input value to the specified type. If the type must be extended, it is zero
2254/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002255const SCEV *
2256ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002257 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002258 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002259 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2260 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002261 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002262 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002263 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002264 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002265 return getTruncateExpr(V, Ty);
2266 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002267}
2268
2269/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2270/// input value to the specified type. If the type must be extended, it is sign
2271/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002272const SCEV *
2273ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002274 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002275 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002276 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2277 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002278 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002279 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002280 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002281 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002282 return getTruncateExpr(V, Ty);
2283 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002284}
2285
Dan Gohman467c4302009-05-13 03:46:30 +00002286/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2287/// input value to the specified type. If the type must be extended, it is zero
2288/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002289const SCEV *
2290ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002291 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002292 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2293 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002294 "Cannot noop or zero extend with non-integer arguments!");
2295 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2296 "getNoopOrZeroExtend cannot truncate!");
2297 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2298 return V; // No conversion
2299 return getZeroExtendExpr(V, Ty);
2300}
2301
2302/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2303/// input value to the specified type. If the type must be extended, it is sign
2304/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002305const SCEV *
2306ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002307 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002308 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2309 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002310 "Cannot noop or sign extend with non-integer arguments!");
2311 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2312 "getNoopOrSignExtend cannot truncate!");
2313 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2314 return V; // No conversion
2315 return getSignExtendExpr(V, Ty);
2316}
2317
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002318/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2319/// the input value to the specified type. If the type must be extended,
2320/// it is extended with unspecified bits. The conversion must not be
2321/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002322const SCEV *
2323ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002324 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002325 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2326 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002327 "Cannot noop or any extend with non-integer arguments!");
2328 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2329 "getNoopOrAnyExtend cannot truncate!");
2330 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2331 return V; // No conversion
2332 return getAnyExtendExpr(V, Ty);
2333}
2334
Dan Gohman467c4302009-05-13 03:46:30 +00002335/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2336/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002337const SCEV *
2338ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002339 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002340 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2341 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002342 "Cannot truncate or noop with non-integer arguments!");
2343 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2344 "getTruncateOrNoop cannot extend!");
2345 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2346 return V; // No conversion
2347 return getTruncateExpr(V, Ty);
2348}
2349
Dan Gohmana334aa72009-06-22 00:31:57 +00002350/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2351/// the types using zero-extension, and then perform a umax operation
2352/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002353const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2354 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002355 const SCEV *PromotedLHS = LHS;
2356 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002357
2358 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2359 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2360 else
2361 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2362
2363 return getUMaxExpr(PromotedLHS, PromotedRHS);
2364}
2365
Dan Gohmanc9759e82009-06-22 15:03:27 +00002366/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2367/// the types using zero-extension, and then perform a umin operation
2368/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002369const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2370 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002371 const SCEV *PromotedLHS = LHS;
2372 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002373
2374 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2375 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2376 else
2377 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2378
2379 return getUMinExpr(PromotedLHS, PromotedRHS);
2380}
2381
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002382/// PushDefUseChildren - Push users of the given Instruction
2383/// onto the given Worklist.
2384static void
2385PushDefUseChildren(Instruction *I,
2386 SmallVectorImpl<Instruction *> &Worklist) {
2387 // Push the def-use children onto the Worklist stack.
2388 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2389 UI != UE; ++UI)
2390 Worklist.push_back(cast<Instruction>(UI));
2391}
2392
2393/// ForgetSymbolicValue - This looks up computed SCEV values for all
2394/// instructions that depend on the given instruction and removes them from
2395/// the Scalars map if they reference SymName. This is used during PHI
2396/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002397void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002398ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2399 SmallVector<Instruction *, 16> Worklist;
2400 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002401
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002402 SmallPtrSet<Instruction *, 8> Visited;
2403 Visited.insert(I);
2404 while (!Worklist.empty()) {
2405 Instruction *I = Worklist.pop_back_val();
2406 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002407
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002408 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2409 Scalars.find(static_cast<Value *>(I));
2410 if (It != Scalars.end()) {
2411 // Short-circuit the def-use traversal if the symbolic name
2412 // ceases to appear in expressions.
2413 if (!It->second->hasOperand(SymName))
2414 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002415
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002416 // SCEVUnknown for a PHI either means that it has an unrecognized
2417 // structure, or it's a PHI that's in the progress of being computed
2418 // by createNodeForPHI. In the former case, additional loop trip
2419 // count information isn't going to change anything. In the later
2420 // case, createNodeForPHI will perform the necessary updates on its
2421 // own when it gets to that point.
2422 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2423 Scalars.erase(It);
2424 ValuesAtScopes.erase(I);
2425 }
2426
2427 PushDefUseChildren(I, Worklist);
2428 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002429}
Chris Lattner53e677a2004-04-02 20:23:17 +00002430
2431/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2432/// a loop header, making it a potential recurrence, or it doesn't.
2433///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002434const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002435 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002436 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002437 if (L->getHeader() == PN->getParent()) {
2438 // If it lives in the loop header, it has two incoming values, one
2439 // from outside the loop, and one from inside.
2440 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2441 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002442
Chris Lattner53e677a2004-04-02 20:23:17 +00002443 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002444 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002445 assert(Scalars.find(PN) == Scalars.end() &&
2446 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002447 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002448
2449 // Using this symbolic name for the PHI, analyze the value coming around
2450 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002451 Value *BEValueV = PN->getIncomingValue(BackEdge);
2452 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002453
2454 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2455 // has a special value for the first iteration of the loop.
2456
2457 // If the value coming around the backedge is an add with the symbolic
2458 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002459 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002460 // If there is a single occurrence of the symbolic value, replace it
2461 // with a recurrence.
2462 unsigned FoundIndex = Add->getNumOperands();
2463 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2464 if (Add->getOperand(i) == SymbolicName)
2465 if (FoundIndex == e) {
2466 FoundIndex = i;
2467 break;
2468 }
2469
2470 if (FoundIndex != Add->getNumOperands()) {
2471 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002472 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002473 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2474 if (i != FoundIndex)
2475 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002476 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002477
2478 // This is not a valid addrec if the step amount is varying each
2479 // loop iteration, but is not itself an addrec in this loop.
2480 if (Accum->isLoopInvariant(L) ||
2481 (isa<SCEVAddRecExpr>(Accum) &&
2482 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002483 const SCEV *StartVal =
2484 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmaneb490a72009-07-25 01:22:26 +00002485 const SCEVAddRecExpr *PHISCEV =
2486 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2487
2488 // If the increment doesn't overflow, then neither the addrec nor the
2489 // post-increment will overflow.
2490 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2491 if (OBO->getOperand(0) == PN &&
2492 getSCEV(OBO->getOperand(1)) ==
2493 PHISCEV->getStepRecurrence(*this)) {
2494 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
Dan Gohman5078f842009-08-20 17:11:38 +00002495 if (OBO->hasNoUnsignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002496 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002497 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002498 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002499 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002500 }
Dan Gohman5078f842009-08-20 17:11:38 +00002501 if (OBO->hasNoSignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002502 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002503 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002504 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002505 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002506 }
2507 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002508
2509 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002510 // to be symbolic. We now need to go back and purge all of the
2511 // entries for the scalars that use the symbolic expression.
2512 ForgetSymbolicName(PN, SymbolicName);
2513 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002514 return PHISCEV;
2515 }
2516 }
Dan Gohman622ed672009-05-04 22:02:23 +00002517 } else if (const SCEVAddRecExpr *AddRec =
2518 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002519 // Otherwise, this could be a loop like this:
2520 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2521 // In this case, j = {1,+,1} and BEValue is j.
2522 // Because the other in-value of i (0) fits the evolution of BEValue
2523 // i really is an addrec evolution.
2524 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002525 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002526
2527 // If StartVal = j.start - j.stride, we can use StartVal as the
2528 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002529 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002530 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002531 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002532 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002533
2534 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002535 // to be symbolic. We now need to go back and purge all of the
2536 // entries for the scalars that use the symbolic expression.
2537 ForgetSymbolicName(PN, SymbolicName);
2538 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002539 return PHISCEV;
2540 }
2541 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002542 }
2543
2544 return SymbolicName;
2545 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002546
Dan Gohmana653fc52009-07-14 14:06:25 +00002547 // It's tempting to recognize PHIs with a unique incoming value, however
2548 // this leads passes like indvars to break LCSSA form. Fortunately, such
2549 // PHIs are rare, as instcombine zaps them.
2550
Chris Lattner53e677a2004-04-02 20:23:17 +00002551 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002552 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002553}
2554
Dan Gohman26466c02009-05-08 20:26:55 +00002555/// createNodeForGEP - Expand GEP instructions into add and multiply
2556/// operations. This allows them to be analyzed by regular SCEV code.
2557///
Dan Gohmanca178902009-07-17 20:47:02 +00002558const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002559
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002560 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002561 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002562 // Don't attempt to analyze GEPs over unsized objects.
2563 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2564 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002565 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002566 gep_type_iterator GTI = gep_type_begin(GEP);
2567 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2568 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002569 I != E; ++I) {
2570 Value *Index = *I;
2571 // Compute the (potentially symbolic) offset in bytes for this index.
2572 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2573 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002574 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002575 TotalOffset = getAddExpr(TotalOffset,
2576 getFieldOffsetExpr(STy, FieldNo));
Dan Gohman26466c02009-05-08 20:26:55 +00002577 } else {
2578 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002579 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002580 if (!isa<PointerType>(LocalOffset->getType()))
2581 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002582 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002583 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI));
Dan Gohman26466c02009-05-08 20:26:55 +00002584 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2585 }
2586 }
2587 return getAddExpr(getSCEV(Base), TotalOffset);
2588}
2589
Nick Lewycky83bb0052007-11-22 07:59:40 +00002590/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2591/// guaranteed to end in (at every loop iteration). It is, at the same time,
2592/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2593/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002594uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002595ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002596 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002597 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002598
Dan Gohman622ed672009-05-04 22:02:23 +00002599 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002600 return std::min(GetMinTrailingZeros(T->getOperand()),
2601 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002602
Dan Gohman622ed672009-05-04 22:02:23 +00002603 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002604 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2605 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2606 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002607 }
2608
Dan Gohman622ed672009-05-04 22:02:23 +00002609 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002610 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2611 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2612 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002613 }
2614
Dan Gohman622ed672009-05-04 22:02:23 +00002615 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002616 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002617 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002618 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002619 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002620 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002621 }
2622
Dan Gohman622ed672009-05-04 22:02:23 +00002623 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002624 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002625 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2626 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002627 for (unsigned i = 1, e = M->getNumOperands();
2628 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002629 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002630 BitWidth);
2631 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002632 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002633
Dan Gohman622ed672009-05-04 22:02:23 +00002634 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002635 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002636 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002637 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002638 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002639 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002640 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002641
Dan Gohman622ed672009-05-04 22:02:23 +00002642 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002643 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002644 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002645 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002646 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002647 return MinOpRes;
2648 }
2649
Dan Gohman622ed672009-05-04 22:02:23 +00002650 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002651 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002652 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002653 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002654 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002655 return MinOpRes;
2656 }
2657
Dan Gohman2c364ad2009-06-19 23:29:04 +00002658 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2659 // For a SCEVUnknown, ask ValueTracking.
2660 unsigned BitWidth = getTypeSizeInBits(U->getType());
2661 APInt Mask = APInt::getAllOnesValue(BitWidth);
2662 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2663 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2664 return Zeros.countTrailingOnes();
2665 }
2666
2667 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002668 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002669}
Chris Lattner53e677a2004-04-02 20:23:17 +00002670
Dan Gohman85b05a22009-07-13 21:35:55 +00002671/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2672///
2673ConstantRange
2674ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002675
2676 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002677 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002678
Dan Gohman85b05a22009-07-13 21:35:55 +00002679 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2680 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2681 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2682 X = X.add(getUnsignedRange(Add->getOperand(i)));
2683 return X;
2684 }
2685
2686 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2687 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2688 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2689 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2690 return X;
2691 }
2692
2693 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2694 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2695 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2696 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2697 return X;
2698 }
2699
2700 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2701 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2702 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2703 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2704 return X;
2705 }
2706
2707 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2708 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2709 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2710 return X.udiv(Y);
2711 }
2712
2713 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2714 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2715 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2716 }
2717
2718 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2719 ConstantRange X = getUnsignedRange(SExt->getOperand());
2720 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2721 }
2722
2723 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2724 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2725 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2726 }
2727
2728 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2729
2730 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2731 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2732 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2733 if (!Trip) return FullSet;
2734
2735 // TODO: non-affine addrec
2736 if (AddRec->isAffine()) {
2737 const Type *Ty = AddRec->getType();
2738 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2739 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2740 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2741
2742 const SCEV *Start = AddRec->getStart();
Dan Gohmana16b5762009-07-21 00:42:47 +00002743 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002744 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2745
2746 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002747 // TODO: This is very conservative.
2748 if (!(Step->isOne() &&
2749 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2750 !(Step->isAllOnesValue() &&
2751 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
Dan Gohman85b05a22009-07-13 21:35:55 +00002752 return FullSet;
2753
2754 ConstantRange StartRange = getUnsignedRange(Start);
2755 ConstantRange EndRange = getUnsignedRange(End);
2756 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2757 EndRange.getUnsignedMin());
2758 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2759 EndRange.getUnsignedMax());
2760 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman0d5bae42009-07-20 22:41:51 +00002761 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002762 return ConstantRange(Min, Max+1);
2763 }
2764 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002765 }
2766
2767 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2768 // For a SCEVUnknown, ask ValueTracking.
2769 unsigned BitWidth = getTypeSizeInBits(U->getType());
2770 APInt Mask = APInt::getAllOnesValue(BitWidth);
2771 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2772 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002773 if (Ones == ~Zeros + 1)
2774 return FullSet;
2775 return ConstantRange(Ones, ~Zeros + 1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002776 }
2777
Dan Gohman85b05a22009-07-13 21:35:55 +00002778 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002779}
2780
Dan Gohman85b05a22009-07-13 21:35:55 +00002781/// getSignedRange - Determine the signed range for a particular SCEV.
2782///
2783ConstantRange
2784ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002785
Dan Gohman85b05a22009-07-13 21:35:55 +00002786 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2787 return ConstantRange(C->getValue()->getValue());
2788
2789 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2790 ConstantRange X = getSignedRange(Add->getOperand(0));
2791 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2792 X = X.add(getSignedRange(Add->getOperand(i)));
2793 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002794 }
2795
Dan Gohman85b05a22009-07-13 21:35:55 +00002796 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2797 ConstantRange X = getSignedRange(Mul->getOperand(0));
2798 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2799 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2800 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002801 }
2802
Dan Gohman85b05a22009-07-13 21:35:55 +00002803 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2804 ConstantRange X = getSignedRange(SMax->getOperand(0));
2805 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2806 X = X.smax(getSignedRange(SMax->getOperand(i)));
2807 return X;
2808 }
Dan Gohman62849c02009-06-24 01:05:09 +00002809
Dan Gohman85b05a22009-07-13 21:35:55 +00002810 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2811 ConstantRange X = getSignedRange(UMax->getOperand(0));
2812 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2813 X = X.umax(getSignedRange(UMax->getOperand(i)));
2814 return X;
2815 }
Dan Gohman62849c02009-06-24 01:05:09 +00002816
Dan Gohman85b05a22009-07-13 21:35:55 +00002817 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2818 ConstantRange X = getSignedRange(UDiv->getLHS());
2819 ConstantRange Y = getSignedRange(UDiv->getRHS());
2820 return X.udiv(Y);
2821 }
Dan Gohman62849c02009-06-24 01:05:09 +00002822
Dan Gohman85b05a22009-07-13 21:35:55 +00002823 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2824 ConstantRange X = getSignedRange(ZExt->getOperand());
2825 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2826 }
2827
2828 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2829 ConstantRange X = getSignedRange(SExt->getOperand());
2830 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2831 }
2832
2833 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2834 ConstantRange X = getSignedRange(Trunc->getOperand());
2835 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2836 }
2837
2838 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2839
2840 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2841 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2842 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2843 if (!Trip) return FullSet;
2844
2845 // TODO: non-affine addrec
2846 if (AddRec->isAffine()) {
2847 const Type *Ty = AddRec->getType();
2848 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2849 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2850 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2851
2852 const SCEV *Start = AddRec->getStart();
2853 const SCEV *Step = AddRec->getStepRecurrence(*this);
2854 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2855
2856 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002857 // TODO: This is very conservative.
2858 if (!(Step->isOne() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002859 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
Dan Gohmana16b5762009-07-21 00:42:47 +00002860 !(Step->isAllOnesValue() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002861 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2862 return FullSet;
2863
2864 ConstantRange StartRange = getSignedRange(Start);
2865 ConstantRange EndRange = getSignedRange(End);
2866 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2867 EndRange.getSignedMin());
2868 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2869 EndRange.getSignedMax());
2870 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmanc268e7c2009-07-21 00:37:45 +00002871 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002872 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002873 }
Dan Gohman62849c02009-06-24 01:05:09 +00002874 }
Dan Gohman62849c02009-06-24 01:05:09 +00002875 }
2876
Dan Gohman2c364ad2009-06-19 23:29:04 +00002877 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2878 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002879 unsigned BitWidth = getTypeSizeInBits(U->getType());
2880 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2881 if (NS == 1)
2882 return FullSet;
2883 return
2884 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2885 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002886 }
2887
Dan Gohman85b05a22009-07-13 21:35:55 +00002888 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002889}
2890
Chris Lattner53e677a2004-04-02 20:23:17 +00002891/// createSCEV - We know that there is no SCEV for the specified value.
2892/// Analyze the expression.
2893///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002894const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002895 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002896 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002897
Dan Gohman6c459a22008-06-22 19:56:46 +00002898 unsigned Opcode = Instruction::UserOp1;
2899 if (Instruction *I = dyn_cast<Instruction>(V))
2900 Opcode = I->getOpcode();
2901 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2902 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002903 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2904 return getConstant(CI);
2905 else if (isa<ConstantPointerNull>(V))
2906 return getIntegerSCEV(0, V->getType());
2907 else if (isa<UndefValue>(V))
2908 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002909 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002910 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002911
Dan Gohmanca178902009-07-17 20:47:02 +00002912 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00002913 switch (Opcode) {
2914 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002915 return getAddExpr(getSCEV(U->getOperand(0)),
2916 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002917 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002918 return getMulExpr(getSCEV(U->getOperand(0)),
2919 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002920 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002921 return getUDivExpr(getSCEV(U->getOperand(0)),
2922 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002923 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002924 return getMinusSCEV(getSCEV(U->getOperand(0)),
2925 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002926 case Instruction::And:
2927 // For an expression like x&255 that merely masks off the high bits,
2928 // use zext(trunc(x)) as the SCEV expression.
2929 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002930 if (CI->isNullValue())
2931 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002932 if (CI->isAllOnesValue())
2933 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002934 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002935
2936 // Instcombine's ShrinkDemandedConstant may strip bits out of
2937 // constants, obscuring what would otherwise be a low-bits mask.
2938 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2939 // knew about to reconstruct a low-bits mask value.
2940 unsigned LZ = A.countLeadingZeros();
2941 unsigned BitWidth = A.getBitWidth();
2942 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2943 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2944 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2945
2946 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2947
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002948 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002949 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002950 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00002951 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002952 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002953 }
2954 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002955
Dan Gohman6c459a22008-06-22 19:56:46 +00002956 case Instruction::Or:
2957 // If the RHS of the Or is a constant, we may have something like:
2958 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2959 // optimizations will transparently handle this case.
2960 //
2961 // In order for this transformation to be safe, the LHS must be of the
2962 // form X*(2^n) and the Or constant must be less than 2^n.
2963 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002964 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002965 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002966 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002967 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002968 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002969 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002970 break;
2971 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002972 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002973 // If the RHS of the xor is a signbit, then this is just an add.
2974 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002975 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002976 return getAddExpr(getSCEV(U->getOperand(0)),
2977 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002978
2979 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002980 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002981 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002982
2983 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2984 // This is a variant of the check for xor with -1, and it handles
2985 // the case where instcombine has trimmed non-demanded bits out
2986 // of an xor with -1.
2987 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2988 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2989 if (BO->getOpcode() == Instruction::And &&
2990 LCI->getValue() == CI->getValue())
2991 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002992 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002993 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002994 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002995 const Type *Z0Ty = Z0->getType();
2996 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2997
2998 // If C is a low-bits mask, the zero extend is zerving to
2999 // mask off the high bits. Complement the operand and
3000 // re-apply the zext.
3001 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3002 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3003
3004 // If C is a single bit, it may be in the sign-bit position
3005 // before the zero-extend. In this case, represent the xor
3006 // using an add, which is equivalent, and re-apply the zext.
3007 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3008 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3009 Trunc.isSignBit())
3010 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3011 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003012 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003013 }
3014 break;
3015
3016 case Instruction::Shl:
3017 // Turn shift left of a constant amount into a multiply.
3018 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3019 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003020 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003021 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003022 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003023 }
3024 break;
3025
Nick Lewycky01eaf802008-07-07 06:15:49 +00003026 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003027 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003028 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3029 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003030 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003031 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003032 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003033 }
3034 break;
3035
Dan Gohman4ee29af2009-04-21 02:26:00 +00003036 case Instruction::AShr:
3037 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3038 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3039 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3040 if (L->getOpcode() == Instruction::Shl &&
3041 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003042 unsigned BitWidth = getTypeSizeInBits(U->getType());
3043 uint64_t Amt = BitWidth - CI->getZExtValue();
3044 if (Amt == BitWidth)
3045 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3046 if (Amt > BitWidth)
3047 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003048 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003049 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003050 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003051 U->getType());
3052 }
3053 break;
3054
Dan Gohman6c459a22008-06-22 19:56:46 +00003055 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003056 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003057
3058 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003059 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003060
3061 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003062 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003063
3064 case Instruction::BitCast:
3065 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003066 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003067 return getSCEV(U->getOperand(0));
3068 break;
3069
Dan Gohmanf2411742009-07-20 17:43:30 +00003070 // It's tempting to handle inttoptr and ptrtoint, however this can
3071 // lead to pointer expressions which cannot be expanded to GEPs
3072 // (because they may overflow). For now, the only pointer-typed
3073 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00003074
Dan Gohman26466c02009-05-08 20:26:55 +00003075 case Instruction::GetElementPtr:
Dan Gohmanfb791602009-05-08 20:58:38 +00003076 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00003077
Dan Gohman6c459a22008-06-22 19:56:46 +00003078 case Instruction::PHI:
3079 return createNodeForPHI(cast<PHINode>(U));
3080
3081 case Instruction::Select:
3082 // This could be a smax or umax that was lowered earlier.
3083 // Try to recover it.
3084 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3085 Value *LHS = ICI->getOperand(0);
3086 Value *RHS = ICI->getOperand(1);
3087 switch (ICI->getPredicate()) {
3088 case ICmpInst::ICMP_SLT:
3089 case ICmpInst::ICMP_SLE:
3090 std::swap(LHS, RHS);
3091 // fall through
3092 case ICmpInst::ICMP_SGT:
3093 case ICmpInst::ICMP_SGE:
3094 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003095 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003096 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003097 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003098 break;
3099 case ICmpInst::ICMP_ULT:
3100 case ICmpInst::ICMP_ULE:
3101 std::swap(LHS, RHS);
3102 // fall through
3103 case ICmpInst::ICMP_UGT:
3104 case ICmpInst::ICMP_UGE:
3105 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003106 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003107 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003108 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003109 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003110 case ICmpInst::ICMP_NE:
3111 // n != 0 ? n : 1 -> umax(n, 1)
3112 if (LHS == U->getOperand(1) &&
3113 isa<ConstantInt>(U->getOperand(2)) &&
3114 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3115 isa<ConstantInt>(RHS) &&
3116 cast<ConstantInt>(RHS)->isZero())
3117 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3118 break;
3119 case ICmpInst::ICMP_EQ:
3120 // n == 0 ? 1 : n -> umax(n, 1)
3121 if (LHS == U->getOperand(2) &&
3122 isa<ConstantInt>(U->getOperand(1)) &&
3123 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3124 isa<ConstantInt>(RHS) &&
3125 cast<ConstantInt>(RHS)->isZero())
3126 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3127 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003128 default:
3129 break;
3130 }
3131 }
3132
3133 default: // We cannot analyze this expression.
3134 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003135 }
3136
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003137 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003138}
3139
3140
3141
3142//===----------------------------------------------------------------------===//
3143// Iteration Count Computation Code
3144//
3145
Dan Gohman46bdfb02009-02-24 18:55:53 +00003146/// getBackedgeTakenCount - If the specified loop has a predictable
3147/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3148/// object. The backedge-taken count is the number of times the loop header
3149/// will be branched to from within the loop. This is one less than the
3150/// trip count of the loop, since it doesn't count the first iteration,
3151/// when the header is branched to from outside the loop.
3152///
3153/// Note that it is not valid to call this method on a loop without a
3154/// loop-invariant backedge-taken count (see
3155/// hasLoopInvariantBackedgeTakenCount).
3156///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003157const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003158 return getBackedgeTakenInfo(L).Exact;
3159}
3160
3161/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3162/// return the least SCEV value that is known never to be less than the
3163/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003164const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003165 return getBackedgeTakenInfo(L).Max;
3166}
3167
Dan Gohman59ae6b92009-07-08 19:23:34 +00003168/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3169/// onto the given Worklist.
3170static void
3171PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3172 BasicBlock *Header = L->getHeader();
3173
3174 // Push all Loop-header PHIs onto the Worklist stack.
3175 for (BasicBlock::iterator I = Header->begin();
3176 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3177 Worklist.push_back(PN);
3178}
3179
Dan Gohmana1af7572009-04-30 20:47:05 +00003180const ScalarEvolution::BackedgeTakenInfo &
3181ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003182 // Initially insert a CouldNotCompute for this loop. If the insertion
3183 // succeeds, procede to actually compute a backedge-taken count and
3184 // update the value. The temporary CouldNotCompute value tells SCEV
3185 // code elsewhere that it shouldn't attempt to request a new
3186 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003187 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003188 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3189 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003190 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003191 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003192 assert(ItCount.Exact->isLoopInvariant(L) &&
3193 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003194 "Computed trip count isn't loop invariant for loop!");
3195 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003196
Dan Gohman01ecca22009-04-27 20:16:15 +00003197 // Update the value in the map.
3198 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003199 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003200 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003201 // Update the value in the map.
3202 Pair.first->second = ItCount;
3203 if (isa<PHINode>(L->getHeader()->begin()))
3204 // Only count loops that have phi nodes as not being computable.
3205 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003206 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003207
3208 // Now that we know more about the trip count for this loop, forget any
3209 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003210 // conservative estimates made without the benefit of trip count
3211 // information. This is similar to the code in
3212 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3213 // nodes specially.
3214 if (ItCount.hasAnyInfo()) {
3215 SmallVector<Instruction *, 16> Worklist;
3216 PushLoopPHIs(L, Worklist);
3217
3218 SmallPtrSet<Instruction *, 8> Visited;
3219 while (!Worklist.empty()) {
3220 Instruction *I = Worklist.pop_back_val();
3221 if (!Visited.insert(I)) continue;
3222
3223 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3224 Scalars.find(static_cast<Value *>(I));
3225 if (It != Scalars.end()) {
3226 // SCEVUnknown for a PHI either means that it has an unrecognized
3227 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003228 // by createNodeForPHI. In the former case, additional loop trip
3229 // count information isn't going to change anything. In the later
3230 // case, createNodeForPHI will perform the necessary updates on its
3231 // own when it gets to that point.
Dan Gohman59ae6b92009-07-08 19:23:34 +00003232 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3233 Scalars.erase(It);
3234 ValuesAtScopes.erase(I);
3235 if (PHINode *PN = dyn_cast<PHINode>(I))
3236 ConstantEvolutionLoopExitValue.erase(PN);
3237 }
3238
3239 PushDefUseChildren(I, Worklist);
3240 }
3241 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003242 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003243 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003244}
3245
Dan Gohman46bdfb02009-02-24 18:55:53 +00003246/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003247/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003248/// ScalarEvolution's ability to compute a trip count, or if the loop
3249/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003250void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003251 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003252
Dan Gohman35738ac2009-05-04 22:30:44 +00003253 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003254 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003255
Dan Gohman59ae6b92009-07-08 19:23:34 +00003256 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003257 while (!Worklist.empty()) {
3258 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003259 if (!Visited.insert(I)) continue;
3260
3261 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3262 Scalars.find(static_cast<Value *>(I));
3263 if (It != Scalars.end()) {
3264 Scalars.erase(It);
3265 ValuesAtScopes.erase(I);
3266 if (PHINode *PN = dyn_cast<PHINode>(I))
3267 ConstantEvolutionLoopExitValue.erase(PN);
3268 }
3269
3270 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003271 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003272}
3273
Dan Gohman46bdfb02009-02-24 18:55:53 +00003274/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3275/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003276ScalarEvolution::BackedgeTakenInfo
3277ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003278 SmallVector<BasicBlock*, 8> ExitingBlocks;
3279 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003280
Dan Gohmana334aa72009-06-22 00:31:57 +00003281 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003282 const SCEV *BECount = getCouldNotCompute();
3283 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003284 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003285 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3286 BackedgeTakenInfo NewBTI =
3287 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003288
Dan Gohman1c343752009-06-27 21:21:31 +00003289 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003290 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003291 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003292 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003293 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003294 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003295 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003296 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003297 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003298 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003299 }
Dan Gohman1c343752009-06-27 21:21:31 +00003300 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003301 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003302 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003303 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003304 }
3305
3306 return BackedgeTakenInfo(BECount, MaxBECount);
3307}
3308
3309/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3310/// of the specified loop will execute if it exits via the specified block.
3311ScalarEvolution::BackedgeTakenInfo
3312ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3313 BasicBlock *ExitingBlock) {
3314
3315 // Okay, we've chosen an exiting block. See what condition causes us to
3316 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003317 //
3318 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003319 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003320 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003321 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003322
Chris Lattner8b0e3602007-01-07 02:24:26 +00003323 // At this point, we know we have a conditional branch that determines whether
3324 // the loop is exited. However, we don't know if the branch is executed each
3325 // time through the loop. If not, then the execution count of the branch will
3326 // not be equal to the trip count of the loop.
3327 //
3328 // Currently we check for this by checking to see if the Exit branch goes to
3329 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003330 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003331 // loop header. This is common for un-rotated loops.
3332 //
3333 // If both of those tests fail, walk up the unique predecessor chain to the
3334 // header, stopping if there is an edge that doesn't exit the loop. If the
3335 // header is reached, the execution count of the branch will be equal to the
3336 // trip count of the loop.
3337 //
3338 // More extensive analysis could be done to handle more cases here.
3339 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003340 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003341 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003342 ExitBr->getParent() != L->getHeader()) {
3343 // The simple checks failed, try climbing the unique predecessor chain
3344 // up to the header.
3345 bool Ok = false;
3346 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3347 BasicBlock *Pred = BB->getUniquePredecessor();
3348 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003349 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003350 TerminatorInst *PredTerm = Pred->getTerminator();
3351 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3352 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3353 if (PredSucc == BB)
3354 continue;
3355 // If the predecessor has a successor that isn't BB and isn't
3356 // outside the loop, assume the worst.
3357 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003358 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003359 }
3360 if (Pred == L->getHeader()) {
3361 Ok = true;
3362 break;
3363 }
3364 BB = Pred;
3365 }
3366 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003367 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003368 }
3369
3370 // Procede to the next level to examine the exit condition expression.
3371 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3372 ExitBr->getSuccessor(0),
3373 ExitBr->getSuccessor(1));
3374}
3375
3376/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3377/// backedge of the specified loop will execute if its exit condition
3378/// were a conditional branch of ExitCond, TBB, and FBB.
3379ScalarEvolution::BackedgeTakenInfo
3380ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3381 Value *ExitCond,
3382 BasicBlock *TBB,
3383 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003384 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003385 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3386 if (BO->getOpcode() == Instruction::And) {
3387 // Recurse on the operands of the and.
3388 BackedgeTakenInfo BTI0 =
3389 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3390 BackedgeTakenInfo BTI1 =
3391 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003392 const SCEV *BECount = getCouldNotCompute();
3393 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003394 if (L->contains(TBB)) {
3395 // Both conditions must be true for the loop to continue executing.
3396 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003397 if (BTI0.Exact == getCouldNotCompute() ||
3398 BTI1.Exact == getCouldNotCompute())
3399 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003400 else
3401 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003402 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003403 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003404 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003405 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003406 else
3407 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003408 } else {
3409 // Both conditions must be true for the loop to exit.
3410 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003411 if (BTI0.Exact != getCouldNotCompute() &&
3412 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003413 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003414 if (BTI0.Max != getCouldNotCompute() &&
3415 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003416 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3417 }
3418
3419 return BackedgeTakenInfo(BECount, MaxBECount);
3420 }
3421 if (BO->getOpcode() == Instruction::Or) {
3422 // Recurse on the operands of the or.
3423 BackedgeTakenInfo BTI0 =
3424 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3425 BackedgeTakenInfo BTI1 =
3426 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003427 const SCEV *BECount = getCouldNotCompute();
3428 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003429 if (L->contains(FBB)) {
3430 // Both conditions must be false for the loop to continue executing.
3431 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003432 if (BTI0.Exact == getCouldNotCompute() ||
3433 BTI1.Exact == getCouldNotCompute())
3434 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003435 else
3436 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003437 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003438 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003439 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003440 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003441 else
3442 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003443 } else {
3444 // Both conditions must be false for the loop to exit.
3445 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003446 if (BTI0.Exact != getCouldNotCompute() &&
3447 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003448 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003449 if (BTI0.Max != getCouldNotCompute() &&
3450 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003451 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3452 }
3453
3454 return BackedgeTakenInfo(BECount, MaxBECount);
3455 }
3456 }
3457
3458 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3459 // Procede to the next level to examine the icmp.
3460 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3461 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462
Eli Friedman361e54d2009-05-09 12:32:42 +00003463 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003464 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3465}
3466
3467/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3468/// backedge of the specified loop will execute if its exit condition
3469/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3470ScalarEvolution::BackedgeTakenInfo
3471ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3472 ICmpInst *ExitCond,
3473 BasicBlock *TBB,
3474 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003475
Reid Spencere4d87aa2006-12-23 06:05:41 +00003476 // If the condition was exit on true, convert the condition to exit on false
3477 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003478 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003480 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003482
3483 // Handle common loops like: for (X = "string"; *X; ++X)
3484 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3485 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003486 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003487 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003488 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3489 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3490 return BackedgeTakenInfo(ItCnt,
3491 isa<SCEVConstant>(ItCnt) ? ItCnt :
3492 getConstant(APInt::getMaxValue(BitWidth)-1));
3493 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003494 }
3495
Dan Gohman0bba49c2009-07-07 17:06:11 +00003496 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3497 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003498
3499 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003500 LHS = getSCEVAtScope(LHS, L);
3501 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003502
Dan Gohman64a845e2009-06-24 04:48:43 +00003503 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003505 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3506 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003507 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003508 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003509 }
3510
Chris Lattner53e677a2004-04-02 20:23:17 +00003511 // If we have a comparison of a chrec against a constant, try to use value
3512 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003513 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3514 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003515 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003516 // Form the constant range.
3517 ConstantRange CompRange(
3518 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003519
Dan Gohman0bba49c2009-07-07 17:06:11 +00003520 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003521 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003522 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003523
Chris Lattner53e677a2004-04-02 20:23:17 +00003524 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003525 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003526 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003527 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003528 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003529 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003530 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003531 case ICmpInst::ICMP_EQ: { // while (X == Y)
3532 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003533 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003535 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003536 }
3537 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003538 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3539 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003540 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003541 }
3542 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003543 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3544 getNotSCEV(RHS), L, true);
3545 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003546 break;
3547 }
3548 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003549 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3550 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003551 break;
3552 }
3553 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003554 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3555 getNotSCEV(RHS), L, false);
3556 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003557 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003558 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003559 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003560#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003561 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003562 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003563 errs() << "[unsigned] ";
3564 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003565 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003567#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003568 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003569 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003570 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003571 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003572}
3573
Chris Lattner673e02b2004-10-12 01:49:27 +00003574static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003575EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3576 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003577 const SCEV *InVal = SE.getConstant(C);
3578 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003579 assert(isa<SCEVConstant>(Val) &&
3580 "Evaluation of SCEV at constant didn't fold correctly?");
3581 return cast<SCEVConstant>(Val)->getValue();
3582}
3583
3584/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3585/// and a GEP expression (missing the pointer index) indexing into it, return
3586/// the addressed element of the initializer or null if the index expression is
3587/// invalid.
3588static Constant *
Owen Andersone922c022009-07-22 00:24:57 +00003589GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003590 const std::vector<ConstantInt*> &Indices) {
3591 Constant *Init = GV->getInitializer();
3592 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003593 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003594 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3595 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3596 Init = cast<Constant>(CS->getOperand(Idx));
3597 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3598 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3599 Init = cast<Constant>(CA->getOperand(Idx));
3600 } else if (isa<ConstantAggregateZero>(Init)) {
3601 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3602 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003603 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003604 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3605 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003606 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003607 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003608 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003609 }
3610 return 0;
3611 } else {
3612 return 0; // Unknown initializer type
3613 }
3614 }
3615 return Init;
3616}
3617
Dan Gohman46bdfb02009-02-24 18:55:53 +00003618/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3619/// 'icmp op load X, cst', try to see if we can compute the backedge
3620/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003621const SCEV *
3622ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3623 LoadInst *LI,
3624 Constant *RHS,
3625 const Loop *L,
3626 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003627 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003628
3629 // Check to see if the loaded pointer is a getelementptr of a global.
3630 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003631 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003632
3633 // Make sure that it is really a constant global we are gepping, with an
3634 // initializer, and make sure the first IDX is really 0.
3635 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003636 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003637 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3638 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003639 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003640
3641 // Okay, we allow one non-constant index into the GEP instruction.
3642 Value *VarIdx = 0;
3643 std::vector<ConstantInt*> Indexes;
3644 unsigned VarIdxNum = 0;
3645 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3646 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3647 Indexes.push_back(CI);
3648 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003649 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003650 VarIdx = GEP->getOperand(i);
3651 VarIdxNum = i-2;
3652 Indexes.push_back(0);
3653 }
3654
3655 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3656 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003657 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003658 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003659
3660 // We can only recognize very limited forms of loop index expressions, in
3661 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003662 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003663 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3664 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3665 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003666 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003667
3668 unsigned MaxSteps = MaxBruteForceIterations;
3669 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003670 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003671 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003672 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003673
3674 // Form the GEP offset.
3675 Indexes[VarIdxNum] = Val;
3676
Owen Andersone922c022009-07-22 00:24:57 +00003677 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003678 if (Result == 0) break; // Cannot compute!
3679
3680 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003682 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003683 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003684#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003685 errs() << "\n***\n*** Computed loop count " << *ItCst
3686 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3687 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003688#endif
3689 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003690 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003691 }
3692 }
Dan Gohman1c343752009-06-27 21:21:31 +00003693 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003694}
3695
3696
Chris Lattner3221ad02004-04-17 22:58:41 +00003697/// CanConstantFold - Return true if we can constant fold an instruction of the
3698/// specified type, assuming that all operands were constants.
3699static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003700 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003701 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3702 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003703
Chris Lattner3221ad02004-04-17 22:58:41 +00003704 if (const CallInst *CI = dyn_cast<CallInst>(I))
3705 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003706 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003707 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003708}
3709
Chris Lattner3221ad02004-04-17 22:58:41 +00003710/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3711/// in the loop that V is derived from. We allow arbitrary operations along the
3712/// way, but the operands of an operation must either be constants or a value
3713/// derived from a constant PHI. If this expression does not fit with these
3714/// constraints, return null.
3715static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3716 // If this is not an instruction, or if this is an instruction outside of the
3717 // loop, it can't be derived from a loop PHI.
3718 Instruction *I = dyn_cast<Instruction>(V);
3719 if (I == 0 || !L->contains(I->getParent())) return 0;
3720
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003721 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003722 if (L->getHeader() == I->getParent())
3723 return PN;
3724 else
3725 // We don't currently keep track of the control flow needed to evaluate
3726 // PHIs, so we cannot handle PHIs inside of loops.
3727 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003728 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003729
3730 // If we won't be able to constant fold this expression even if the operands
3731 // are constants, return early.
3732 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003733
Chris Lattner3221ad02004-04-17 22:58:41 +00003734 // Otherwise, we can evaluate this instruction if all of its operands are
3735 // constant or derived from a PHI node themselves.
3736 PHINode *PHI = 0;
3737 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3738 if (!(isa<Constant>(I->getOperand(Op)) ||
3739 isa<GlobalValue>(I->getOperand(Op)))) {
3740 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3741 if (P == 0) return 0; // Not evolving from PHI
3742 if (PHI == 0)
3743 PHI = P;
3744 else if (PHI != P)
3745 return 0; // Evolving from multiple different PHIs.
3746 }
3747
3748 // This is a expression evolving from a constant PHI!
3749 return PHI;
3750}
3751
3752/// EvaluateExpression - Given an expression that passes the
3753/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3754/// in the loop has the value PHIVal. If we can't fold this expression for some
3755/// reason, return null.
3756static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3757 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003758 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003759 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003760 Instruction *I = cast<Instruction>(V);
Owen Andersone922c022009-07-22 00:24:57 +00003761 LLVMContext &Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003762
3763 std::vector<Constant*> Operands;
3764 Operands.resize(I->getNumOperands());
3765
3766 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3767 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3768 if (Operands[i] == 0) return 0;
3769 }
3770
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003771 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3772 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003773 &Operands[0], Operands.size(),
3774 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003775 else
3776 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003777 &Operands[0], Operands.size(),
3778 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003779}
3780
3781/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3782/// in the header of its containing loop, we know the loop executes a
3783/// constant number of times, and the PHI node is just a recurrence
3784/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003785Constant *
3786ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3787 const APInt& BEs,
3788 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003789 std::map<PHINode*, Constant*>::iterator I =
3790 ConstantEvolutionLoopExitValue.find(PN);
3791 if (I != ConstantEvolutionLoopExitValue.end())
3792 return I->second;
3793
Dan Gohman46bdfb02009-02-24 18:55:53 +00003794 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003795 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3796
3797 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3798
3799 // Since the loop is canonicalized, the PHI node must have two entries. One
3800 // entry must be a constant (coming in from outside of the loop), and the
3801 // second must be derived from the same PHI.
3802 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3803 Constant *StartCST =
3804 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3805 if (StartCST == 0)
3806 return RetVal = 0; // Must be a constant.
3807
3808 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3809 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3810 if (PN2 != PN)
3811 return RetVal = 0; // Not derived from same PHI.
3812
3813 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003814 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003815 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003816
Dan Gohman46bdfb02009-02-24 18:55:53 +00003817 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003818 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003819 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3820 if (IterationNum == NumIterations)
3821 return RetVal = PHIVal; // Got exit value!
3822
3823 // Compute the value of the PHI node for the next iteration.
3824 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3825 if (NextPHI == PHIVal)
3826 return RetVal = NextPHI; // Stopped evolving!
3827 if (NextPHI == 0)
3828 return 0; // Couldn't evaluate!
3829 PHIVal = NextPHI;
3830 }
3831}
3832
Dan Gohman07ad19b2009-07-27 16:09:48 +00003833/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003834/// constant number of times (the condition evolves only from constants),
3835/// try to evaluate a few iterations of the loop until we get the exit
3836/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003837/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003838const SCEV *
3839ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3840 Value *Cond,
3841 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003842 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003843 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003844
3845 // Since the loop is canonicalized, the PHI node must have two entries. One
3846 // entry must be a constant (coming in from outside of the loop), and the
3847 // second must be derived from the same PHI.
3848 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3849 Constant *StartCST =
3850 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003851 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003852
3853 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3854 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003855 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003856
3857 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3858 // the loop symbolically to determine when the condition gets a value of
3859 // "ExitWhen".
3860 unsigned IterationNum = 0;
3861 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3862 for (Constant *PHIVal = StartCST;
3863 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003864 ConstantInt *CondVal =
3865 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003866
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003867 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003868 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003869
Reid Spencere8019bb2007-03-01 07:25:48 +00003870 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003871 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00003872 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003873 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003874
Chris Lattner3221ad02004-04-17 22:58:41 +00003875 // Compute the value of the PHI node for the next iteration.
3876 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3877 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003878 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003879 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003880 }
3881
3882 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003883 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003884}
3885
Dan Gohman66a7e852009-05-08 20:38:54 +00003886/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3887/// at the specified scope in the program. The L value specifies a loop
3888/// nest to evaluate the expression at, where null is the top-level or a
3889/// specified loop is immediately inside of the loop.
3890///
3891/// This method can be used to compute the exit value for a variable defined
3892/// in a loop by querying what the value will hold in the parent loop.
3893///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003894/// In the case that a relevant loop exit value cannot be computed, the
3895/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003896const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003897 // FIXME: this should be turned into a virtual method on SCEV!
3898
Chris Lattner3221ad02004-04-17 22:58:41 +00003899 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003900
Nick Lewycky3e630762008-02-20 06:48:22 +00003901 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003902 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003903 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003904 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003905 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003906 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3907 if (PHINode *PN = dyn_cast<PHINode>(I))
3908 if (PN->getParent() == LI->getHeader()) {
3909 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003910 // to see if the loop that contains it has a known backedge-taken
3911 // count. If so, we may be able to force computation of the exit
3912 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003913 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003914 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003915 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003916 // Okay, we know how many times the containing loop executes. If
3917 // this is a constant evolving PHI node, get the final value at
3918 // the specified iteration number.
3919 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003920 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003921 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003922 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003923 }
3924 }
3925
Reid Spencer09906f32006-12-04 21:33:23 +00003926 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003927 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003928 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003929 // result. This is particularly useful for computing loop exit values.
3930 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003931 // Check to see if we've folded this instruction at this loop before.
3932 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3933 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3934 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3935 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003936 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003937
Chris Lattner3221ad02004-04-17 22:58:41 +00003938 std::vector<Constant*> Operands;
3939 Operands.reserve(I->getNumOperands());
3940 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3941 Value *Op = I->getOperand(i);
3942 if (Constant *C = dyn_cast<Constant>(Op)) {
3943 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003944 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003945 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003946 // non-integer and non-pointer, don't even try to analyze them
3947 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003948 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003949 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003950
Dan Gohman85b05a22009-07-13 21:35:55 +00003951 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00003952 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003953 Constant *C = SC->getValue();
3954 if (C->getType() != Op->getType())
3955 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3956 Op->getType(),
3957 false),
3958 C, Op->getType());
3959 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003960 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003961 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3962 if (C->getType() != Op->getType())
3963 C =
3964 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3965 Op->getType(),
3966 false),
3967 C, Op->getType());
3968 Operands.push_back(C);
3969 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003970 return V;
3971 } else {
3972 return V;
3973 }
3974 }
3975 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003976
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003977 Constant *C;
3978 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3979 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003980 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00003981 getContext());
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003982 else
3983 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003984 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00003985 getContext());
Dan Gohman6bce6432009-05-08 20:47:27 +00003986 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003987 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003988 }
3989 }
3990
3991 // This is some other type of SCEVUnknown, just return it.
3992 return V;
3993 }
3994
Dan Gohman622ed672009-05-04 22:02:23 +00003995 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003996 // Avoid performing the look-up in the common case where the specified
3997 // expression has no loop-variant portions.
3998 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003999 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004000 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004001 // Okay, at least one of these operands is loop variant but might be
4002 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004003 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4004 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004005 NewOps.push_back(OpAtScope);
4006
4007 for (++i; i != e; ++i) {
4008 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004009 NewOps.push_back(OpAtScope);
4010 }
4011 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004012 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004013 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004014 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004015 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004016 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004017 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004018 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004019 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004020 }
4021 }
4022 // If we got here, all operands are loop invariant.
4023 return Comm;
4024 }
4025
Dan Gohman622ed672009-05-04 22:02:23 +00004026 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004027 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4028 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004029 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4030 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004031 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004032 }
4033
4034 // If this is a loop recurrence for a loop that does not contain L, then we
4035 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004036 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004037 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
4038 // To evaluate this recurrence, we need to know how many times the AddRec
4039 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004040 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004041 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004042
Eli Friedmanb42a6262008-08-04 23:49:06 +00004043 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004044 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004045 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004046 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004047 }
4048
Dan Gohman622ed672009-05-04 22:02:23 +00004049 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004050 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004051 if (Op == Cast->getOperand())
4052 return Cast; // must be loop invariant
4053 return getZeroExtendExpr(Op, Cast->getType());
4054 }
4055
Dan Gohman622ed672009-05-04 22:02:23 +00004056 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004057 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004058 if (Op == Cast->getOperand())
4059 return Cast; // must be loop invariant
4060 return getSignExtendExpr(Op, Cast->getType());
4061 }
4062
Dan Gohman622ed672009-05-04 22:02:23 +00004063 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004064 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004065 if (Op == Cast->getOperand())
4066 return Cast; // must be loop invariant
4067 return getTruncateExpr(Op, Cast->getType());
4068 }
4069
Dan Gohmanc40f17b2009-08-18 16:46:41 +00004070 if (isa<SCEVTargetDataConstant>(V))
4071 return V;
4072
Torok Edwinc23197a2009-07-14 16:55:14 +00004073 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004074 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004075}
4076
Dan Gohman66a7e852009-05-08 20:38:54 +00004077/// getSCEVAtScope - This is a convenience function which does
4078/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004079const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004080 return getSCEVAtScope(getSCEV(V), L);
4081}
4082
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004083/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4084/// following equation:
4085///
4086/// A * X = B (mod N)
4087///
4088/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4089/// A and B isn't important.
4090///
4091/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004092static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004093 ScalarEvolution &SE) {
4094 uint32_t BW = A.getBitWidth();
4095 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4096 assert(A != 0 && "A must be non-zero.");
4097
4098 // 1. D = gcd(A, N)
4099 //
4100 // The gcd of A and N may have only one prime factor: 2. The number of
4101 // trailing zeros in A is its multiplicity
4102 uint32_t Mult2 = A.countTrailingZeros();
4103 // D = 2^Mult2
4104
4105 // 2. Check if B is divisible by D.
4106 //
4107 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4108 // is not less than multiplicity of this prime factor for D.
4109 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004110 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004111
4112 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4113 // modulo (N / D).
4114 //
4115 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4116 // bit width during computations.
4117 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4118 APInt Mod(BW + 1, 0);
4119 Mod.set(BW - Mult2); // Mod = N / D
4120 APInt I = AD.multiplicativeInverse(Mod);
4121
4122 // 4. Compute the minimum unsigned root of the equation:
4123 // I * (B / D) mod (N / D)
4124 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4125
4126 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4127 // bits.
4128 return SE.getConstant(Result.trunc(BW));
4129}
Chris Lattner53e677a2004-04-02 20:23:17 +00004130
4131/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4132/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4133/// might be the same) or two SCEVCouldNotCompute objects.
4134///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004135static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004136SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004137 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004138 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4139 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4140 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004141
Chris Lattner53e677a2004-04-02 20:23:17 +00004142 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004143 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004144 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004145 return std::make_pair(CNC, CNC);
4146 }
4147
Reid Spencere8019bb2007-03-01 07:25:48 +00004148 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004149 const APInt &L = LC->getValue()->getValue();
4150 const APInt &M = MC->getValue()->getValue();
4151 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004152 APInt Two(BitWidth, 2);
4153 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004154
Dan Gohman64a845e2009-06-24 04:48:43 +00004155 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004156 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004157 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004158 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4159 // The B coefficient is M-N/2
4160 APInt B(M);
4161 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004162
Reid Spencere8019bb2007-03-01 07:25:48 +00004163 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004164 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004165
Reid Spencere8019bb2007-03-01 07:25:48 +00004166 // Compute the B^2-4ac term.
4167 APInt SqrtTerm(B);
4168 SqrtTerm *= B;
4169 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004170
Reid Spencere8019bb2007-03-01 07:25:48 +00004171 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4172 // integer value or else APInt::sqrt() will assert.
4173 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004174
Dan Gohman64a845e2009-06-24 04:48:43 +00004175 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004176 // The divisions must be performed as signed divisions.
4177 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004178 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004179 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004180 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004181 return std::make_pair(CNC, CNC);
4182 }
4183
Owen Andersone922c022009-07-22 00:24:57 +00004184 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004185
4186 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004187 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004188 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004189 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004190
Dan Gohman64a845e2009-06-24 04:48:43 +00004191 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004192 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004193 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004194}
4195
4196/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004197/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004198const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004199 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004200 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004201 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004202 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004203 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004204 }
4205
Dan Gohman35738ac2009-05-04 22:30:44 +00004206 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004207 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004208 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004209
4210 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004211 // If this is an affine expression, the execution count of this branch is
4212 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004213 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004214 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004215 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004216 // equivalent to:
4217 //
4218 // Step*N = -Start (mod 2^BW)
4219 //
4220 // where BW is the common bit width of Start and Step.
4221
Chris Lattner53e677a2004-04-02 20:23:17 +00004222 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004223 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4224 L->getParentLoop());
4225 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4226 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004227
Dan Gohman622ed672009-05-04 22:02:23 +00004228 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004229 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004230
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004231 // First, handle unitary steps.
4232 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004233 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004234 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4235 return Start; // N = Start (as unsigned)
4236
4237 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004238 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004239 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004240 -StartC->getValue()->getValue(),
4241 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004242 }
Chris Lattner42a75512007-01-15 02:27:26 +00004243 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004244 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4245 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004246 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004247 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004248 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4249 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004250 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004251#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004252 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4253 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004254#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004255 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004256 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004257 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004258 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004259 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004260 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004261
Chris Lattner53e677a2004-04-02 20:23:17 +00004262 // We can only use this value if the chrec ends up with an exact zero
4263 // value at this index. When solving for "X*X != 5", for example, we
4264 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004265 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004266 if (Val->isZero())
4267 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004268 }
4269 }
4270 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004271
Dan Gohman1c343752009-06-27 21:21:31 +00004272 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004273}
4274
4275/// HowFarToNonZero - Return the number of times a backedge checking the
4276/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004277/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004278const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004279 // Loops that look like: while (X == 0) are very strange indeed. We don't
4280 // handle them yet except for the trivial case. This could be expanded in the
4281 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004282
Chris Lattner53e677a2004-04-02 20:23:17 +00004283 // If the value is a constant, check to see if it is known to be non-zero
4284 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004285 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004286 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004287 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004288 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004289 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004290
Chris Lattner53e677a2004-04-02 20:23:17 +00004291 // We could implement others, but I really doubt anyone writes loops like
4292 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004293 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004294}
4295
Dan Gohman859b4822009-05-18 15:36:09 +00004296/// getLoopPredecessor - If the given loop's header has exactly one unique
4297/// predecessor outside the loop, return it. Otherwise return null.
4298///
4299BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4300 BasicBlock *Header = L->getHeader();
4301 BasicBlock *Pred = 0;
4302 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4303 PI != E; ++PI)
4304 if (!L->contains(*PI)) {
4305 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4306 Pred = *PI;
4307 }
4308 return Pred;
4309}
4310
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004311/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4312/// (which may not be an immediate predecessor) which has exactly one
4313/// successor from which BB is reachable, or null if no such block is
4314/// found.
4315///
4316BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004317ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004318 // If the block has a unique predecessor, then there is no path from the
4319 // predecessor to the block that does not go through the direct edge
4320 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004321 if (BasicBlock *Pred = BB->getSinglePredecessor())
4322 return Pred;
4323
4324 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004325 // If the header has a unique predecessor outside the loop, it must be
4326 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004327 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004328 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004329
4330 return 0;
4331}
4332
Dan Gohman763bad12009-06-20 00:35:32 +00004333/// HasSameValue - SCEV structural equivalence is usually sufficient for
4334/// testing whether two expressions are equal, however for the purposes of
4335/// looking for a condition guarding a loop, it can be useful to be a little
4336/// more general, since a front-end may have replicated the controlling
4337/// expression.
4338///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004339static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004340 // Quick check to see if they are the same SCEV.
4341 if (A == B) return true;
4342
4343 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4344 // two different instructions with the same value. Check for this case.
4345 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4346 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4347 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4348 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4349 if (AI->isIdenticalTo(BI))
4350 return true;
4351
4352 // Otherwise assume they may have a different value.
4353 return false;
4354}
4355
Dan Gohman85b05a22009-07-13 21:35:55 +00004356bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4357 return getSignedRange(S).getSignedMax().isNegative();
4358}
4359
4360bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4361 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4362}
4363
4364bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4365 return !getSignedRange(S).getSignedMin().isNegative();
4366}
4367
4368bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4369 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4370}
4371
4372bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4373 return isKnownNegative(S) || isKnownPositive(S);
4374}
4375
4376bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4377 const SCEV *LHS, const SCEV *RHS) {
4378
4379 if (HasSameValue(LHS, RHS))
4380 return ICmpInst::isTrueWhenEqual(Pred);
4381
4382 switch (Pred) {
4383 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004384 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004385 break;
4386 case ICmpInst::ICMP_SGT:
4387 Pred = ICmpInst::ICMP_SLT;
4388 std::swap(LHS, RHS);
4389 case ICmpInst::ICMP_SLT: {
4390 ConstantRange LHSRange = getSignedRange(LHS);
4391 ConstantRange RHSRange = getSignedRange(RHS);
4392 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4393 return true;
4394 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4395 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004396 break;
4397 }
4398 case ICmpInst::ICMP_SGE:
4399 Pred = ICmpInst::ICMP_SLE;
4400 std::swap(LHS, RHS);
4401 case ICmpInst::ICMP_SLE: {
4402 ConstantRange LHSRange = getSignedRange(LHS);
4403 ConstantRange RHSRange = getSignedRange(RHS);
4404 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4405 return true;
4406 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4407 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004408 break;
4409 }
4410 case ICmpInst::ICMP_UGT:
4411 Pred = ICmpInst::ICMP_ULT;
4412 std::swap(LHS, RHS);
4413 case ICmpInst::ICMP_ULT: {
4414 ConstantRange LHSRange = getUnsignedRange(LHS);
4415 ConstantRange RHSRange = getUnsignedRange(RHS);
4416 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4417 return true;
4418 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4419 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004420 break;
4421 }
4422 case ICmpInst::ICMP_UGE:
4423 Pred = ICmpInst::ICMP_ULE;
4424 std::swap(LHS, RHS);
4425 case ICmpInst::ICMP_ULE: {
4426 ConstantRange LHSRange = getUnsignedRange(LHS);
4427 ConstantRange RHSRange = getUnsignedRange(RHS);
4428 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4429 return true;
4430 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4431 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004432 break;
4433 }
4434 case ICmpInst::ICMP_NE: {
4435 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4436 return true;
4437 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4438 return true;
4439
4440 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4441 if (isKnownNonZero(Diff))
4442 return true;
4443 break;
4444 }
4445 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004446 // The check at the top of the function catches the case where
4447 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004448 break;
4449 }
4450 return false;
4451}
4452
4453/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4454/// protected by a conditional between LHS and RHS. This is used to
4455/// to eliminate casts.
4456bool
4457ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4458 ICmpInst::Predicate Pred,
4459 const SCEV *LHS, const SCEV *RHS) {
4460 // Interpret a null as meaning no loop, where there is obviously no guard
4461 // (interprocedural conditions notwithstanding).
4462 if (!L) return true;
4463
4464 BasicBlock *Latch = L->getLoopLatch();
4465 if (!Latch)
4466 return false;
4467
4468 BranchInst *LoopContinuePredicate =
4469 dyn_cast<BranchInst>(Latch->getTerminator());
4470 if (!LoopContinuePredicate ||
4471 LoopContinuePredicate->isUnconditional())
4472 return false;
4473
Dan Gohman0f4b2852009-07-21 23:03:19 +00004474 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4475 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004476}
4477
4478/// isLoopGuardedByCond - Test whether entry to the loop is protected
4479/// by a conditional between LHS and RHS. This is used to help avoid max
4480/// expressions in loop trip counts, and to eliminate casts.
4481bool
4482ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4483 ICmpInst::Predicate Pred,
4484 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004485 // Interpret a null as meaning no loop, where there is obviously no guard
4486 // (interprocedural conditions notwithstanding).
4487 if (!L) return false;
4488
Dan Gohman859b4822009-05-18 15:36:09 +00004489 BasicBlock *Predecessor = getLoopPredecessor(L);
4490 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004491
Dan Gohman859b4822009-05-18 15:36:09 +00004492 // Starting at the loop predecessor, climb up the predecessor chain, as long
4493 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004494 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004495 for (; Predecessor;
4496 PredecessorDest = Predecessor,
4497 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004498
4499 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004500 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004501 if (!LoopEntryPredicate ||
4502 LoopEntryPredicate->isUnconditional())
4503 continue;
4504
Dan Gohman0f4b2852009-07-21 23:03:19 +00004505 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4506 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004507 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004508 }
4509
Dan Gohman38372182008-08-12 20:17:31 +00004510 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004511}
4512
Dan Gohman0f4b2852009-07-21 23:03:19 +00004513/// isImpliedCond - Test whether the condition described by Pred, LHS,
4514/// and RHS is true whenever the given Cond value evaluates to true.
4515bool ScalarEvolution::isImpliedCond(Value *CondValue,
4516 ICmpInst::Predicate Pred,
4517 const SCEV *LHS, const SCEV *RHS,
4518 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004519 // Recursivly handle And and Or conditions.
4520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4521 if (BO->getOpcode() == Instruction::And) {
4522 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004523 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4524 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004525 } else if (BO->getOpcode() == Instruction::Or) {
4526 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004527 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4528 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004529 }
4530 }
4531
4532 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4533 if (!ICI) return false;
4534
Dan Gohman85b05a22009-07-13 21:35:55 +00004535 // Bail if the ICmp's operands' types are wider than the needed type
4536 // before attempting to call getSCEV on them. This avoids infinite
4537 // recursion, since the analysis of widening casts can require loop
4538 // exit condition information for overflow checking, which would
4539 // lead back here.
4540 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004541 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004542 return false;
4543
Dan Gohman0f4b2852009-07-21 23:03:19 +00004544 // Now that we found a conditional branch that dominates the loop, check to
4545 // see if it is the comparison we are looking for.
4546 ICmpInst::Predicate FoundPred;
4547 if (Inverse)
4548 FoundPred = ICI->getInversePredicate();
4549 else
4550 FoundPred = ICI->getPredicate();
4551
4552 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4553 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004554
4555 // Balance the types. The case where FoundLHS' type is wider than
4556 // LHS' type is checked for above.
4557 if (getTypeSizeInBits(LHS->getType()) >
4558 getTypeSizeInBits(FoundLHS->getType())) {
4559 if (CmpInst::isSigned(Pred)) {
4560 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4561 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4562 } else {
4563 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4564 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4565 }
4566 }
4567
Dan Gohman0f4b2852009-07-21 23:03:19 +00004568 // Canonicalize the query to match the way instcombine will have
4569 // canonicalized the comparison.
4570 // First, put a constant operand on the right.
4571 if (isa<SCEVConstant>(LHS)) {
4572 std::swap(LHS, RHS);
4573 Pred = ICmpInst::getSwappedPredicate(Pred);
4574 }
4575 // Then, canonicalize comparisons with boundary cases.
4576 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4577 const APInt &RA = RC->getValue()->getValue();
4578 switch (Pred) {
4579 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4580 case ICmpInst::ICMP_EQ:
4581 case ICmpInst::ICMP_NE:
4582 break;
4583 case ICmpInst::ICMP_UGE:
4584 if ((RA - 1).isMinValue()) {
4585 Pred = ICmpInst::ICMP_NE;
4586 RHS = getConstant(RA - 1);
4587 break;
4588 }
4589 if (RA.isMaxValue()) {
4590 Pred = ICmpInst::ICMP_EQ;
4591 break;
4592 }
4593 if (RA.isMinValue()) return true;
4594 break;
4595 case ICmpInst::ICMP_ULE:
4596 if ((RA + 1).isMaxValue()) {
4597 Pred = ICmpInst::ICMP_NE;
4598 RHS = getConstant(RA + 1);
4599 break;
4600 }
4601 if (RA.isMinValue()) {
4602 Pred = ICmpInst::ICMP_EQ;
4603 break;
4604 }
4605 if (RA.isMaxValue()) return true;
4606 break;
4607 case ICmpInst::ICMP_SGE:
4608 if ((RA - 1).isMinSignedValue()) {
4609 Pred = ICmpInst::ICMP_NE;
4610 RHS = getConstant(RA - 1);
4611 break;
4612 }
4613 if (RA.isMaxSignedValue()) {
4614 Pred = ICmpInst::ICMP_EQ;
4615 break;
4616 }
4617 if (RA.isMinSignedValue()) return true;
4618 break;
4619 case ICmpInst::ICMP_SLE:
4620 if ((RA + 1).isMaxSignedValue()) {
4621 Pred = ICmpInst::ICMP_NE;
4622 RHS = getConstant(RA + 1);
4623 break;
4624 }
4625 if (RA.isMinSignedValue()) {
4626 Pred = ICmpInst::ICMP_EQ;
4627 break;
4628 }
4629 if (RA.isMaxSignedValue()) return true;
4630 break;
4631 case ICmpInst::ICMP_UGT:
4632 if (RA.isMinValue()) {
4633 Pred = ICmpInst::ICMP_NE;
4634 break;
4635 }
4636 if ((RA + 1).isMaxValue()) {
4637 Pred = ICmpInst::ICMP_EQ;
4638 RHS = getConstant(RA + 1);
4639 break;
4640 }
4641 if (RA.isMaxValue()) return false;
4642 break;
4643 case ICmpInst::ICMP_ULT:
4644 if (RA.isMaxValue()) {
4645 Pred = ICmpInst::ICMP_NE;
4646 break;
4647 }
4648 if ((RA - 1).isMinValue()) {
4649 Pred = ICmpInst::ICMP_EQ;
4650 RHS = getConstant(RA - 1);
4651 break;
4652 }
4653 if (RA.isMinValue()) return false;
4654 break;
4655 case ICmpInst::ICMP_SGT:
4656 if (RA.isMinSignedValue()) {
4657 Pred = ICmpInst::ICMP_NE;
4658 break;
4659 }
4660 if ((RA + 1).isMaxSignedValue()) {
4661 Pred = ICmpInst::ICMP_EQ;
4662 RHS = getConstant(RA + 1);
4663 break;
4664 }
4665 if (RA.isMaxSignedValue()) return false;
4666 break;
4667 case ICmpInst::ICMP_SLT:
4668 if (RA.isMaxSignedValue()) {
4669 Pred = ICmpInst::ICMP_NE;
4670 break;
4671 }
4672 if ((RA - 1).isMinSignedValue()) {
4673 Pred = ICmpInst::ICMP_EQ;
4674 RHS = getConstant(RA - 1);
4675 break;
4676 }
4677 if (RA.isMinSignedValue()) return false;
4678 break;
4679 }
4680 }
4681
4682 // Check to see if we can make the LHS or RHS match.
4683 if (LHS == FoundRHS || RHS == FoundLHS) {
4684 if (isa<SCEVConstant>(RHS)) {
4685 std::swap(FoundLHS, FoundRHS);
4686 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4687 } else {
4688 std::swap(LHS, RHS);
4689 Pred = ICmpInst::getSwappedPredicate(Pred);
4690 }
4691 }
4692
4693 // Check whether the found predicate is the same as the desired predicate.
4694 if (FoundPred == Pred)
4695 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4696
4697 // Check whether swapping the found predicate makes it the same as the
4698 // desired predicate.
4699 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4700 if (isa<SCEVConstant>(RHS))
4701 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4702 else
4703 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4704 RHS, LHS, FoundLHS, FoundRHS);
4705 }
4706
4707 // Check whether the actual condition is beyond sufficient.
4708 if (FoundPred == ICmpInst::ICMP_EQ)
4709 if (ICmpInst::isTrueWhenEqual(Pred))
4710 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4711 return true;
4712 if (Pred == ICmpInst::ICMP_NE)
4713 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4714 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4715 return true;
4716
4717 // Otherwise assume the worst.
4718 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004719}
4720
Dan Gohman0f4b2852009-07-21 23:03:19 +00004721/// isImpliedCondOperands - Test whether the condition described by Pred,
4722/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4723/// and FoundRHS is true.
4724bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4725 const SCEV *LHS, const SCEV *RHS,
4726 const SCEV *FoundLHS,
4727 const SCEV *FoundRHS) {
4728 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4729 FoundLHS, FoundRHS) ||
4730 // ~x < ~y --> x > y
4731 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4732 getNotSCEV(FoundRHS),
4733 getNotSCEV(FoundLHS));
4734}
4735
4736/// isImpliedCondOperandsHelper - Test whether the condition described by
4737/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4738/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004739bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004740ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4741 const SCEV *LHS, const SCEV *RHS,
4742 const SCEV *FoundLHS,
4743 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004744 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004745 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4746 case ICmpInst::ICMP_EQ:
4747 case ICmpInst::ICMP_NE:
4748 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4749 return true;
4750 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004751 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004752 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004753 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4754 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4755 return true;
4756 break;
4757 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004758 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004759 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4760 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4761 return true;
4762 break;
4763 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004764 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004765 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4766 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4767 return true;
4768 break;
4769 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004770 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004771 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4772 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4773 return true;
4774 break;
4775 }
4776
4777 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004778}
4779
Dan Gohman51f53b72009-06-21 23:46:38 +00004780/// getBECount - Subtract the end and start values and divide by the step,
4781/// rounding up, to get the number of times the backedge is executed. Return
4782/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004783const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004784 const SCEV *End,
4785 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004786 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004787 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4788 const SCEV *Diff = getMinusSCEV(End, Start);
4789 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004790
4791 // Add an adjustment to the difference between End and Start so that
4792 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004793 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004794
4795 // Check Add for unsigned overflow.
4796 // TODO: More sophisticated things could be done here.
Owen Anderson1d0be152009-08-13 21:58:54 +00004797 const Type *WideTy = IntegerType::get(getContext(),
4798 getTypeSizeInBits(Ty) + 1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004799 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4800 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4801 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004802 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004803 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004804
4805 return getUDivExpr(Add, Step);
4806}
4807
Chris Lattnerdb25de42005-08-15 23:33:51 +00004808/// HowManyLessThans - Return the number of times a backedge containing the
4809/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004810/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004811ScalarEvolution::BackedgeTakenInfo
4812ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4813 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004814 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004815 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004816
Dan Gohman35738ac2009-05-04 22:30:44 +00004817 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004818 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004819 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004820
4821 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004822 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004823 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004824 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004825
4826 // TODO: handle non-constant strides.
4827 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4828 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004829 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004830 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004831 // With unit stride, the iteration never steps past the limit value.
4832 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4833 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4834 // Test whether a positive iteration iteration can step past the limit
4835 // value and past the maximum value for its type in a single step.
4836 if (isSigned) {
4837 APInt Max = APInt::getSignedMaxValue(BitWidth);
4838 if ((Max - CStep->getValue()->getValue())
4839 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004840 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004841 } else {
4842 APInt Max = APInt::getMaxValue(BitWidth);
4843 if ((Max - CStep->getValue()->getValue())
4844 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004845 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004846 }
4847 } else
4848 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004849 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004850 } else
4851 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004852 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004853
Dan Gohmana1af7572009-04-30 20:47:05 +00004854 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4855 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4856 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004857 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004858
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004859 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004860 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004861
Dan Gohmana1af7572009-04-30 20:47:05 +00004862 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004863 const SCEV *MinStart = getConstant(isSigned ?
4864 getSignedRange(Start).getSignedMin() :
4865 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004866
Dan Gohmana1af7572009-04-30 20:47:05 +00004867 // If we know that the condition is true in order to enter the loop,
4868 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004869 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4870 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004871 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004872 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004873 isSigned ? ICmpInst::ICMP_SLT :
4874 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004875 getMinusSCEV(Start, Step), RHS))
4876 End = isSigned ? getSMaxExpr(RHS, Start)
4877 : getUMaxExpr(RHS, Start);
4878
4879 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004880 const SCEV *MaxEnd = getConstant(isSigned ?
4881 getSignedRange(End).getSignedMax() :
4882 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004883
4884 // Finally, we subtract these two values and divide, rounding up, to get
4885 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004886 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004887
4888 // The maximum backedge count is similar, except using the minimum start
4889 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004890 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004891
4892 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004893 }
4894
Dan Gohman1c343752009-06-27 21:21:31 +00004895 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004896}
4897
Chris Lattner53e677a2004-04-02 20:23:17 +00004898/// getNumIterationsInRange - Return the number of iterations of this loop that
4899/// produce values in the specified constant range. Another way of looking at
4900/// this is that it returns the first iteration number where the value is not in
4901/// the condition, thus computing the exit count. If the iteration count can't
4902/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004903const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004904 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004905 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004906 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004907
4908 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004909 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004910 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004911 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004912 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004913 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004914 if (const SCEVAddRecExpr *ShiftedAddRec =
4915 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004916 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004917 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004918 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004919 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004920 }
4921
4922 // The only time we can solve this is when we have all constant indices.
4923 // Otherwise, we cannot determine the overflow conditions.
4924 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4925 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004926 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004927
4928
4929 // Okay at this point we know that all elements of the chrec are constants and
4930 // that the start element is zero.
4931
4932 // First check to see if the range contains zero. If not, the first
4933 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004934 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004935 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004936 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004937
Chris Lattner53e677a2004-04-02 20:23:17 +00004938 if (isAffine()) {
4939 // If this is an affine expression then we have this situation:
4940 // Solve {0,+,A} in Range === Ax in Range
4941
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004942 // We know that zero is in the range. If A is positive then we know that
4943 // the upper value of the range must be the first possible exit value.
4944 // If A is negative then the lower of the range is the last possible loop
4945 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004946 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004947 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4948 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004949
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004950 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004951 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00004952 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004953
4954 // Evaluate at the exit value. If we really did fall out of the valid
4955 // range, then we computed our trip count, otherwise wrap around or other
4956 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004957 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004958 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004959 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004960
4961 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004962 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004963 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00004964 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004965 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004966 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004967 } else if (isQuadratic()) {
4968 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4969 // quadratic equation to solve it. To do this, we must frame our problem in
4970 // terms of figuring out when zero is crossed, instead of when
4971 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004972 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004973 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004974 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004975
4976 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004977 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004978 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004979 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4980 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004981 if (R1) {
4982 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004983 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004984 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00004985 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004986 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004987 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004988
Chris Lattner53e677a2004-04-02 20:23:17 +00004989 // Make sure the root is not off by one. The returned iteration should
4990 // not be in the range, but the previous one should be. When solving
4991 // for "X*X < 5", for example, we should not return a root of 2.
4992 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004993 R1->getValue(),
4994 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004995 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004996 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004997 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00004998 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004999
Dan Gohman246b2562007-10-22 18:31:58 +00005000 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005001 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005002 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005003 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005004 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005005
Chris Lattner53e677a2004-04-02 20:23:17 +00005006 // If R1 was not in the range, then it is a good return value. Make
5007 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005008 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005009 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005010 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005011 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005012 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005013 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005014 }
5015 }
5016 }
5017
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005018 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005019}
5020
5021
5022
5023//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005024// SCEVCallbackVH Class Implementation
5025//===----------------------------------------------------------------------===//
5026
Dan Gohman1959b752009-05-19 19:22:47 +00005027void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005028 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005029 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5030 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00005031 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
5032 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00005033 SE->Scalars.erase(getValPtr());
5034 // this now dangles!
5035}
5036
Dan Gohman1959b752009-05-19 19:22:47 +00005037void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005038 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005039
5040 // Forget all the expressions associated with users of the old value,
5041 // so that future queries will recompute the expressions using the new
5042 // value.
5043 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005044 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005045 Value *Old = getValPtr();
5046 bool DeleteOld = false;
5047 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5048 UI != UE; ++UI)
5049 Worklist.push_back(*UI);
5050 while (!Worklist.empty()) {
5051 User *U = Worklist.pop_back_val();
5052 // Deleting the Old value will cause this to dangle. Postpone
5053 // that until everything else is done.
5054 if (U == Old) {
5055 DeleteOld = true;
5056 continue;
5057 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005058 if (!Visited.insert(U))
5059 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005060 if (PHINode *PN = dyn_cast<PHINode>(U))
5061 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00005062 if (Instruction *I = dyn_cast<Instruction>(U))
5063 SE->ValuesAtScopes.erase(I);
Dan Gohman69fcae92009-07-14 14:34:04 +00005064 SE->Scalars.erase(U);
5065 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5066 UI != UE; ++UI)
5067 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005068 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005069 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005070 if (DeleteOld) {
5071 if (PHINode *PN = dyn_cast<PHINode>(Old))
5072 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00005073 if (Instruction *I = dyn_cast<Instruction>(Old))
5074 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00005075 SE->Scalars.erase(Old);
5076 // this now dangles!
5077 }
5078 // this may dangle!
5079}
5080
Dan Gohman1959b752009-05-19 19:22:47 +00005081ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005082 : CallbackVH(V), SE(se) {}
5083
5084//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005085// ScalarEvolution Class Implementation
5086//===----------------------------------------------------------------------===//
5087
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005088ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005089 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005090}
5091
Chris Lattner53e677a2004-04-02 20:23:17 +00005092bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005093 this->F = &F;
5094 LI = &getAnalysis<LoopInfo>();
5095 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005096 return false;
5097}
5098
5099void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005100 Scalars.clear();
5101 BackedgeTakenCounts.clear();
5102 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005103 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005104 UniqueSCEVs.clear();
5105 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005106}
5107
5108void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5109 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005110 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005111}
5112
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005113bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005114 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005115}
5116
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005117static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005118 const Loop *L) {
5119 // Print all inner loops first
5120 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5121 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005122
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005123 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005124
Devang Patelb7211a22007-08-21 00:31:24 +00005125 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005126 L->getExitBlocks(ExitBlocks);
5127 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005128 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005129
Dan Gohman46bdfb02009-02-24 18:55:53 +00005130 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5131 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005132 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005133 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005134 }
5135
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005136 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005137 OS << "Loop " << L->getHeader()->getName() << ": ";
5138
5139 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5140 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5141 } else {
5142 OS << "Unpredictable max backedge-taken count. ";
5143 }
5144
5145 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005146}
5147
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005148void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005149 // ScalarEvolution's implementaiton of the print method is to print
5150 // out SCEV values of all instructions that are interesting. Doing
5151 // this potentially causes it to create new SCEV objects though,
5152 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005153 // observable from outside the class though, so casting away the
5154 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005155 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005156
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005157 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005158 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005159 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005160 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005161 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005162 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005163 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005164
Dan Gohman0c689c52009-06-19 17:49:54 +00005165 const Loop *L = LI->getLoopFor((*I).getParent());
5166
Dan Gohman0bba49c2009-07-07 17:06:11 +00005167 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005168 if (AtUse != SV) {
5169 OS << " --> ";
5170 AtUse->print(OS);
5171 }
5172
5173 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005174 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005175 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005176 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005177 OS << "<<Unknown>>";
5178 } else {
5179 OS << *ExitValue;
5180 }
5181 }
5182
Chris Lattner53e677a2004-04-02 20:23:17 +00005183 OS << "\n";
5184 }
5185
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005186 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5187 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5188 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005189}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005190