blob: d639aee70993d0b7b6fb42e3cbb3c1e8f4f79118 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/ConstantRange.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000121 print(errs());
122 errs() << '\n';
123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000181 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000182 UniqueSCEVs.InsertNode(S, IP);
183 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman0bba49c2009-07-07 17:06:11 +0000186const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000187 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Dan Gohman0bba49c2009-07-07 17:06:11 +0000190const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000192 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohmanc050fd92009-07-13 20:50:19 +0000210SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
211 const SCEV *op, const Type *ty)
212 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000213 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
214 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216}
Chris Lattner53e677a2004-04-02 20:23:17 +0000217
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000218void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
221
Dan Gohmanc050fd92009-07-13 20:50:19 +0000222SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
223 const SCEV *op, const Type *ty)
224 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000225 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
226 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228}
229
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000230void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000231 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanc050fd92009-07-13 20:50:19 +0000234SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
235 const SCEV *op, const Type *ty)
236 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000237 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
238 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000239 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000240}
241
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000242void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000243 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000247 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
248 const char *OpStr = getOperationStr();
249 OS << "(" << *Operands[0];
250 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
251 OS << OpStr << *Operands[i];
252 OS << ")";
253}
254
Dan Gohmanecb403a2009-05-07 14:00:19 +0000255bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000256 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
257 if (!getOperand(i)->dominates(BB, DT))
258 return false;
259 }
260 return true;
261}
262
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000263bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
264 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
265}
266
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000267void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000268 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000269}
270
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000271const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000272 // In most cases the types of LHS and RHS will be the same, but in some
273 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
274 // depend on the type for correctness, but handling types carefully can
275 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
276 // a pointer type than the RHS, so use the RHS' type here.
277 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000278}
279
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000280bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000281 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000282 if (!QueryLoop)
283 return false;
284
285 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
286 if (QueryLoop->contains(L->getHeader()))
287 return false;
288
289 // This recurrence is variant w.r.t. QueryLoop if any of its operands
290 // are variant.
291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
292 if (!getOperand(i)->isLoopInvariant(QueryLoop))
293 return false;
294
295 // Otherwise it's loop-invariant.
296 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000297}
298
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000299void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000300 OS << "{" << *Operands[0];
301 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
302 OS << ",+," << *Operands[i];
303 OS << "}<" << L->getHeader()->getName() + ">";
304}
Chris Lattner53e677a2004-04-02 20:23:17 +0000305
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000306void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
307 // LLVM struct fields don't have names, so just print the field number.
308 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
309}
310
311void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
312 OS << "sizeof(" << *AllocTy << ")";
313}
314
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
316 // All non-instruction values are loop invariant. All instructions are loop
317 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000318 // Instructions are never considered invariant in the function body
319 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000320 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000321 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322 return true;
323}
Chris Lattner53e677a2004-04-02 20:23:17 +0000324
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000325bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
326 if (Instruction *I = dyn_cast<Instruction>(getValue()))
327 return DT->dominates(I->getParent(), BB);
328 return true;
329}
330
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331const Type *SCEVUnknown::getType() const {
332 return V->getType();
333}
Chris Lattner53e677a2004-04-02 20:23:17 +0000334
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000335void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000337}
338
Chris Lattner8d741b82004-06-20 06:23:15 +0000339//===----------------------------------------------------------------------===//
340// SCEV Utilities
341//===----------------------------------------------------------------------===//
342
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000343static bool CompareTypes(const Type *A, const Type *B) {
344 if (A->getTypeID() != B->getTypeID())
345 return A->getTypeID() < B->getTypeID();
346 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
347 const IntegerType *BI = cast<IntegerType>(B);
348 return AI->getBitWidth() < BI->getBitWidth();
349 }
350 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
351 const PointerType *BI = cast<PointerType>(B);
352 return CompareTypes(AI->getElementType(), BI->getElementType());
353 }
354 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
355 const ArrayType *BI = cast<ArrayType>(B);
356 if (AI->getNumElements() != BI->getNumElements())
357 return AI->getNumElements() < BI->getNumElements();
358 return CompareTypes(AI->getElementType(), BI->getElementType());
359 }
360 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
361 const VectorType *BI = cast<VectorType>(B);
362 if (AI->getNumElements() != BI->getNumElements())
363 return AI->getNumElements() < BI->getNumElements();
364 return CompareTypes(AI->getElementType(), BI->getElementType());
365 }
366 if (const StructType *AI = dyn_cast<StructType>(A)) {
367 const StructType *BI = cast<StructType>(B);
368 if (AI->getNumElements() != BI->getNumElements())
369 return AI->getNumElements() < BI->getNumElements();
370 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
371 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
372 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
373 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
374 }
375 return false;
376}
377
Chris Lattner8d741b82004-06-20 06:23:15 +0000378namespace {
379 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
380 /// than the complexity of the RHS. This comparator is used to canonicalize
381 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000382 class VISIBILITY_HIDDEN SCEVComplexityCompare {
383 LoopInfo *LI;
384 public:
385 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
386
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000387 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000388 // Primarily, sort the SCEVs by their getSCEVType().
389 if (LHS->getSCEVType() != RHS->getSCEVType())
390 return LHS->getSCEVType() < RHS->getSCEVType();
391
392 // Aside from the getSCEVType() ordering, the particular ordering
393 // isn't very important except that it's beneficial to be consistent,
394 // so that (a + b) and (b + a) don't end up as different expressions.
395
396 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
397 // not as complete as it could be.
398 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
399 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
400
Dan Gohman5be18e82009-05-19 02:15:55 +0000401 // Order pointer values after integer values. This helps SCEVExpander
402 // form GEPs.
403 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
404 return false;
405 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
406 return true;
407
Dan Gohman72861302009-05-07 14:39:04 +0000408 // Compare getValueID values.
409 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
410 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
411
412 // Sort arguments by their position.
413 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
414 const Argument *RA = cast<Argument>(RU->getValue());
415 return LA->getArgNo() < RA->getArgNo();
416 }
417
418 // For instructions, compare their loop depth, and their opcode.
419 // This is pretty loose.
420 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
421 Instruction *RV = cast<Instruction>(RU->getValue());
422
423 // Compare loop depths.
424 if (LI->getLoopDepth(LV->getParent()) !=
425 LI->getLoopDepth(RV->getParent()))
426 return LI->getLoopDepth(LV->getParent()) <
427 LI->getLoopDepth(RV->getParent());
428
429 // Compare opcodes.
430 if (LV->getOpcode() != RV->getOpcode())
431 return LV->getOpcode() < RV->getOpcode();
432
433 // Compare the number of operands.
434 if (LV->getNumOperands() != RV->getNumOperands())
435 return LV->getNumOperands() < RV->getNumOperands();
436 }
437
438 return false;
439 }
440
Dan Gohman4dfad292009-06-14 22:51:25 +0000441 // Compare constant values.
442 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
443 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000444 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
445 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000446 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
447 }
448
449 // Compare addrec loop depths.
450 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
451 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
452 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
453 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
454 }
Dan Gohman72861302009-05-07 14:39:04 +0000455
456 // Lexicographically compare n-ary expressions.
457 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
458 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
459 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
460 if (i >= RC->getNumOperands())
461 return false;
462 if (operator()(LC->getOperand(i), RC->getOperand(i)))
463 return true;
464 if (operator()(RC->getOperand(i), LC->getOperand(i)))
465 return false;
466 }
467 return LC->getNumOperands() < RC->getNumOperands();
468 }
469
Dan Gohmana6b35e22009-05-07 19:23:21 +0000470 // Lexicographically compare udiv expressions.
471 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
472 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
473 if (operator()(LC->getLHS(), RC->getLHS()))
474 return true;
475 if (operator()(RC->getLHS(), LC->getLHS()))
476 return false;
477 if (operator()(LC->getRHS(), RC->getRHS()))
478 return true;
479 if (operator()(RC->getRHS(), LC->getRHS()))
480 return false;
481 return false;
482 }
483
Dan Gohman72861302009-05-07 14:39:04 +0000484 // Compare cast expressions by operand.
485 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
486 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
487 return operator()(LC->getOperand(), RC->getOperand());
488 }
489
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000490 // Compare offsetof expressions.
491 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
492 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
493 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
494 CompareTypes(RA->getStructType(), LA->getStructType()))
495 return CompareTypes(LA->getStructType(), RA->getStructType());
496 return LA->getFieldNo() < RA->getFieldNo();
497 }
498
499 // Compare sizeof expressions by the allocation type.
500 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
501 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
502 return CompareTypes(LA->getAllocType(), RA->getAllocType());
503 }
504
Torok Edwinc23197a2009-07-14 16:55:14 +0000505 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000506 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000507 }
508 };
509}
510
511/// GroupByComplexity - Given a list of SCEV objects, order them by their
512/// complexity, and group objects of the same complexity together by value.
513/// When this routine is finished, we know that any duplicates in the vector are
514/// consecutive and that complexity is monotonically increasing.
515///
516/// Note that we go take special precautions to ensure that we get determinstic
517/// results from this routine. In other words, we don't want the results of
518/// this to depend on where the addresses of various SCEV objects happened to
519/// land in memory.
520///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000521static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000522 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000523 if (Ops.size() < 2) return; // Noop
524 if (Ops.size() == 2) {
525 // This is the common case, which also happens to be trivially simple.
526 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000527 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000528 std::swap(Ops[0], Ops[1]);
529 return;
530 }
531
532 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000533 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000534
535 // Now that we are sorted by complexity, group elements of the same
536 // complexity. Note that this is, at worst, N^2, but the vector is likely to
537 // be extremely short in practice. Note that we take this approach because we
538 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000539 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000540 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000541 unsigned Complexity = S->getSCEVType();
542
543 // If there are any objects of the same complexity and same value as this
544 // one, group them.
545 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
546 if (Ops[j] == S) { // Found a duplicate.
547 // Move it to immediately after i'th element.
548 std::swap(Ops[i+1], Ops[j]);
549 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000550 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000551 }
552 }
553 }
554}
555
Chris Lattner53e677a2004-04-02 20:23:17 +0000556
Chris Lattner53e677a2004-04-02 20:23:17 +0000557
558//===----------------------------------------------------------------------===//
559// Simple SCEV method implementations
560//===----------------------------------------------------------------------===//
561
Eli Friedmanb42a6262008-08-04 23:49:06 +0000562/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000563/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000564static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000565 ScalarEvolution &SE,
566 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000567 // Handle the simplest case efficiently.
568 if (K == 1)
569 return SE.getTruncateOrZeroExtend(It, ResultTy);
570
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000571 // We are using the following formula for BC(It, K):
572 //
573 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
574 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000575 // Suppose, W is the bitwidth of the return value. We must be prepared for
576 // overflow. Hence, we must assure that the result of our computation is
577 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
578 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000579 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000581 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000582 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
583 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000585 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000586 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587 // This formula is trivially equivalent to the previous formula. However,
588 // this formula can be implemented much more efficiently. The trick is that
589 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
590 // arithmetic. To do exact division in modular arithmetic, all we have
591 // to do is multiply by the inverse. Therefore, this step can be done at
592 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000593 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000594 // The next issue is how to safely do the division by 2^T. The way this
595 // is done is by doing the multiplication step at a width of at least W + T
596 // bits. This way, the bottom W+T bits of the product are accurate. Then,
597 // when we perform the division by 2^T (which is equivalent to a right shift
598 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
599 // truncated out after the division by 2^T.
600 //
601 // In comparison to just directly using the first formula, this technique
602 // is much more efficient; using the first formula requires W * K bits,
603 // but this formula less than W + K bits. Also, the first formula requires
604 // a division step, whereas this formula only requires multiplies and shifts.
605 //
606 // It doesn't matter whether the subtraction step is done in the calculation
607 // width or the input iteration count's width; if the subtraction overflows,
608 // the result must be zero anyway. We prefer here to do it in the width of
609 // the induction variable because it helps a lot for certain cases; CodeGen
610 // isn't smart enough to ignore the overflow, which leads to much less
611 // efficient code if the width of the subtraction is wider than the native
612 // register width.
613 //
614 // (It's possible to not widen at all by pulling out factors of 2 before
615 // the multiplication; for example, K=2 can be calculated as
616 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
617 // extra arithmetic, so it's not an obvious win, and it gets
618 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000619
Eli Friedmanb42a6262008-08-04 23:49:06 +0000620 // Protection from insane SCEVs; this bound is conservative,
621 // but it probably doesn't matter.
622 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000623 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000625 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000626
Eli Friedmanb42a6262008-08-04 23:49:06 +0000627 // Calculate K! / 2^T and T; we divide out the factors of two before
628 // multiplying for calculating K! / 2^T to avoid overflow.
629 // Other overflow doesn't matter because we only care about the bottom
630 // W bits of the result.
631 APInt OddFactorial(W, 1);
632 unsigned T = 1;
633 for (unsigned i = 3; i <= K; ++i) {
634 APInt Mult(W, i);
635 unsigned TwoFactors = Mult.countTrailingZeros();
636 T += TwoFactors;
637 Mult = Mult.lshr(TwoFactors);
638 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000640
Eli Friedmanb42a6262008-08-04 23:49:06 +0000641 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000642 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000643
644 // Calcuate 2^T, at width T+W.
645 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
646
647 // Calculate the multiplicative inverse of K! / 2^T;
648 // this multiplication factor will perform the exact division by
649 // K! / 2^T.
650 APInt Mod = APInt::getSignedMinValue(W+1);
651 APInt MultiplyFactor = OddFactorial.zext(W+1);
652 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
653 MultiplyFactor = MultiplyFactor.trunc(W);
654
655 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000656 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
657 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000658 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000659 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000660 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000661 Dividend = SE.getMulExpr(Dividend,
662 SE.getTruncateOrZeroExtend(S, CalculationTy));
663 }
664
665 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000666 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000667
668 // Truncate the result, and divide by K! / 2^T.
669
670 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
671 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000672}
673
Chris Lattner53e677a2004-04-02 20:23:17 +0000674/// evaluateAtIteration - Return the value of this chain of recurrences at
675/// the specified iteration number. We can evaluate this recurrence by
676/// multiplying each element in the chain by the binomial coefficient
677/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
678///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000679/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000680///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000681/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000682///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000683const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000684 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000685 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000686 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000687 // The computation is correct in the face of overflow provided that the
688 // multiplication is performed _after_ the evaluation of the binomial
689 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000690 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000691 if (isa<SCEVCouldNotCompute>(Coeff))
692 return Coeff;
693
694 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000695 }
696 return Result;
697}
698
Chris Lattner53e677a2004-04-02 20:23:17 +0000699//===----------------------------------------------------------------------===//
700// SCEV Expression folder implementations
701//===----------------------------------------------------------------------===//
702
Dan Gohman0bba49c2009-07-07 17:06:11 +0000703const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000704 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000705 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000706 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000707 assert(isSCEVable(Ty) &&
708 "This is not a conversion to a SCEVable type!");
709 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000710
Dan Gohmanc050fd92009-07-13 20:50:19 +0000711 FoldingSetNodeID ID;
712 ID.AddInteger(scTruncate);
713 ID.AddPointer(Op);
714 ID.AddPointer(Ty);
715 void *IP = 0;
716 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
717
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000718 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000719 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000720 return getConstant(
721 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000722
Dan Gohman20900ca2009-04-22 16:20:48 +0000723 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000724 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000725 return getTruncateExpr(ST->getOperand(), Ty);
726
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000727 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000728 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000729 return getTruncateOrSignExtend(SS->getOperand(), Ty);
730
731 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000732 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000733 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
734
Dan Gohman6864db62009-06-18 16:24:47 +0000735 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000736 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000737 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000738 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000739 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
740 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000741 }
742
Dan Gohmanc050fd92009-07-13 20:50:19 +0000743 // The cast wasn't folded; create an explicit cast node.
744 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000745 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
746 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000747 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000748 UniqueSCEVs.InsertNode(S, IP);
749 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000750}
751
Dan Gohman0bba49c2009-07-07 17:06:11 +0000752const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000753 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000754 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000755 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000756 assert(isSCEVable(Ty) &&
757 "This is not a conversion to a SCEVable type!");
758 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000759
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000760 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000761 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000762 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000763 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
764 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000765 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000766 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000767
Dan Gohman20900ca2009-04-22 16:20:48 +0000768 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000769 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000770 return getZeroExtendExpr(SZ->getOperand(), Ty);
771
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000772 // Before doing any expensive analysis, check to see if we've already
773 // computed a SCEV for this Op and Ty.
774 FoldingSetNodeID ID;
775 ID.AddInteger(scZeroExtend);
776 ID.AddPointer(Op);
777 ID.AddPointer(Ty);
778 void *IP = 0;
779 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
780
Dan Gohman01ecca22009-04-27 20:16:15 +0000781 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000782 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000783 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000784 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000785 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000786 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000787 const SCEV *Start = AR->getStart();
788 const SCEV *Step = AR->getStepRecurrence(*this);
789 unsigned BitWidth = getTypeSizeInBits(AR->getType());
790 const Loop *L = AR->getLoop();
791
Dan Gohmaneb490a72009-07-25 01:22:26 +0000792 // If we have special knowledge that this addrec won't overflow,
793 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000794 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000795 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
796 getZeroExtendExpr(Step, Ty),
797 L);
798
Dan Gohman01ecca22009-04-27 20:16:15 +0000799 // Check whether the backedge-taken count is SCEVCouldNotCompute.
800 // Note that this serves two purposes: It filters out loops that are
801 // simply not analyzable, and it covers the case where this code is
802 // being called from within backedge-taken count analysis, such that
803 // attempting to ask for the backedge-taken count would likely result
804 // in infinite recursion. In the later case, the analysis code will
805 // cope with a conservative value, and it will take care to purge
806 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000807 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000808 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000809 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000810 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000811
812 // Check whether the backedge-taken count can be losslessly casted to
813 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000814 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000815 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000816 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000817 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
818 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000819 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000820 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000821 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000822 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000823 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000824 const SCEV *Add = getAddExpr(Start, ZMul);
825 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000826 getAddExpr(getZeroExtendExpr(Start, WideTy),
827 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
828 getZeroExtendExpr(Step, WideTy)));
829 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000830 // Return the expression with the addrec on the outside.
831 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
832 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000833 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000834
835 // Similar to above, only this time treat the step value as signed.
836 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000837 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000838 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000839 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000840 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000841 OperandExtendedAdd =
842 getAddExpr(getZeroExtendExpr(Start, WideTy),
843 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
844 getSignExtendExpr(Step, WideTy)));
845 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000846 // Return the expression with the addrec on the outside.
847 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
848 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000849 L);
850 }
851
852 // If the backedge is guarded by a comparison with the pre-inc value
853 // the addrec is safe. Also, if the entry is guarded by a comparison
854 // with the start value and the backedge is guarded by a comparison
855 // with the post-inc value, the addrec is safe.
856 if (isKnownPositive(Step)) {
857 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
858 getUnsignedRange(Step).getUnsignedMax());
859 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
860 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
861 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
862 AR->getPostIncExpr(*this), N)))
863 // Return the expression with the addrec on the outside.
864 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
865 getZeroExtendExpr(Step, Ty),
866 L);
867 } else if (isKnownNegative(Step)) {
868 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
869 getSignedRange(Step).getSignedMin());
870 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
871 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
872 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
873 AR->getPostIncExpr(*this), N)))
874 // Return the expression with the addrec on the outside.
875 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
876 getSignExtendExpr(Step, Ty),
877 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000878 }
879 }
880 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000881
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000882 // The cast wasn't folded; create an explicit cast node.
883 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000884 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
885 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000886 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000887 UniqueSCEVs.InsertNode(S, IP);
888 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000889}
890
Dan Gohman0bba49c2009-07-07 17:06:11 +0000891const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000892 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000893 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000894 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000895 assert(isSCEVable(Ty) &&
896 "This is not a conversion to a SCEVable type!");
897 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000898
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000899 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000900 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000901 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000902 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
903 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000904 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000905 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000906
Dan Gohman20900ca2009-04-22 16:20:48 +0000907 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000908 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000909 return getSignExtendExpr(SS->getOperand(), Ty);
910
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000911 // Before doing any expensive analysis, check to see if we've already
912 // computed a SCEV for this Op and Ty.
913 FoldingSetNodeID ID;
914 ID.AddInteger(scSignExtend);
915 ID.AddPointer(Op);
916 ID.AddPointer(Ty);
917 void *IP = 0;
918 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
919
Dan Gohman01ecca22009-04-27 20:16:15 +0000920 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000921 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000922 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000923 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000924 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000925 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000926 const SCEV *Start = AR->getStart();
927 const SCEV *Step = AR->getStepRecurrence(*this);
928 unsigned BitWidth = getTypeSizeInBits(AR->getType());
929 const Loop *L = AR->getLoop();
930
Dan Gohmaneb490a72009-07-25 01:22:26 +0000931 // If we have special knowledge that this addrec won't overflow,
932 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000933 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000934 return getAddRecExpr(getSignExtendExpr(Start, Ty),
935 getSignExtendExpr(Step, Ty),
936 L);
937
Dan Gohman01ecca22009-04-27 20:16:15 +0000938 // Check whether the backedge-taken count is SCEVCouldNotCompute.
939 // Note that this serves two purposes: It filters out loops that are
940 // simply not analyzable, and it covers the case where this code is
941 // being called from within backedge-taken count analysis, such that
942 // attempting to ask for the backedge-taken count would likely result
943 // in infinite recursion. In the later case, the analysis code will
944 // cope with a conservative value, and it will take care to purge
945 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000946 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000947 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000948 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000949 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000950
951 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000952 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000953 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000954 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000955 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000956 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
957 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000958 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000959 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000960 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000961 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000962 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000963 const SCEV *Add = getAddExpr(Start, SMul);
964 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000965 getAddExpr(getSignExtendExpr(Start, WideTy),
966 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
967 getSignExtendExpr(Step, WideTy)));
968 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000969 // Return the expression with the addrec on the outside.
970 return getAddRecExpr(getSignExtendExpr(Start, Ty),
971 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000972 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000973
974 // Similar to above, only this time treat the step value as unsigned.
975 // This covers loops that count up with an unsigned step.
976 const SCEV *UMul =
977 getMulExpr(CastedMaxBECount,
978 getTruncateOrZeroExtend(Step, Start->getType()));
979 Add = getAddExpr(Start, UMul);
980 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +0000981 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +0000982 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
983 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +0000984 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +0000985 // Return the expression with the addrec on the outside.
986 return getAddRecExpr(getSignExtendExpr(Start, Ty),
987 getZeroExtendExpr(Step, Ty),
988 L);
Dan Gohman85b05a22009-07-13 21:35:55 +0000989 }
990
991 // If the backedge is guarded by a comparison with the pre-inc value
992 // the addrec is safe. Also, if the entry is guarded by a comparison
993 // with the start value and the backedge is guarded by a comparison
994 // with the post-inc value, the addrec is safe.
995 if (isKnownPositive(Step)) {
996 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
997 getSignedRange(Step).getSignedMax());
998 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
999 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1000 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1001 AR->getPostIncExpr(*this), N)))
1002 // Return the expression with the addrec on the outside.
1003 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1004 getSignExtendExpr(Step, Ty),
1005 L);
1006 } else if (isKnownNegative(Step)) {
1007 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1008 getSignedRange(Step).getSignedMin());
1009 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1010 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1011 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1012 AR->getPostIncExpr(*this), N)))
1013 // Return the expression with the addrec on the outside.
1014 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1015 getSignExtendExpr(Step, Ty),
1016 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001017 }
1018 }
1019 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001020
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001021 // The cast wasn't folded; create an explicit cast node.
1022 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001023 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1024 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001025 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001026 UniqueSCEVs.InsertNode(S, IP);
1027 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001028}
1029
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001030/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1031/// unspecified bits out to the given type.
1032///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001033const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001034 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001035 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1036 "This is not an extending conversion!");
1037 assert(isSCEVable(Ty) &&
1038 "This is not a conversion to a SCEVable type!");
1039 Ty = getEffectiveSCEVType(Ty);
1040
1041 // Sign-extend negative constants.
1042 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1043 if (SC->getValue()->getValue().isNegative())
1044 return getSignExtendExpr(Op, Ty);
1045
1046 // Peel off a truncate cast.
1047 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001048 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001049 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1050 return getAnyExtendExpr(NewOp, Ty);
1051 return getTruncateOrNoop(NewOp, Ty);
1052 }
1053
1054 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001055 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001056 if (!isa<SCEVZeroExtendExpr>(ZExt))
1057 return ZExt;
1058
1059 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001060 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001061 if (!isa<SCEVSignExtendExpr>(SExt))
1062 return SExt;
1063
1064 // If the expression is obviously signed, use the sext cast value.
1065 if (isa<SCEVSMaxExpr>(Op))
1066 return SExt;
1067
1068 // Absent any other information, use the zext cast value.
1069 return ZExt;
1070}
1071
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001072/// CollectAddOperandsWithScales - Process the given Ops list, which is
1073/// a list of operands to be added under the given scale, update the given
1074/// map. This is a helper function for getAddRecExpr. As an example of
1075/// what it does, given a sequence of operands that would form an add
1076/// expression like this:
1077///
1078/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1079///
1080/// where A and B are constants, update the map with these values:
1081///
1082/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1083///
1084/// and add 13 + A*B*29 to AccumulatedConstant.
1085/// This will allow getAddRecExpr to produce this:
1086///
1087/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1088///
1089/// This form often exposes folding opportunities that are hidden in
1090/// the original operand list.
1091///
1092/// Return true iff it appears that any interesting folding opportunities
1093/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1094/// the common case where no interesting opportunities are present, and
1095/// is also used as a check to avoid infinite recursion.
1096///
1097static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001098CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1099 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001100 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001101 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001102 const APInt &Scale,
1103 ScalarEvolution &SE) {
1104 bool Interesting = false;
1105
1106 // Iterate over the add operands.
1107 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1108 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1109 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1110 APInt NewScale =
1111 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1112 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1113 // A multiplication of a constant with another add; recurse.
1114 Interesting |=
1115 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1116 cast<SCEVAddExpr>(Mul->getOperand(1))
1117 ->getOperands(),
1118 NewScale, SE);
1119 } else {
1120 // A multiplication of a constant with some other value. Update
1121 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001122 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1123 const SCEV *Key = SE.getMulExpr(MulOps);
1124 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001125 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001126 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001127 NewOps.push_back(Pair.first->first);
1128 } else {
1129 Pair.first->second += NewScale;
1130 // The map already had an entry for this value, which may indicate
1131 // a folding opportunity.
1132 Interesting = true;
1133 }
1134 }
1135 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1136 // Pull a buried constant out to the outside.
1137 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1138 Interesting = true;
1139 AccumulatedConstant += Scale * C->getValue()->getValue();
1140 } else {
1141 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001142 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001143 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001144 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001145 NewOps.push_back(Pair.first->first);
1146 } else {
1147 Pair.first->second += Scale;
1148 // The map already had an entry for this value, which may indicate
1149 // a folding opportunity.
1150 Interesting = true;
1151 }
1152 }
1153 }
1154
1155 return Interesting;
1156}
1157
1158namespace {
1159 struct APIntCompare {
1160 bool operator()(const APInt &LHS, const APInt &RHS) const {
1161 return LHS.ult(RHS);
1162 }
1163 };
1164}
1165
Dan Gohman6c0866c2009-05-24 23:45:28 +00001166/// getAddExpr - Get a canonical add expression, or something simpler if
1167/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001168const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001169 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001170 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001171#ifndef NDEBUG
1172 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1173 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1174 getEffectiveSCEVType(Ops[0]->getType()) &&
1175 "SCEVAddExpr operand types don't match!");
1176#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001177
1178 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001179 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001180
1181 // If there are any constants, fold them together.
1182 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001183 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001184 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001185 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001186 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001188 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1189 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001190 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001191 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001192 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001193 }
1194
1195 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001196 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001197 Ops.erase(Ops.begin());
1198 --Idx;
1199 }
1200 }
1201
Chris Lattner627018b2004-04-07 16:16:11 +00001202 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001203
Chris Lattner53e677a2004-04-02 20:23:17 +00001204 // Okay, check to see if the same value occurs in the operand list twice. If
1205 // so, merge them together into an multiply expression. Since we sorted the
1206 // list, these values are required to be adjacent.
1207 const Type *Ty = Ops[0]->getType();
1208 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1209 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1210 // Found a match, merge the two values into a multiply, and add any
1211 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001212 const SCEV *Two = getIntegerSCEV(2, Ty);
1213 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001214 if (Ops.size() == 2)
1215 return Mul;
1216 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1217 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001218 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 }
1220
Dan Gohman728c7f32009-05-08 21:03:19 +00001221 // Check for truncates. If all the operands are truncated from the same
1222 // type, see if factoring out the truncate would permit the result to be
1223 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1224 // if the contents of the resulting outer trunc fold to something simple.
1225 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1226 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1227 const Type *DstType = Trunc->getType();
1228 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001229 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001230 bool Ok = true;
1231 // Check all the operands to see if they can be represented in the
1232 // source type of the truncate.
1233 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1234 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1235 if (T->getOperand()->getType() != SrcType) {
1236 Ok = false;
1237 break;
1238 }
1239 LargeOps.push_back(T->getOperand());
1240 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1241 // This could be either sign or zero extension, but sign extension
1242 // is much more likely to be foldable here.
1243 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1244 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001245 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001246 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1247 if (const SCEVTruncateExpr *T =
1248 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1249 if (T->getOperand()->getType() != SrcType) {
1250 Ok = false;
1251 break;
1252 }
1253 LargeMulOps.push_back(T->getOperand());
1254 } else if (const SCEVConstant *C =
1255 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1256 // This could be either sign or zero extension, but sign extension
1257 // is much more likely to be foldable here.
1258 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1259 } else {
1260 Ok = false;
1261 break;
1262 }
1263 }
1264 if (Ok)
1265 LargeOps.push_back(getMulExpr(LargeMulOps));
1266 } else {
1267 Ok = false;
1268 break;
1269 }
1270 }
1271 if (Ok) {
1272 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001273 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001274 // If it folds to something simple, use it. Otherwise, don't.
1275 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1276 return getTruncateExpr(Fold, DstType);
1277 }
1278 }
1279
1280 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1282 ++Idx;
1283
1284 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001285 if (Idx < Ops.size()) {
1286 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001287 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001288 // If we have an add, expand the add operands onto the end of the operands
1289 // list.
1290 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1291 Ops.erase(Ops.begin()+Idx);
1292 DeletedAdd = true;
1293 }
1294
1295 // If we deleted at least one add, we added operands to the end of the list,
1296 // and they are not necessarily sorted. Recurse to resort and resimplify
1297 // any operands we just aquired.
1298 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001299 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 }
1301
1302 // Skip over the add expression until we get to a multiply.
1303 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1304 ++Idx;
1305
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001306 // Check to see if there are any folding opportunities present with
1307 // operands multiplied by constant values.
1308 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1309 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001310 DenseMap<const SCEV *, APInt> M;
1311 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001312 APInt AccumulatedConstant(BitWidth, 0);
1313 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1314 Ops, APInt(BitWidth, 1), *this)) {
1315 // Some interesting folding opportunity is present, so its worthwhile to
1316 // re-generate the operands list. Group the operands by constant scale,
1317 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001318 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1319 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001320 E = NewOps.end(); I != E; ++I)
1321 MulOpLists[M.find(*I)->second].push_back(*I);
1322 // Re-generate the operands list.
1323 Ops.clear();
1324 if (AccumulatedConstant != 0)
1325 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001326 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1327 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001328 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001329 Ops.push_back(getMulExpr(getConstant(I->first),
1330 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001331 if (Ops.empty())
1332 return getIntegerSCEV(0, Ty);
1333 if (Ops.size() == 1)
1334 return Ops[0];
1335 return getAddExpr(Ops);
1336 }
1337 }
1338
Chris Lattner53e677a2004-04-02 20:23:17 +00001339 // If we are adding something to a multiply expression, make sure the
1340 // something is not already an operand of the multiply. If so, merge it into
1341 // the multiply.
1342 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001343 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001344 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001345 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001346 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001347 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001348 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001349 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001350 if (Mul->getNumOperands() != 2) {
1351 // If the multiply has more than two operands, we must get the
1352 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001353 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001354 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001355 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001356 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001357 const SCEV *One = getIntegerSCEV(1, Ty);
1358 const SCEV *AddOne = getAddExpr(InnerMul, One);
1359 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 if (Ops.size() == 2) return OuterMul;
1361 if (AddOp < Idx) {
1362 Ops.erase(Ops.begin()+AddOp);
1363 Ops.erase(Ops.begin()+Idx-1);
1364 } else {
1365 Ops.erase(Ops.begin()+Idx);
1366 Ops.erase(Ops.begin()+AddOp-1);
1367 }
1368 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001369 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001370 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001371
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 // Check this multiply against other multiplies being added together.
1373 for (unsigned OtherMulIdx = Idx+1;
1374 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1375 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001376 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 // If MulOp occurs in OtherMul, we can fold the two multiplies
1378 // together.
1379 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1380 OMulOp != e; ++OMulOp)
1381 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1382 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001383 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001384 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001385 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1386 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001387 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001388 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001390 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001391 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001392 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1393 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001394 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001395 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001397 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1398 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001399 if (Ops.size() == 2) return OuterMul;
1400 Ops.erase(Ops.begin()+Idx);
1401 Ops.erase(Ops.begin()+OtherMulIdx-1);
1402 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001403 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 }
1405 }
1406 }
1407 }
1408
1409 // If there are any add recurrences in the operands list, see if any other
1410 // added values are loop invariant. If so, we can fold them into the
1411 // recurrence.
1412 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1413 ++Idx;
1414
1415 // Scan over all recurrences, trying to fold loop invariants into them.
1416 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1417 // Scan all of the other operands to this add and add them to the vector if
1418 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001419 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001420 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001421 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1422 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1423 LIOps.push_back(Ops[i]);
1424 Ops.erase(Ops.begin()+i);
1425 --i; --e;
1426 }
1427
1428 // If we found some loop invariants, fold them into the recurrence.
1429 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001430 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001431 LIOps.push_back(AddRec->getStart());
1432
Dan Gohman0bba49c2009-07-07 17:06:11 +00001433 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001434 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001435 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001436
Dan Gohman0bba49c2009-07-07 17:06:11 +00001437 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001438 // If all of the other operands were loop invariant, we are done.
1439 if (Ops.size() == 1) return NewRec;
1440
1441 // Otherwise, add the folded AddRec by the non-liv parts.
1442 for (unsigned i = 0;; ++i)
1443 if (Ops[i] == AddRec) {
1444 Ops[i] = NewRec;
1445 break;
1446 }
Dan Gohman246b2562007-10-22 18:31:58 +00001447 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001448 }
1449
1450 // Okay, if there weren't any loop invariants to be folded, check to see if
1451 // there are multiple AddRec's with the same loop induction variable being
1452 // added together. If so, we can fold them.
1453 for (unsigned OtherIdx = Idx+1;
1454 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1455 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001456 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001457 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1458 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001459 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1460 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001461 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1462 if (i >= NewOps.size()) {
1463 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1464 OtherAddRec->op_end());
1465 break;
1466 }
Dan Gohman246b2562007-10-22 18:31:58 +00001467 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001469 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001470
1471 if (Ops.size() == 2) return NewAddRec;
1472
1473 Ops.erase(Ops.begin()+Idx);
1474 Ops.erase(Ops.begin()+OtherIdx-1);
1475 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001476 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 }
1478 }
1479
1480 // Otherwise couldn't fold anything into this recurrence. Move onto the
1481 // next one.
1482 }
1483
1484 // Okay, it looks like we really DO need an add expr. Check to see if we
1485 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001486 FoldingSetNodeID ID;
1487 ID.AddInteger(scAddExpr);
1488 ID.AddInteger(Ops.size());
1489 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1490 ID.AddPointer(Ops[i]);
1491 void *IP = 0;
1492 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1493 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001494 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001495 UniqueSCEVs.InsertNode(S, IP);
1496 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001497}
1498
1499
Dan Gohman6c0866c2009-05-24 23:45:28 +00001500/// getMulExpr - Get a canonical multiply expression, or something simpler if
1501/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001502const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001504#ifndef NDEBUG
1505 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1506 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1507 getEffectiveSCEVType(Ops[0]->getType()) &&
1508 "SCEVMulExpr operand types don't match!");
1509#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001510
1511 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001512 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001513
1514 // If there are any constants, fold them together.
1515 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001516 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001517
1518 // C1*(C2+V) -> C1*C2 + C1*V
1519 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001520 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001521 if (Add->getNumOperands() == 2 &&
1522 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001523 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1524 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001525
1526
1527 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001528 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001529 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001530 ConstantInt *Fold = ConstantInt::get(getContext(),
1531 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001532 RHSC->getValue()->getValue());
1533 Ops[0] = getConstant(Fold);
1534 Ops.erase(Ops.begin()+1); // Erase the folded element
1535 if (Ops.size() == 1) return Ops[0];
1536 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 }
1538
1539 // If we are left with a constant one being multiplied, strip it off.
1540 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1541 Ops.erase(Ops.begin());
1542 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001543 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 // If we have a multiply of zero, it will always be zero.
1545 return Ops[0];
1546 }
1547 }
1548
1549 // Skip over the add expression until we get to a multiply.
1550 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1551 ++Idx;
1552
1553 if (Ops.size() == 1)
1554 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001555
Chris Lattner53e677a2004-04-02 20:23:17 +00001556 // If there are mul operands inline them all into this expression.
1557 if (Idx < Ops.size()) {
1558 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001559 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001560 // If we have an mul, expand the mul operands onto the end of the operands
1561 // list.
1562 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1563 Ops.erase(Ops.begin()+Idx);
1564 DeletedMul = true;
1565 }
1566
1567 // If we deleted at least one mul, we added operands to the end of the list,
1568 // and they are not necessarily sorted. Recurse to resort and resimplify
1569 // any operands we just aquired.
1570 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001571 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 }
1573
1574 // If there are any add recurrences in the operands list, see if any other
1575 // added values are loop invariant. If so, we can fold them into the
1576 // recurrence.
1577 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1578 ++Idx;
1579
1580 // Scan over all recurrences, trying to fold loop invariants into them.
1581 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1582 // Scan all of the other operands to this mul and add them to the vector if
1583 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001584 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001585 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1587 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1588 LIOps.push_back(Ops[i]);
1589 Ops.erase(Ops.begin()+i);
1590 --i; --e;
1591 }
1592
1593 // If we found some loop invariants, fold them into the recurrence.
1594 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001595 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001596 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 NewOps.reserve(AddRec->getNumOperands());
1598 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001599 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001600 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001601 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 } else {
1603 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001604 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001606 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001607 }
1608 }
1609
Dan Gohman0bba49c2009-07-07 17:06:11 +00001610 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001611
1612 // If all of the other operands were loop invariant, we are done.
1613 if (Ops.size() == 1) return NewRec;
1614
1615 // Otherwise, multiply the folded AddRec by the non-liv parts.
1616 for (unsigned i = 0;; ++i)
1617 if (Ops[i] == AddRec) {
1618 Ops[i] = NewRec;
1619 break;
1620 }
Dan Gohman246b2562007-10-22 18:31:58 +00001621 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001622 }
1623
1624 // Okay, if there weren't any loop invariants to be folded, check to see if
1625 // there are multiple AddRec's with the same loop induction variable being
1626 // multiplied together. If so, we can fold them.
1627 for (unsigned OtherIdx = Idx+1;
1628 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1629 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001630 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001631 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1632 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001633 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001634 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001636 const SCEV *B = F->getStepRecurrence(*this);
1637 const SCEV *D = G->getStepRecurrence(*this);
1638 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001639 getMulExpr(G, B),
1640 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001641 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001642 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001643 if (Ops.size() == 2) return NewAddRec;
1644
1645 Ops.erase(Ops.begin()+Idx);
1646 Ops.erase(Ops.begin()+OtherIdx-1);
1647 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001648 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001649 }
1650 }
1651
1652 // Otherwise couldn't fold anything into this recurrence. Move onto the
1653 // next one.
1654 }
1655
1656 // Okay, it looks like we really DO need an mul expr. Check to see if we
1657 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001658 FoldingSetNodeID ID;
1659 ID.AddInteger(scMulExpr);
1660 ID.AddInteger(Ops.size());
1661 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1662 ID.AddPointer(Ops[i]);
1663 void *IP = 0;
1664 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1665 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001666 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001667 UniqueSCEVs.InsertNode(S, IP);
1668 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001669}
1670
Andreas Bolka8a11c982009-08-07 22:55:26 +00001671/// getUDivExpr - Get a canonical unsigned division expression, or something
1672/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001673const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1674 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001675 assert(getEffectiveSCEVType(LHS->getType()) ==
1676 getEffectiveSCEVType(RHS->getType()) &&
1677 "SCEVUDivExpr operand types don't match!");
1678
Dan Gohman622ed672009-05-04 22:02:23 +00001679 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001681 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001682 if (RHSC->isZero())
1683 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001684
Dan Gohman185cf032009-05-08 20:18:49 +00001685 // Determine if the division can be folded into the operands of
1686 // its operands.
1687 // TODO: Generalize this to non-constants by using known-bits information.
1688 const Type *Ty = LHS->getType();
1689 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1690 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1691 // For non-power-of-two values, effectively round the value up to the
1692 // nearest power of two.
1693 if (!RHSC->getValue()->getValue().isPowerOf2())
1694 ++MaxShiftAmt;
1695 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001696 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001697 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1698 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1699 if (const SCEVConstant *Step =
1700 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1701 if (!Step->getValue()->getValue()
1702 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001703 getZeroExtendExpr(AR, ExtTy) ==
1704 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1705 getZeroExtendExpr(Step, ExtTy),
1706 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001707 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001708 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1709 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1710 return getAddRecExpr(Operands, AR->getLoop());
1711 }
1712 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001713 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001714 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001715 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1716 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1717 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001718 // Find an operand that's safely divisible.
1719 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001720 const SCEV *Op = M->getOperand(i);
1721 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001722 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001723 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1724 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001725 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001726 Operands[i] = Div;
1727 return getMulExpr(Operands);
1728 }
1729 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001730 }
Dan Gohman185cf032009-05-08 20:18:49 +00001731 // (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 +00001732 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001733 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001734 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1735 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1736 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1737 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001738 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001739 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001740 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1741 break;
1742 Operands.push_back(Op);
1743 }
1744 if (Operands.size() == A->getNumOperands())
1745 return getAddExpr(Operands);
1746 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001747 }
Dan Gohman185cf032009-05-08 20:18:49 +00001748
1749 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001750 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 Constant *LHSCV = LHSC->getValue();
1752 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001753 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001754 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001755 }
1756 }
1757
Dan Gohman1c343752009-06-27 21:21:31 +00001758 FoldingSetNodeID ID;
1759 ID.AddInteger(scUDivExpr);
1760 ID.AddPointer(LHS);
1761 ID.AddPointer(RHS);
1762 void *IP = 0;
1763 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1764 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001765 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001766 UniqueSCEVs.InsertNode(S, IP);
1767 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001768}
1769
1770
Dan Gohman6c0866c2009-05-24 23:45:28 +00001771/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1772/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001773const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohmand1e5db62009-07-24 01:03:59 +00001774 const SCEV *Step, const Loop *L) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001775 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001776 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001777 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001778 if (StepChrec->getLoop() == L) {
1779 Operands.insert(Operands.end(), StepChrec->op_begin(),
1780 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001781 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001782 }
1783
1784 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001785 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001786}
1787
Dan Gohman6c0866c2009-05-24 23:45:28 +00001788/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1789/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001790const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001791ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001792 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001793 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001794#ifndef NDEBUG
1795 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1796 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1797 getEffectiveSCEVType(Operands[0]->getType()) &&
1798 "SCEVAddRecExpr operand types don't match!");
1799#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001800
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001801 if (Operands.back()->isZero()) {
1802 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001803 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001804 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001805
Dan Gohmand9cc7492008-08-08 18:33:12 +00001806 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001807 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001808 const Loop* NestedLoop = NestedAR->getLoop();
1809 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001810 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001811 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001812 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001813 // AddRecs require their operands be loop-invariant with respect to their
1814 // loops. Don't perform this transformation if it would break this
1815 // requirement.
1816 bool AllInvariant = true;
1817 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1818 if (!Operands[i]->isLoopInvariant(L)) {
1819 AllInvariant = false;
1820 break;
1821 }
1822 if (AllInvariant) {
1823 NestedOperands[0] = getAddRecExpr(Operands, L);
1824 AllInvariant = true;
1825 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1826 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1827 AllInvariant = false;
1828 break;
1829 }
1830 if (AllInvariant)
1831 // Ok, both add recurrences are valid after the transformation.
1832 return getAddRecExpr(NestedOperands, NestedLoop);
1833 }
1834 // Reset Operands to its original state.
1835 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001836 }
1837 }
1838
Dan Gohman1c343752009-06-27 21:21:31 +00001839 FoldingSetNodeID ID;
1840 ID.AddInteger(scAddRecExpr);
1841 ID.AddInteger(Operands.size());
1842 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1843 ID.AddPointer(Operands[i]);
1844 ID.AddPointer(L);
1845 void *IP = 0;
1846 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1847 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001848 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001849 UniqueSCEVs.InsertNode(S, IP);
1850 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001851}
1852
Dan Gohman9311ef62009-06-24 14:49:00 +00001853const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1854 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001855 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001856 Ops.push_back(LHS);
1857 Ops.push_back(RHS);
1858 return getSMaxExpr(Ops);
1859}
1860
Dan Gohman0bba49c2009-07-07 17:06:11 +00001861const SCEV *
1862ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001863 assert(!Ops.empty() && "Cannot get empty smax!");
1864 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001865#ifndef NDEBUG
1866 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1867 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1868 getEffectiveSCEVType(Ops[0]->getType()) &&
1869 "SCEVSMaxExpr operand types don't match!");
1870#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001871
1872 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001873 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001874
1875 // If there are any constants, fold them together.
1876 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001877 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001878 ++Idx;
1879 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001880 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001881 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001882 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001883 APIntOps::smax(LHSC->getValue()->getValue(),
1884 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001885 Ops[0] = getConstant(Fold);
1886 Ops.erase(Ops.begin()+1); // Erase the folded element
1887 if (Ops.size() == 1) return Ops[0];
1888 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001889 }
1890
Dan Gohmane5aceed2009-06-24 14:46:22 +00001891 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001892 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1893 Ops.erase(Ops.begin());
1894 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001895 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1896 // If we have an smax with a constant maximum-int, it will always be
1897 // maximum-int.
1898 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001899 }
1900 }
1901
1902 if (Ops.size() == 1) return Ops[0];
1903
1904 // Find the first SMax
1905 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1906 ++Idx;
1907
1908 // Check to see if one of the operands is an SMax. If so, expand its operands
1909 // onto our operand list, and recurse to simplify.
1910 if (Idx < Ops.size()) {
1911 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001912 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001913 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1914 Ops.erase(Ops.begin()+Idx);
1915 DeletedSMax = true;
1916 }
1917
1918 if (DeletedSMax)
1919 return getSMaxExpr(Ops);
1920 }
1921
1922 // Okay, check to see if the same value occurs in the operand list twice. If
1923 // so, delete one. Since we sorted the list, these values are required to
1924 // be adjacent.
1925 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1926 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1927 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1928 --i; --e;
1929 }
1930
1931 if (Ops.size() == 1) return Ops[0];
1932
1933 assert(!Ops.empty() && "Reduced smax down to nothing!");
1934
Nick Lewycky3e630762008-02-20 06:48:22 +00001935 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001936 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001937 FoldingSetNodeID ID;
1938 ID.AddInteger(scSMaxExpr);
1939 ID.AddInteger(Ops.size());
1940 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1941 ID.AddPointer(Ops[i]);
1942 void *IP = 0;
1943 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1944 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001945 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001946 UniqueSCEVs.InsertNode(S, IP);
1947 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001948}
1949
Dan Gohman9311ef62009-06-24 14:49:00 +00001950const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1951 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001952 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001953 Ops.push_back(LHS);
1954 Ops.push_back(RHS);
1955 return getUMaxExpr(Ops);
1956}
1957
Dan Gohman0bba49c2009-07-07 17:06:11 +00001958const SCEV *
1959ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001960 assert(!Ops.empty() && "Cannot get empty umax!");
1961 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001962#ifndef NDEBUG
1963 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1964 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1965 getEffectiveSCEVType(Ops[0]->getType()) &&
1966 "SCEVUMaxExpr operand types don't match!");
1967#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001968
1969 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001970 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001971
1972 // If there are any constants, fold them together.
1973 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001974 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001975 ++Idx;
1976 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001977 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001978 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001979 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00001980 APIntOps::umax(LHSC->getValue()->getValue(),
1981 RHSC->getValue()->getValue()));
1982 Ops[0] = getConstant(Fold);
1983 Ops.erase(Ops.begin()+1); // Erase the folded element
1984 if (Ops.size() == 1) return Ops[0];
1985 LHSC = cast<SCEVConstant>(Ops[0]);
1986 }
1987
Dan Gohmane5aceed2009-06-24 14:46:22 +00001988 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001989 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1990 Ops.erase(Ops.begin());
1991 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001992 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1993 // If we have an umax with a constant maximum-int, it will always be
1994 // maximum-int.
1995 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001996 }
1997 }
1998
1999 if (Ops.size() == 1) return Ops[0];
2000
2001 // Find the first UMax
2002 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2003 ++Idx;
2004
2005 // Check to see if one of the operands is a UMax. If so, expand its operands
2006 // onto our operand list, and recurse to simplify.
2007 if (Idx < Ops.size()) {
2008 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002009 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002010 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2011 Ops.erase(Ops.begin()+Idx);
2012 DeletedUMax = true;
2013 }
2014
2015 if (DeletedUMax)
2016 return getUMaxExpr(Ops);
2017 }
2018
2019 // Okay, check to see if the same value occurs in the operand list twice. If
2020 // so, delete one. Since we sorted the list, these values are required to
2021 // be adjacent.
2022 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2023 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2024 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2025 --i; --e;
2026 }
2027
2028 if (Ops.size() == 1) return Ops[0];
2029
2030 assert(!Ops.empty() && "Reduced umax down to nothing!");
2031
2032 // Okay, it looks like we really DO need a umax expr. Check to see if we
2033 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002034 FoldingSetNodeID ID;
2035 ID.AddInteger(scUMaxExpr);
2036 ID.AddInteger(Ops.size());
2037 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2038 ID.AddPointer(Ops[i]);
2039 void *IP = 0;
2040 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2041 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002042 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002043 UniqueSCEVs.InsertNode(S, IP);
2044 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002045}
2046
Dan Gohman9311ef62009-06-24 14:49:00 +00002047const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2048 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002049 // ~smax(~x, ~y) == smin(x, y).
2050 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2051}
2052
Dan Gohman9311ef62009-06-24 14:49:00 +00002053const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2054 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002055 // ~umax(~x, ~y) == umin(x, y)
2056 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2057}
2058
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002059const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2060 unsigned FieldNo) {
2061 // If we have TargetData we can determine the constant offset.
2062 if (TD) {
2063 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2064 const StructLayout &SL = *TD->getStructLayout(STy);
2065 uint64_t Offset = SL.getElementOffset(FieldNo);
2066 return getIntegerSCEV(Offset, IntPtrTy);
2067 }
2068
2069 // Field 0 is always at offset 0.
2070 if (FieldNo == 0) {
2071 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2072 return getIntegerSCEV(0, Ty);
2073 }
2074
2075 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2076 // already have one, otherwise create a new one.
2077 FoldingSetNodeID ID;
2078 ID.AddInteger(scFieldOffset);
2079 ID.AddPointer(STy);
2080 ID.AddInteger(FieldNo);
2081 void *IP = 0;
2082 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2083 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2084 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2085 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2086 UniqueSCEVs.InsertNode(S, IP);
2087 return S;
2088}
2089
2090const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2091 // If we have TargetData we can determine the constant size.
2092 if (TD && AllocTy->isSized()) {
2093 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2094 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2095 }
2096
2097 // Expand an array size into the element size times the number
2098 // of elements.
2099 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2100 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2101 return getMulExpr(
2102 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2103 ATy->getNumElements())));
2104 }
2105
2106 // Expand a vector size into the element size times the number
2107 // of elements.
2108 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2109 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2110 return getMulExpr(
2111 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2112 VTy->getNumElements())));
2113 }
2114
2115 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2116 // already have one, otherwise create a new one.
2117 FoldingSetNodeID ID;
2118 ID.AddInteger(scAllocSize);
2119 ID.AddPointer(AllocTy);
2120 void *IP = 0;
2121 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2122 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2123 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2124 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2125 UniqueSCEVs.InsertNode(S, IP);
2126 return S;
2127}
2128
Dan Gohman0bba49c2009-07-07 17:06:11 +00002129const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002130 // Don't attempt to do anything other than create a SCEVUnknown object
2131 // here. createSCEV only calls getUnknown after checking for all other
2132 // interesting possibilities, and any other code that calls getUnknown
2133 // is doing so in order to hide a value from SCEV canonicalization.
2134
Dan Gohman1c343752009-06-27 21:21:31 +00002135 FoldingSetNodeID ID;
2136 ID.AddInteger(scUnknown);
2137 ID.AddPointer(V);
2138 void *IP = 0;
2139 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2140 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002141 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002142 UniqueSCEVs.InsertNode(S, IP);
2143 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002144}
2145
Chris Lattner53e677a2004-04-02 20:23:17 +00002146//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002147// Basic SCEV Analysis and PHI Idiom Recognition Code
2148//
2149
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002150/// isSCEVable - Test if values of the given type are analyzable within
2151/// the SCEV framework. This primarily includes integer types, and it
2152/// can optionally include pointer types if the ScalarEvolution class
2153/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002154bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002155 // Integers and pointers are always SCEVable.
2156 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002157}
2158
2159/// getTypeSizeInBits - Return the size in bits of the specified type,
2160/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002161uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002162 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2163
2164 // If we have a TargetData, use it!
2165 if (TD)
2166 return TD->getTypeSizeInBits(Ty);
2167
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002168 // Integer types have fixed sizes.
2169 if (Ty->isInteger())
2170 return Ty->getPrimitiveSizeInBits();
2171
2172 // The only other support type is pointer. Without TargetData, conservatively
2173 // assume pointers are 64-bit.
2174 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2175 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002176}
2177
2178/// getEffectiveSCEVType - Return a type with the same bitwidth as
2179/// the given type and which represents how SCEV will treat the given
2180/// type, for which isSCEVable must return true. For pointer types,
2181/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002182const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002183 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2184
2185 if (Ty->isInteger())
2186 return Ty;
2187
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002188 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002189 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002190 if (TD) return TD->getIntPtrType(getContext());
2191
2192 // Without TargetData, conservatively assume pointers are 64-bit.
2193 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002194}
Chris Lattner53e677a2004-04-02 20:23:17 +00002195
Dan Gohman0bba49c2009-07-07 17:06:11 +00002196const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002197 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002198}
2199
Chris Lattner53e677a2004-04-02 20:23:17 +00002200/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2201/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002202const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002203 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002204
Dan Gohman0bba49c2009-07-07 17:06:11 +00002205 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002206 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002207 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002208 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002209 return S;
2210}
2211
Dan Gohman6bbcba12009-06-24 00:54:57 +00002212/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002213/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002214const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002215 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002216 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002217}
2218
2219/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2220///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002221const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002222 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002223 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002224 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002225
2226 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002227 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002228 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002229 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002230}
2231
2232/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002233const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002234 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002235 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002236 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002237
2238 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002239 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002240 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002241 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002242 return getMinusSCEV(AllOnes, V);
2243}
2244
2245/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2246///
Dan Gohman9311ef62009-06-24 14:49:00 +00002247const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2248 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002249 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002250 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002251}
2252
2253/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2254/// input value to the specified type. If the type must be extended, it is zero
2255/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002256const SCEV *
2257ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002258 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002259 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002260 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2261 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002262 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002263 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002264 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002265 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002266 return getTruncateExpr(V, Ty);
2267 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002268}
2269
2270/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2271/// input value to the specified type. If the type must be extended, it is sign
2272/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002273const SCEV *
2274ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002275 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002276 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002277 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2278 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002279 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002280 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002281 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002282 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002283 return getTruncateExpr(V, Ty);
2284 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002285}
2286
Dan Gohman467c4302009-05-13 03:46:30 +00002287/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2288/// input value to the specified type. If the type must be extended, it is zero
2289/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002290const SCEV *
2291ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002292 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002293 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2294 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002295 "Cannot noop or zero extend with non-integer arguments!");
2296 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2297 "getNoopOrZeroExtend cannot truncate!");
2298 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2299 return V; // No conversion
2300 return getZeroExtendExpr(V, Ty);
2301}
2302
2303/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2304/// input value to the specified type. If the type must be extended, it is sign
2305/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002306const SCEV *
2307ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002308 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002309 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2310 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002311 "Cannot noop or sign extend with non-integer arguments!");
2312 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2313 "getNoopOrSignExtend cannot truncate!");
2314 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2315 return V; // No conversion
2316 return getSignExtendExpr(V, Ty);
2317}
2318
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002319/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2320/// the input value to the specified type. If the type must be extended,
2321/// it is extended with unspecified bits. The conversion must not be
2322/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002323const SCEV *
2324ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002325 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002326 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2327 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002328 "Cannot noop or any extend with non-integer arguments!");
2329 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2330 "getNoopOrAnyExtend cannot truncate!");
2331 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2332 return V; // No conversion
2333 return getAnyExtendExpr(V, Ty);
2334}
2335
Dan Gohman467c4302009-05-13 03:46:30 +00002336/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2337/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002338const SCEV *
2339ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002340 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002341 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2342 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002343 "Cannot truncate or noop with non-integer arguments!");
2344 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2345 "getTruncateOrNoop cannot extend!");
2346 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2347 return V; // No conversion
2348 return getTruncateExpr(V, Ty);
2349}
2350
Dan Gohmana334aa72009-06-22 00:31:57 +00002351/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2352/// the types using zero-extension, and then perform a umax operation
2353/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002354const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2355 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002356 const SCEV *PromotedLHS = LHS;
2357 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002358
2359 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2360 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2361 else
2362 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2363
2364 return getUMaxExpr(PromotedLHS, PromotedRHS);
2365}
2366
Dan Gohmanc9759e82009-06-22 15:03:27 +00002367/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2368/// the types using zero-extension, and then perform a umin operation
2369/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002370const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2371 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002372 const SCEV *PromotedLHS = LHS;
2373 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002374
2375 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2376 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2377 else
2378 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2379
2380 return getUMinExpr(PromotedLHS, PromotedRHS);
2381}
2382
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002383/// PushDefUseChildren - Push users of the given Instruction
2384/// onto the given Worklist.
2385static void
2386PushDefUseChildren(Instruction *I,
2387 SmallVectorImpl<Instruction *> &Worklist) {
2388 // Push the def-use children onto the Worklist stack.
2389 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2390 UI != UE; ++UI)
2391 Worklist.push_back(cast<Instruction>(UI));
2392}
2393
2394/// ForgetSymbolicValue - This looks up computed SCEV values for all
2395/// instructions that depend on the given instruction and removes them from
2396/// the Scalars map if they reference SymName. This is used during PHI
2397/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002398void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002399ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2400 SmallVector<Instruction *, 16> Worklist;
2401 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002402
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002403 SmallPtrSet<Instruction *, 8> Visited;
2404 Visited.insert(I);
2405 while (!Worklist.empty()) {
2406 Instruction *I = Worklist.pop_back_val();
2407 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002408
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002409 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2410 Scalars.find(static_cast<Value *>(I));
2411 if (It != Scalars.end()) {
2412 // Short-circuit the def-use traversal if the symbolic name
2413 // ceases to appear in expressions.
2414 if (!It->second->hasOperand(SymName))
2415 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002416
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002417 // SCEVUnknown for a PHI either means that it has an unrecognized
2418 // structure, or it's a PHI that's in the progress of being computed
2419 // by createNodeForPHI. In the former case, additional loop trip
2420 // count information isn't going to change anything. In the later
2421 // case, createNodeForPHI will perform the necessary updates on its
2422 // own when it gets to that point.
2423 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2424 Scalars.erase(It);
2425 ValuesAtScopes.erase(I);
2426 }
2427
2428 PushDefUseChildren(I, Worklist);
2429 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002430}
Chris Lattner53e677a2004-04-02 20:23:17 +00002431
2432/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2433/// a loop header, making it a potential recurrence, or it doesn't.
2434///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002435const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002436 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002437 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002438 if (L->getHeader() == PN->getParent()) {
2439 // If it lives in the loop header, it has two incoming values, one
2440 // from outside the loop, and one from inside.
2441 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2442 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002443
Chris Lattner53e677a2004-04-02 20:23:17 +00002444 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002445 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002446 assert(Scalars.find(PN) == Scalars.end() &&
2447 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002448 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002449
2450 // Using this symbolic name for the PHI, analyze the value coming around
2451 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002452 Value *BEValueV = PN->getIncomingValue(BackEdge);
2453 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002454
2455 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2456 // has a special value for the first iteration of the loop.
2457
2458 // If the value coming around the backedge is an add with the symbolic
2459 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002460 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002461 // If there is a single occurrence of the symbolic value, replace it
2462 // with a recurrence.
2463 unsigned FoundIndex = Add->getNumOperands();
2464 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2465 if (Add->getOperand(i) == SymbolicName)
2466 if (FoundIndex == e) {
2467 FoundIndex = i;
2468 break;
2469 }
2470
2471 if (FoundIndex != Add->getNumOperands()) {
2472 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002473 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002474 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2475 if (i != FoundIndex)
2476 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002477 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002478
2479 // This is not a valid addrec if the step amount is varying each
2480 // loop iteration, but is not itself an addrec in this loop.
2481 if (Accum->isLoopInvariant(L) ||
2482 (isa<SCEVAddRecExpr>(Accum) &&
2483 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002484 const SCEV *StartVal =
2485 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmaneb490a72009-07-25 01:22:26 +00002486 const SCEVAddRecExpr *PHISCEV =
2487 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2488
2489 // If the increment doesn't overflow, then neither the addrec nor the
2490 // post-increment will overflow.
2491 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2492 if (OBO->getOperand(0) == PN &&
2493 getSCEV(OBO->getOperand(1)) ==
2494 PHISCEV->getStepRecurrence(*this)) {
2495 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
Dan Gohman5078f842009-08-20 17:11:38 +00002496 if (OBO->hasNoUnsignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002497 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002498 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002499 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002500 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002501 }
Dan Gohman5078f842009-08-20 17:11:38 +00002502 if (OBO->hasNoSignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002503 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002504 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002505 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002506 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002507 }
2508 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002509
2510 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002511 // to be symbolic. We now need to go back and purge all of the
2512 // entries for the scalars that use the symbolic expression.
2513 ForgetSymbolicName(PN, SymbolicName);
2514 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002515 return PHISCEV;
2516 }
2517 }
Dan Gohman622ed672009-05-04 22:02:23 +00002518 } else if (const SCEVAddRecExpr *AddRec =
2519 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002520 // Otherwise, this could be a loop like this:
2521 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2522 // In this case, j = {1,+,1} and BEValue is j.
2523 // Because the other in-value of i (0) fits the evolution of BEValue
2524 // i really is an addrec evolution.
2525 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002526 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002527
2528 // If StartVal = j.start - j.stride, we can use StartVal as the
2529 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002530 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002531 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002532 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002533 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002534
2535 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002536 // to be symbolic. We now need to go back and purge all of the
2537 // entries for the scalars that use the symbolic expression.
2538 ForgetSymbolicName(PN, SymbolicName);
2539 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002540 return PHISCEV;
2541 }
2542 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002543 }
2544
2545 return SymbolicName;
2546 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002547
Dan Gohmana653fc52009-07-14 14:06:25 +00002548 // It's tempting to recognize PHIs with a unique incoming value, however
2549 // this leads passes like indvars to break LCSSA form. Fortunately, such
2550 // PHIs are rare, as instcombine zaps them.
2551
Chris Lattner53e677a2004-04-02 20:23:17 +00002552 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002553 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002554}
2555
Dan Gohman26466c02009-05-08 20:26:55 +00002556/// createNodeForGEP - Expand GEP instructions into add and multiply
2557/// operations. This allows them to be analyzed by regular SCEV code.
2558///
Dan Gohmanca178902009-07-17 20:47:02 +00002559const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002560
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002561 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002562 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002563 // Don't attempt to analyze GEPs over unsized objects.
2564 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2565 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002566 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002567 gep_type_iterator GTI = gep_type_begin(GEP);
2568 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2569 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002570 I != E; ++I) {
2571 Value *Index = *I;
2572 // Compute the (potentially symbolic) offset in bytes for this index.
2573 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2574 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002575 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002576 TotalOffset = getAddExpr(TotalOffset,
2577 getFieldOffsetExpr(STy, FieldNo));
Dan Gohman26466c02009-05-08 20:26:55 +00002578 } else {
2579 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002580 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002581 if (!isa<PointerType>(LocalOffset->getType()))
2582 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002583 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002584 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI));
Dan Gohman26466c02009-05-08 20:26:55 +00002585 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2586 }
2587 }
2588 return getAddExpr(getSCEV(Base), TotalOffset);
2589}
2590
Nick Lewycky83bb0052007-11-22 07:59:40 +00002591/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2592/// guaranteed to end in (at every loop iteration). It is, at the same time,
2593/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2594/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002595uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002596ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002597 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002598 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002599
Dan Gohman622ed672009-05-04 22:02:23 +00002600 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002601 return std::min(GetMinTrailingZeros(T->getOperand()),
2602 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002603
Dan Gohman622ed672009-05-04 22:02:23 +00002604 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002605 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2606 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2607 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002608 }
2609
Dan Gohman622ed672009-05-04 22:02:23 +00002610 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002611 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2612 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2613 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002614 }
2615
Dan Gohman622ed672009-05-04 22:02:23 +00002616 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002617 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002618 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002619 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002620 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002621 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002622 }
2623
Dan Gohman622ed672009-05-04 22:02:23 +00002624 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002625 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002626 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2627 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002628 for (unsigned i = 1, e = M->getNumOperands();
2629 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002630 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002631 BitWidth);
2632 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002633 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002634
Dan Gohman622ed672009-05-04 22:02:23 +00002635 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002636 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002637 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002638 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002639 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002640 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002641 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002642
Dan Gohman622ed672009-05-04 22:02:23 +00002643 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002644 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002645 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002646 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002647 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002648 return MinOpRes;
2649 }
2650
Dan Gohman622ed672009-05-04 22:02:23 +00002651 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002652 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002653 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002654 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002655 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002656 return MinOpRes;
2657 }
2658
Dan Gohman2c364ad2009-06-19 23:29:04 +00002659 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2660 // For a SCEVUnknown, ask ValueTracking.
2661 unsigned BitWidth = getTypeSizeInBits(U->getType());
2662 APInt Mask = APInt::getAllOnesValue(BitWidth);
2663 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2664 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2665 return Zeros.countTrailingOnes();
2666 }
2667
2668 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002669 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002670}
Chris Lattner53e677a2004-04-02 20:23:17 +00002671
Dan Gohman85b05a22009-07-13 21:35:55 +00002672/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2673///
2674ConstantRange
2675ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002676
2677 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002678 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002679
Dan Gohman85b05a22009-07-13 21:35:55 +00002680 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2681 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2682 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2683 X = X.add(getUnsignedRange(Add->getOperand(i)));
2684 return X;
2685 }
2686
2687 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2688 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2689 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2690 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2691 return X;
2692 }
2693
2694 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2695 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2696 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2697 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2698 return X;
2699 }
2700
2701 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2702 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2703 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2704 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2705 return X;
2706 }
2707
2708 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2709 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2710 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2711 return X.udiv(Y);
2712 }
2713
2714 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2715 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2716 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2717 }
2718
2719 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2720 ConstantRange X = getUnsignedRange(SExt->getOperand());
2721 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2722 }
2723
2724 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2725 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2726 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2727 }
2728
2729 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2730
2731 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2732 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2733 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2734 if (!Trip) return FullSet;
2735
2736 // TODO: non-affine addrec
2737 if (AddRec->isAffine()) {
2738 const Type *Ty = AddRec->getType();
2739 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2740 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2741 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2742
2743 const SCEV *Start = AddRec->getStart();
Dan Gohmana16b5762009-07-21 00:42:47 +00002744 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002745 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2746
2747 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002748 // TODO: This is very conservative.
2749 if (!(Step->isOne() &&
2750 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2751 !(Step->isAllOnesValue() &&
2752 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
Dan Gohman85b05a22009-07-13 21:35:55 +00002753 return FullSet;
2754
2755 ConstantRange StartRange = getUnsignedRange(Start);
2756 ConstantRange EndRange = getUnsignedRange(End);
2757 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2758 EndRange.getUnsignedMin());
2759 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2760 EndRange.getUnsignedMax());
2761 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman0d5bae42009-07-20 22:41:51 +00002762 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002763 return ConstantRange(Min, Max+1);
2764 }
2765 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002766 }
2767
2768 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2769 // For a SCEVUnknown, ask ValueTracking.
2770 unsigned BitWidth = getTypeSizeInBits(U->getType());
2771 APInt Mask = APInt::getAllOnesValue(BitWidth);
2772 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2773 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002774 if (Ones == ~Zeros + 1)
2775 return FullSet;
2776 return ConstantRange(Ones, ~Zeros + 1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002777 }
2778
Dan Gohman85b05a22009-07-13 21:35:55 +00002779 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002780}
2781
Dan Gohman85b05a22009-07-13 21:35:55 +00002782/// getSignedRange - Determine the signed range for a particular SCEV.
2783///
2784ConstantRange
2785ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002786
Dan Gohman85b05a22009-07-13 21:35:55 +00002787 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2788 return ConstantRange(C->getValue()->getValue());
2789
2790 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2791 ConstantRange X = getSignedRange(Add->getOperand(0));
2792 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2793 X = X.add(getSignedRange(Add->getOperand(i)));
2794 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002795 }
2796
Dan Gohman85b05a22009-07-13 21:35:55 +00002797 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2798 ConstantRange X = getSignedRange(Mul->getOperand(0));
2799 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2800 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2801 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002802 }
2803
Dan Gohman85b05a22009-07-13 21:35:55 +00002804 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2805 ConstantRange X = getSignedRange(SMax->getOperand(0));
2806 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2807 X = X.smax(getSignedRange(SMax->getOperand(i)));
2808 return X;
2809 }
Dan Gohman62849c02009-06-24 01:05:09 +00002810
Dan Gohman85b05a22009-07-13 21:35:55 +00002811 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2812 ConstantRange X = getSignedRange(UMax->getOperand(0));
2813 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2814 X = X.umax(getSignedRange(UMax->getOperand(i)));
2815 return X;
2816 }
Dan Gohman62849c02009-06-24 01:05:09 +00002817
Dan Gohman85b05a22009-07-13 21:35:55 +00002818 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2819 ConstantRange X = getSignedRange(UDiv->getLHS());
2820 ConstantRange Y = getSignedRange(UDiv->getRHS());
2821 return X.udiv(Y);
2822 }
Dan Gohman62849c02009-06-24 01:05:09 +00002823
Dan Gohman85b05a22009-07-13 21:35:55 +00002824 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2825 ConstantRange X = getSignedRange(ZExt->getOperand());
2826 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2827 }
2828
2829 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2830 ConstantRange X = getSignedRange(SExt->getOperand());
2831 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2832 }
2833
2834 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2835 ConstantRange X = getSignedRange(Trunc->getOperand());
2836 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2837 }
2838
2839 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2840
2841 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2842 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2843 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2844 if (!Trip) return FullSet;
2845
2846 // TODO: non-affine addrec
2847 if (AddRec->isAffine()) {
2848 const Type *Ty = AddRec->getType();
2849 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2850 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2851 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2852
2853 const SCEV *Start = AddRec->getStart();
2854 const SCEV *Step = AddRec->getStepRecurrence(*this);
2855 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2856
2857 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002858 // TODO: This is very conservative.
2859 if (!(Step->isOne() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002860 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
Dan Gohmana16b5762009-07-21 00:42:47 +00002861 !(Step->isAllOnesValue() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002862 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2863 return FullSet;
2864
2865 ConstantRange StartRange = getSignedRange(Start);
2866 ConstantRange EndRange = getSignedRange(End);
2867 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2868 EndRange.getSignedMin());
2869 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2870 EndRange.getSignedMax());
2871 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmanc268e7c2009-07-21 00:37:45 +00002872 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002873 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002874 }
Dan Gohman62849c02009-06-24 01:05:09 +00002875 }
Dan Gohman62849c02009-06-24 01:05:09 +00002876 }
2877
Dan Gohman2c364ad2009-06-19 23:29:04 +00002878 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2879 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002880 unsigned BitWidth = getTypeSizeInBits(U->getType());
2881 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2882 if (NS == 1)
2883 return FullSet;
2884 return
2885 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2886 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002887 }
2888
Dan Gohman85b05a22009-07-13 21:35:55 +00002889 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002890}
2891
Chris Lattner53e677a2004-04-02 20:23:17 +00002892/// createSCEV - We know that there is no SCEV for the specified value.
2893/// Analyze the expression.
2894///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002895const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002896 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002897 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002898
Dan Gohman6c459a22008-06-22 19:56:46 +00002899 unsigned Opcode = Instruction::UserOp1;
2900 if (Instruction *I = dyn_cast<Instruction>(V))
2901 Opcode = I->getOpcode();
2902 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2903 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002904 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2905 return getConstant(CI);
2906 else if (isa<ConstantPointerNull>(V))
2907 return getIntegerSCEV(0, V->getType());
2908 else if (isa<UndefValue>(V))
2909 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00002910 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
2911 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00002912 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002913 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002914
Dan Gohmanca178902009-07-17 20:47:02 +00002915 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00002916 switch (Opcode) {
2917 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002918 return getAddExpr(getSCEV(U->getOperand(0)),
2919 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002920 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002921 return getMulExpr(getSCEV(U->getOperand(0)),
2922 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002923 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002924 return getUDivExpr(getSCEV(U->getOperand(0)),
2925 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002926 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002927 return getMinusSCEV(getSCEV(U->getOperand(0)),
2928 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002929 case Instruction::And:
2930 // For an expression like x&255 that merely masks off the high bits,
2931 // use zext(trunc(x)) as the SCEV expression.
2932 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002933 if (CI->isNullValue())
2934 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002935 if (CI->isAllOnesValue())
2936 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002937 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002938
2939 // Instcombine's ShrinkDemandedConstant may strip bits out of
2940 // constants, obscuring what would otherwise be a low-bits mask.
2941 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2942 // knew about to reconstruct a low-bits mask value.
2943 unsigned LZ = A.countLeadingZeros();
2944 unsigned BitWidth = A.getBitWidth();
2945 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2946 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2947 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2948
2949 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2950
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002951 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002952 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002953 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00002954 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002955 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002956 }
2957 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002958
Dan Gohman6c459a22008-06-22 19:56:46 +00002959 case Instruction::Or:
2960 // If the RHS of the Or is a constant, we may have something like:
2961 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2962 // optimizations will transparently handle this case.
2963 //
2964 // In order for this transformation to be safe, the LHS must be of the
2965 // form X*(2^n) and the Or constant must be less than 2^n.
2966 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002967 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002968 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002969 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002970 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002971 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002972 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002973 break;
2974 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002975 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002976 // If the RHS of the xor is a signbit, then this is just an add.
2977 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002978 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002979 return getAddExpr(getSCEV(U->getOperand(0)),
2980 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002981
2982 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002983 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002984 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002985
2986 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2987 // This is a variant of the check for xor with -1, and it handles
2988 // the case where instcombine has trimmed non-demanded bits out
2989 // of an xor with -1.
2990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2991 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2992 if (BO->getOpcode() == Instruction::And &&
2993 LCI->getValue() == CI->getValue())
2994 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002995 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002996 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002997 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002998 const Type *Z0Ty = Z0->getType();
2999 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3000
3001 // If C is a low-bits mask, the zero extend is zerving to
3002 // mask off the high bits. Complement the operand and
3003 // re-apply the zext.
3004 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3005 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3006
3007 // If C is a single bit, it may be in the sign-bit position
3008 // before the zero-extend. In this case, represent the xor
3009 // using an add, which is equivalent, and re-apply the zext.
3010 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3011 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3012 Trunc.isSignBit())
3013 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3014 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003015 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003016 }
3017 break;
3018
3019 case Instruction::Shl:
3020 // Turn shift left of a constant amount into a multiply.
3021 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3022 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003023 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003024 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003025 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003026 }
3027 break;
3028
Nick Lewycky01eaf802008-07-07 06:15:49 +00003029 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003030 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003031 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3032 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003033 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003034 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003035 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003036 }
3037 break;
3038
Dan Gohman4ee29af2009-04-21 02:26:00 +00003039 case Instruction::AShr:
3040 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3041 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3042 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3043 if (L->getOpcode() == Instruction::Shl &&
3044 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003045 unsigned BitWidth = getTypeSizeInBits(U->getType());
3046 uint64_t Amt = BitWidth - CI->getZExtValue();
3047 if (Amt == BitWidth)
3048 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3049 if (Amt > BitWidth)
3050 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003051 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003052 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003053 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003054 U->getType());
3055 }
3056 break;
3057
Dan Gohman6c459a22008-06-22 19:56:46 +00003058 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003059 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003060
3061 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003062 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003063
3064 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003065 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003066
3067 case Instruction::BitCast:
3068 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003069 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003070 return getSCEV(U->getOperand(0));
3071 break;
3072
Dan Gohmanf2411742009-07-20 17:43:30 +00003073 // It's tempting to handle inttoptr and ptrtoint, however this can
3074 // lead to pointer expressions which cannot be expanded to GEPs
3075 // (because they may overflow). For now, the only pointer-typed
3076 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00003077
Dan Gohman26466c02009-05-08 20:26:55 +00003078 case Instruction::GetElementPtr:
Dan Gohmanfb791602009-05-08 20:58:38 +00003079 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00003080
Dan Gohman6c459a22008-06-22 19:56:46 +00003081 case Instruction::PHI:
3082 return createNodeForPHI(cast<PHINode>(U));
3083
3084 case Instruction::Select:
3085 // This could be a smax or umax that was lowered earlier.
3086 // Try to recover it.
3087 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3088 Value *LHS = ICI->getOperand(0);
3089 Value *RHS = ICI->getOperand(1);
3090 switch (ICI->getPredicate()) {
3091 case ICmpInst::ICMP_SLT:
3092 case ICmpInst::ICMP_SLE:
3093 std::swap(LHS, RHS);
3094 // fall through
3095 case ICmpInst::ICMP_SGT:
3096 case ICmpInst::ICMP_SGE:
3097 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003098 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003099 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003100 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003101 break;
3102 case ICmpInst::ICMP_ULT:
3103 case ICmpInst::ICMP_ULE:
3104 std::swap(LHS, RHS);
3105 // fall through
3106 case ICmpInst::ICMP_UGT:
3107 case ICmpInst::ICMP_UGE:
3108 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003109 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003110 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003111 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003112 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003113 case ICmpInst::ICMP_NE:
3114 // n != 0 ? n : 1 -> umax(n, 1)
3115 if (LHS == U->getOperand(1) &&
3116 isa<ConstantInt>(U->getOperand(2)) &&
3117 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3118 isa<ConstantInt>(RHS) &&
3119 cast<ConstantInt>(RHS)->isZero())
3120 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3121 break;
3122 case ICmpInst::ICMP_EQ:
3123 // n == 0 ? 1 : n -> umax(n, 1)
3124 if (LHS == U->getOperand(2) &&
3125 isa<ConstantInt>(U->getOperand(1)) &&
3126 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3127 isa<ConstantInt>(RHS) &&
3128 cast<ConstantInt>(RHS)->isZero())
3129 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3130 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003131 default:
3132 break;
3133 }
3134 }
3135
3136 default: // We cannot analyze this expression.
3137 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003138 }
3139
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003140 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003141}
3142
3143
3144
3145//===----------------------------------------------------------------------===//
3146// Iteration Count Computation Code
3147//
3148
Dan Gohman46bdfb02009-02-24 18:55:53 +00003149/// getBackedgeTakenCount - If the specified loop has a predictable
3150/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3151/// object. The backedge-taken count is the number of times the loop header
3152/// will be branched to from within the loop. This is one less than the
3153/// trip count of the loop, since it doesn't count the first iteration,
3154/// when the header is branched to from outside the loop.
3155///
3156/// Note that it is not valid to call this method on a loop without a
3157/// loop-invariant backedge-taken count (see
3158/// hasLoopInvariantBackedgeTakenCount).
3159///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003160const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003161 return getBackedgeTakenInfo(L).Exact;
3162}
3163
3164/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3165/// return the least SCEV value that is known never to be less than the
3166/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003167const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003168 return getBackedgeTakenInfo(L).Max;
3169}
3170
Dan Gohman59ae6b92009-07-08 19:23:34 +00003171/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3172/// onto the given Worklist.
3173static void
3174PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3175 BasicBlock *Header = L->getHeader();
3176
3177 // Push all Loop-header PHIs onto the Worklist stack.
3178 for (BasicBlock::iterator I = Header->begin();
3179 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3180 Worklist.push_back(PN);
3181}
3182
Dan Gohmana1af7572009-04-30 20:47:05 +00003183const ScalarEvolution::BackedgeTakenInfo &
3184ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003185 // Initially insert a CouldNotCompute for this loop. If the insertion
3186 // succeeds, procede to actually compute a backedge-taken count and
3187 // update the value. The temporary CouldNotCompute value tells SCEV
3188 // code elsewhere that it shouldn't attempt to request a new
3189 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003190 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003191 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3192 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003193 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003194 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003195 assert(ItCount.Exact->isLoopInvariant(L) &&
3196 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003197 "Computed trip count isn't loop invariant for loop!");
3198 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003199
Dan Gohman01ecca22009-04-27 20:16:15 +00003200 // Update the value in the map.
3201 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003202 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003203 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003204 // Update the value in the map.
3205 Pair.first->second = ItCount;
3206 if (isa<PHINode>(L->getHeader()->begin()))
3207 // Only count loops that have phi nodes as not being computable.
3208 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003209 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003210
3211 // Now that we know more about the trip count for this loop, forget any
3212 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003213 // conservative estimates made without the benefit of trip count
3214 // information. This is similar to the code in
3215 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3216 // nodes specially.
3217 if (ItCount.hasAnyInfo()) {
3218 SmallVector<Instruction *, 16> Worklist;
3219 PushLoopPHIs(L, Worklist);
3220
3221 SmallPtrSet<Instruction *, 8> Visited;
3222 while (!Worklist.empty()) {
3223 Instruction *I = Worklist.pop_back_val();
3224 if (!Visited.insert(I)) continue;
3225
3226 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3227 Scalars.find(static_cast<Value *>(I));
3228 if (It != Scalars.end()) {
3229 // SCEVUnknown for a PHI either means that it has an unrecognized
3230 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003231 // by createNodeForPHI. In the former case, additional loop trip
3232 // count information isn't going to change anything. In the later
3233 // case, createNodeForPHI will perform the necessary updates on its
3234 // own when it gets to that point.
Dan Gohman59ae6b92009-07-08 19:23:34 +00003235 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3236 Scalars.erase(It);
3237 ValuesAtScopes.erase(I);
3238 if (PHINode *PN = dyn_cast<PHINode>(I))
3239 ConstantEvolutionLoopExitValue.erase(PN);
3240 }
3241
3242 PushDefUseChildren(I, Worklist);
3243 }
3244 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003245 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003246 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003247}
3248
Dan Gohman46bdfb02009-02-24 18:55:53 +00003249/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003250/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003251/// ScalarEvolution's ability to compute a trip count, or if the loop
3252/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003253void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003254 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003255
Dan Gohman35738ac2009-05-04 22:30:44 +00003256 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003257 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003258
Dan Gohman59ae6b92009-07-08 19:23:34 +00003259 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003260 while (!Worklist.empty()) {
3261 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003262 if (!Visited.insert(I)) continue;
3263
3264 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3265 Scalars.find(static_cast<Value *>(I));
3266 if (It != Scalars.end()) {
3267 Scalars.erase(It);
3268 ValuesAtScopes.erase(I);
3269 if (PHINode *PN = dyn_cast<PHINode>(I))
3270 ConstantEvolutionLoopExitValue.erase(PN);
3271 }
3272
3273 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003274 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003275}
3276
Dan Gohman46bdfb02009-02-24 18:55:53 +00003277/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3278/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003279ScalarEvolution::BackedgeTakenInfo
3280ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003281 SmallVector<BasicBlock*, 8> ExitingBlocks;
3282 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003283
Dan Gohmana334aa72009-06-22 00:31:57 +00003284 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003285 const SCEV *BECount = getCouldNotCompute();
3286 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003287 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003288 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3289 BackedgeTakenInfo NewBTI =
3290 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003291
Dan Gohman1c343752009-06-27 21:21:31 +00003292 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003293 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003294 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003295 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003296 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003297 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003298 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003299 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003300 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003301 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003302 }
Dan Gohman1c343752009-06-27 21:21:31 +00003303 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003304 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003305 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003306 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003307 }
3308
3309 return BackedgeTakenInfo(BECount, MaxBECount);
3310}
3311
3312/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3313/// of the specified loop will execute if it exits via the specified block.
3314ScalarEvolution::BackedgeTakenInfo
3315ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3316 BasicBlock *ExitingBlock) {
3317
3318 // Okay, we've chosen an exiting block. See what condition causes us to
3319 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003320 //
3321 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003322 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003323 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003324 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003325
Chris Lattner8b0e3602007-01-07 02:24:26 +00003326 // At this point, we know we have a conditional branch that determines whether
3327 // the loop is exited. However, we don't know if the branch is executed each
3328 // time through the loop. If not, then the execution count of the branch will
3329 // not be equal to the trip count of the loop.
3330 //
3331 // Currently we check for this by checking to see if the Exit branch goes to
3332 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003333 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003334 // loop header. This is common for un-rotated loops.
3335 //
3336 // If both of those tests fail, walk up the unique predecessor chain to the
3337 // header, stopping if there is an edge that doesn't exit the loop. If the
3338 // header is reached, the execution count of the branch will be equal to the
3339 // trip count of the loop.
3340 //
3341 // More extensive analysis could be done to handle more cases here.
3342 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003343 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003344 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003345 ExitBr->getParent() != L->getHeader()) {
3346 // The simple checks failed, try climbing the unique predecessor chain
3347 // up to the header.
3348 bool Ok = false;
3349 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3350 BasicBlock *Pred = BB->getUniquePredecessor();
3351 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003352 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003353 TerminatorInst *PredTerm = Pred->getTerminator();
3354 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3355 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3356 if (PredSucc == BB)
3357 continue;
3358 // If the predecessor has a successor that isn't BB and isn't
3359 // outside the loop, assume the worst.
3360 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003361 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003362 }
3363 if (Pred == L->getHeader()) {
3364 Ok = true;
3365 break;
3366 }
3367 BB = Pred;
3368 }
3369 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003370 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003371 }
3372
3373 // Procede to the next level to examine the exit condition expression.
3374 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3375 ExitBr->getSuccessor(0),
3376 ExitBr->getSuccessor(1));
3377}
3378
3379/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3380/// backedge of the specified loop will execute if its exit condition
3381/// were a conditional branch of ExitCond, TBB, and FBB.
3382ScalarEvolution::BackedgeTakenInfo
3383ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3384 Value *ExitCond,
3385 BasicBlock *TBB,
3386 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003387 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3389 if (BO->getOpcode() == Instruction::And) {
3390 // Recurse on the operands of the and.
3391 BackedgeTakenInfo BTI0 =
3392 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3393 BackedgeTakenInfo BTI1 =
3394 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003395 const SCEV *BECount = getCouldNotCompute();
3396 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003397 if (L->contains(TBB)) {
3398 // Both conditions must be true for the loop to continue executing.
3399 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003400 if (BTI0.Exact == getCouldNotCompute() ||
3401 BTI1.Exact == getCouldNotCompute())
3402 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003403 else
3404 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003405 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003406 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003407 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003408 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003409 else
3410 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003411 } else {
3412 // Both conditions must be true for the loop to exit.
3413 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003414 if (BTI0.Exact != getCouldNotCompute() &&
3415 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003416 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003417 if (BTI0.Max != getCouldNotCompute() &&
3418 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003419 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3420 }
3421
3422 return BackedgeTakenInfo(BECount, MaxBECount);
3423 }
3424 if (BO->getOpcode() == Instruction::Or) {
3425 // Recurse on the operands of the or.
3426 BackedgeTakenInfo BTI0 =
3427 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3428 BackedgeTakenInfo BTI1 =
3429 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003430 const SCEV *BECount = getCouldNotCompute();
3431 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003432 if (L->contains(FBB)) {
3433 // Both conditions must be false for the loop to continue executing.
3434 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003435 if (BTI0.Exact == getCouldNotCompute() ||
3436 BTI1.Exact == getCouldNotCompute())
3437 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003438 else
3439 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003440 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003441 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003442 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003443 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003444 else
3445 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003446 } else {
3447 // Both conditions must be false for the loop to exit.
3448 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003449 if (BTI0.Exact != getCouldNotCompute() &&
3450 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003451 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003452 if (BTI0.Max != getCouldNotCompute() &&
3453 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003454 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3455 }
3456
3457 return BackedgeTakenInfo(BECount, MaxBECount);
3458 }
3459 }
3460
3461 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3462 // Procede to the next level to examine the icmp.
3463 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3464 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465
Eli Friedman361e54d2009-05-09 12:32:42 +00003466 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003467 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3468}
3469
3470/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3471/// backedge of the specified loop will execute if its exit condition
3472/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3473ScalarEvolution::BackedgeTakenInfo
3474ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3475 ICmpInst *ExitCond,
3476 BasicBlock *TBB,
3477 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003478
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 // If the condition was exit on true, convert the condition to exit on false
3480 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003481 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003482 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003483 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003484 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003485
3486 // Handle common loops like: for (X = "string"; *X; ++X)
3487 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3488 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003489 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003490 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003491 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3492 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3493 return BackedgeTakenInfo(ItCnt,
3494 isa<SCEVConstant>(ItCnt) ? ItCnt :
3495 getConstant(APInt::getMaxValue(BitWidth)-1));
3496 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003497 }
3498
Dan Gohman0bba49c2009-07-07 17:06:11 +00003499 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3500 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003501
3502 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003503 LHS = getSCEVAtScope(LHS, L);
3504 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003505
Dan Gohman64a845e2009-06-24 04:48:43 +00003506 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003507 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003508 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3509 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003510 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003511 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003512 }
3513
Chris Lattner53e677a2004-04-02 20:23:17 +00003514 // If we have a comparison of a chrec against a constant, try to use value
3515 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003516 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3517 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003518 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003519 // Form the constant range.
3520 ConstantRange CompRange(
3521 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003522
Dan Gohman0bba49c2009-07-07 17:06:11 +00003523 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003524 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003525 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003526
Chris Lattner53e677a2004-04-02 20:23:17 +00003527 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003528 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003529 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003530 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003531 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003532 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003533 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003534 case ICmpInst::ICMP_EQ: { // while (X == Y)
3535 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003536 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003537 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003538 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003539 }
3540 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003541 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3542 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003543 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003544 }
3545 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003546 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3547 getNotSCEV(RHS), L, true);
3548 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003549 break;
3550 }
3551 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003552 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3553 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003554 break;
3555 }
3556 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003557 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3558 getNotSCEV(RHS), L, false);
3559 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003560 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003561 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003562 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003563#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003564 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003565 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003566 errs() << "[unsigned] ";
3567 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003568 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003569 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003570#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003571 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003572 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003573 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003574 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003575}
3576
Chris Lattner673e02b2004-10-12 01:49:27 +00003577static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003578EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3579 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003580 const SCEV *InVal = SE.getConstant(C);
3581 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003582 assert(isa<SCEVConstant>(Val) &&
3583 "Evaluation of SCEV at constant didn't fold correctly?");
3584 return cast<SCEVConstant>(Val)->getValue();
3585}
3586
3587/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3588/// and a GEP expression (missing the pointer index) indexing into it, return
3589/// the addressed element of the initializer or null if the index expression is
3590/// invalid.
3591static Constant *
Owen Andersone922c022009-07-22 00:24:57 +00003592GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003593 const std::vector<ConstantInt*> &Indices) {
3594 Constant *Init = GV->getInitializer();
3595 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003596 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003597 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3598 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3599 Init = cast<Constant>(CS->getOperand(Idx));
3600 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3601 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3602 Init = cast<Constant>(CA->getOperand(Idx));
3603 } else if (isa<ConstantAggregateZero>(Init)) {
3604 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3605 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003606 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003607 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3608 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003609 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003610 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003611 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003612 }
3613 return 0;
3614 } else {
3615 return 0; // Unknown initializer type
3616 }
3617 }
3618 return Init;
3619}
3620
Dan Gohman46bdfb02009-02-24 18:55:53 +00003621/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3622/// 'icmp op load X, cst', try to see if we can compute the backedge
3623/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003624const SCEV *
3625ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3626 LoadInst *LI,
3627 Constant *RHS,
3628 const Loop *L,
3629 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003630 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003631
3632 // Check to see if the loaded pointer is a getelementptr of a global.
3633 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003634 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003635
3636 // Make sure that it is really a constant global we are gepping, with an
3637 // initializer, and make sure the first IDX is really 0.
3638 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003639 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003640 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3641 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003642 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003643
3644 // Okay, we allow one non-constant index into the GEP instruction.
3645 Value *VarIdx = 0;
3646 std::vector<ConstantInt*> Indexes;
3647 unsigned VarIdxNum = 0;
3648 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3649 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3650 Indexes.push_back(CI);
3651 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003652 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003653 VarIdx = GEP->getOperand(i);
3654 VarIdxNum = i-2;
3655 Indexes.push_back(0);
3656 }
3657
3658 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3659 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003660 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003661 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003662
3663 // We can only recognize very limited forms of loop index expressions, in
3664 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003665 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003666 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3667 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3668 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003669 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003670
3671 unsigned MaxSteps = MaxBruteForceIterations;
3672 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003673 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003674 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003675 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003676
3677 // Form the GEP offset.
3678 Indexes[VarIdxNum] = Val;
3679
Owen Andersone922c022009-07-22 00:24:57 +00003680 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003681 if (Result == 0) break; // Cannot compute!
3682
3683 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003685 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003686 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003687#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003688 errs() << "\n***\n*** Computed loop count " << *ItCst
3689 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3690 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003691#endif
3692 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003693 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003694 }
3695 }
Dan Gohman1c343752009-06-27 21:21:31 +00003696 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003697}
3698
3699
Chris Lattner3221ad02004-04-17 22:58:41 +00003700/// CanConstantFold - Return true if we can constant fold an instruction of the
3701/// specified type, assuming that all operands were constants.
3702static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003703 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003704 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3705 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003706
Chris Lattner3221ad02004-04-17 22:58:41 +00003707 if (const CallInst *CI = dyn_cast<CallInst>(I))
3708 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003709 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003710 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003711}
3712
Chris Lattner3221ad02004-04-17 22:58:41 +00003713/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3714/// in the loop that V is derived from. We allow arbitrary operations along the
3715/// way, but the operands of an operation must either be constants or a value
3716/// derived from a constant PHI. If this expression does not fit with these
3717/// constraints, return null.
3718static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3719 // If this is not an instruction, or if this is an instruction outside of the
3720 // loop, it can't be derived from a loop PHI.
3721 Instruction *I = dyn_cast<Instruction>(V);
3722 if (I == 0 || !L->contains(I->getParent())) return 0;
3723
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003724 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003725 if (L->getHeader() == I->getParent())
3726 return PN;
3727 else
3728 // We don't currently keep track of the control flow needed to evaluate
3729 // PHIs, so we cannot handle PHIs inside of loops.
3730 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003731 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003732
3733 // If we won't be able to constant fold this expression even if the operands
3734 // are constants, return early.
3735 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003736
Chris Lattner3221ad02004-04-17 22:58:41 +00003737 // Otherwise, we can evaluate this instruction if all of its operands are
3738 // constant or derived from a PHI node themselves.
3739 PHINode *PHI = 0;
3740 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3741 if (!(isa<Constant>(I->getOperand(Op)) ||
3742 isa<GlobalValue>(I->getOperand(Op)))) {
3743 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3744 if (P == 0) return 0; // Not evolving from PHI
3745 if (PHI == 0)
3746 PHI = P;
3747 else if (PHI != P)
3748 return 0; // Evolving from multiple different PHIs.
3749 }
3750
3751 // This is a expression evolving from a constant PHI!
3752 return PHI;
3753}
3754
3755/// EvaluateExpression - Given an expression that passes the
3756/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3757/// in the loop has the value PHIVal. If we can't fold this expression for some
3758/// reason, return null.
3759static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3760 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003761 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003762 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003763 Instruction *I = cast<Instruction>(V);
Owen Andersone922c022009-07-22 00:24:57 +00003764 LLVMContext &Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003765
3766 std::vector<Constant*> Operands;
3767 Operands.resize(I->getNumOperands());
3768
3769 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3770 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3771 if (Operands[i] == 0) return 0;
3772 }
3773
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003774 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3775 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003776 &Operands[0], Operands.size(),
3777 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003778 else
3779 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003780 &Operands[0], Operands.size(),
3781 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003782}
3783
3784/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3785/// in the header of its containing loop, we know the loop executes a
3786/// constant number of times, and the PHI node is just a recurrence
3787/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003788Constant *
3789ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3790 const APInt& BEs,
3791 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003792 std::map<PHINode*, Constant*>::iterator I =
3793 ConstantEvolutionLoopExitValue.find(PN);
3794 if (I != ConstantEvolutionLoopExitValue.end())
3795 return I->second;
3796
Dan Gohman46bdfb02009-02-24 18:55:53 +00003797 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003798 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3799
3800 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3801
3802 // Since the loop is canonicalized, the PHI node must have two entries. One
3803 // entry must be a constant (coming in from outside of the loop), and the
3804 // second must be derived from the same PHI.
3805 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3806 Constant *StartCST =
3807 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3808 if (StartCST == 0)
3809 return RetVal = 0; // Must be a constant.
3810
3811 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3812 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3813 if (PN2 != PN)
3814 return RetVal = 0; // Not derived from same PHI.
3815
3816 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003817 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003818 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003819
Dan Gohman46bdfb02009-02-24 18:55:53 +00003820 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003821 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003822 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3823 if (IterationNum == NumIterations)
3824 return RetVal = PHIVal; // Got exit value!
3825
3826 // Compute the value of the PHI node for the next iteration.
3827 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3828 if (NextPHI == PHIVal)
3829 return RetVal = NextPHI; // Stopped evolving!
3830 if (NextPHI == 0)
3831 return 0; // Couldn't evaluate!
3832 PHIVal = NextPHI;
3833 }
3834}
3835
Dan Gohman07ad19b2009-07-27 16:09:48 +00003836/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003837/// constant number of times (the condition evolves only from constants),
3838/// try to evaluate a few iterations of the loop until we get the exit
3839/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003840/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003841const SCEV *
3842ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3843 Value *Cond,
3844 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003845 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003846 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003847
3848 // Since the loop is canonicalized, the PHI node must have two entries. One
3849 // entry must be a constant (coming in from outside of the loop), and the
3850 // second must be derived from the same PHI.
3851 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3852 Constant *StartCST =
3853 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003854 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003855
3856 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3857 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003858 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003859
3860 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3861 // the loop symbolically to determine when the condition gets a value of
3862 // "ExitWhen".
3863 unsigned IterationNum = 0;
3864 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3865 for (Constant *PHIVal = StartCST;
3866 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003867 ConstantInt *CondVal =
3868 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003869
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003870 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003871 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003872
Reid Spencere8019bb2007-03-01 07:25:48 +00003873 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003874 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00003875 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003876 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003877
Chris Lattner3221ad02004-04-17 22:58:41 +00003878 // Compute the value of the PHI node for the next iteration.
3879 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3880 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003881 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003882 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003883 }
3884
3885 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003886 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003887}
3888
Dan Gohman66a7e852009-05-08 20:38:54 +00003889/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3890/// at the specified scope in the program. The L value specifies a loop
3891/// nest to evaluate the expression at, where null is the top-level or a
3892/// specified loop is immediately inside of the loop.
3893///
3894/// This method can be used to compute the exit value for a variable defined
3895/// in a loop by querying what the value will hold in the parent loop.
3896///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003897/// In the case that a relevant loop exit value cannot be computed, the
3898/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003899const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003900 // FIXME: this should be turned into a virtual method on SCEV!
3901
Chris Lattner3221ad02004-04-17 22:58:41 +00003902 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003903
Nick Lewycky3e630762008-02-20 06:48:22 +00003904 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003905 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003906 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003907 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003908 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003909 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3910 if (PHINode *PN = dyn_cast<PHINode>(I))
3911 if (PN->getParent() == LI->getHeader()) {
3912 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003913 // to see if the loop that contains it has a known backedge-taken
3914 // count. If so, we may be able to force computation of the exit
3915 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003916 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003917 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003918 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003919 // Okay, we know how many times the containing loop executes. If
3920 // this is a constant evolving PHI node, get the final value at
3921 // the specified iteration number.
3922 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003923 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003924 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003925 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003926 }
3927 }
3928
Reid Spencer09906f32006-12-04 21:33:23 +00003929 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003930 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003931 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003932 // result. This is particularly useful for computing loop exit values.
3933 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003934 // Check to see if we've folded this instruction at this loop before.
3935 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3936 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3937 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3938 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003939 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003940
Chris Lattner3221ad02004-04-17 22:58:41 +00003941 std::vector<Constant*> Operands;
3942 Operands.reserve(I->getNumOperands());
3943 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3944 Value *Op = I->getOperand(i);
3945 if (Constant *C = dyn_cast<Constant>(Op)) {
3946 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003947 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003948 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003949 // non-integer and non-pointer, don't even try to analyze them
3950 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003951 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003952 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003953
Dan Gohman85b05a22009-07-13 21:35:55 +00003954 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00003955 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003956 Constant *C = SC->getValue();
3957 if (C->getType() != Op->getType())
3958 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3959 Op->getType(),
3960 false),
3961 C, Op->getType());
3962 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003963 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003964 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3965 if (C->getType() != Op->getType())
3966 C =
3967 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3968 Op->getType(),
3969 false),
3970 C, Op->getType());
3971 Operands.push_back(C);
3972 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003973 return V;
3974 } else {
3975 return V;
3976 }
3977 }
3978 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003979
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003980 Constant *C;
3981 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3982 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003983 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00003984 getContext());
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003985 else
3986 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003987 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00003988 getContext());
Dan Gohman6bce6432009-05-08 20:47:27 +00003989 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003990 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003991 }
3992 }
3993
3994 // This is some other type of SCEVUnknown, just return it.
3995 return V;
3996 }
3997
Dan Gohman622ed672009-05-04 22:02:23 +00003998 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003999 // Avoid performing the look-up in the common case where the specified
4000 // expression has no loop-variant portions.
4001 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004002 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004003 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004004 // Okay, at least one of these operands is loop variant but might be
4005 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004006 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4007 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004008 NewOps.push_back(OpAtScope);
4009
4010 for (++i; i != e; ++i) {
4011 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004012 NewOps.push_back(OpAtScope);
4013 }
4014 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004015 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004016 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004017 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004018 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004019 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004020 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004021 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004022 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004023 }
4024 }
4025 // If we got here, all operands are loop invariant.
4026 return Comm;
4027 }
4028
Dan Gohman622ed672009-05-04 22:02:23 +00004029 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004030 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4031 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004032 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4033 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004034 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004035 }
4036
4037 // If this is a loop recurrence for a loop that does not contain L, then we
4038 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004039 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004040 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
4041 // To evaluate this recurrence, we need to know how many times the AddRec
4042 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004043 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004044 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004045
Eli Friedmanb42a6262008-08-04 23:49:06 +00004046 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004047 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004048 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004049 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004050 }
4051
Dan Gohman622ed672009-05-04 22:02:23 +00004052 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004053 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004054 if (Op == Cast->getOperand())
4055 return Cast; // must be loop invariant
4056 return getZeroExtendExpr(Op, Cast->getType());
4057 }
4058
Dan Gohman622ed672009-05-04 22:02:23 +00004059 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004060 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004061 if (Op == Cast->getOperand())
4062 return Cast; // must be loop invariant
4063 return getSignExtendExpr(Op, Cast->getType());
4064 }
4065
Dan Gohman622ed672009-05-04 22:02:23 +00004066 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004067 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004068 if (Op == Cast->getOperand())
4069 return Cast; // must be loop invariant
4070 return getTruncateExpr(Op, Cast->getType());
4071 }
4072
Dan Gohmanc40f17b2009-08-18 16:46:41 +00004073 if (isa<SCEVTargetDataConstant>(V))
4074 return V;
4075
Torok Edwinc23197a2009-07-14 16:55:14 +00004076 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004077 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004078}
4079
Dan Gohman66a7e852009-05-08 20:38:54 +00004080/// getSCEVAtScope - This is a convenience function which does
4081/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004082const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004083 return getSCEVAtScope(getSCEV(V), L);
4084}
4085
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004086/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4087/// following equation:
4088///
4089/// A * X = B (mod N)
4090///
4091/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4092/// A and B isn't important.
4093///
4094/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004095static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004096 ScalarEvolution &SE) {
4097 uint32_t BW = A.getBitWidth();
4098 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4099 assert(A != 0 && "A must be non-zero.");
4100
4101 // 1. D = gcd(A, N)
4102 //
4103 // The gcd of A and N may have only one prime factor: 2. The number of
4104 // trailing zeros in A is its multiplicity
4105 uint32_t Mult2 = A.countTrailingZeros();
4106 // D = 2^Mult2
4107
4108 // 2. Check if B is divisible by D.
4109 //
4110 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4111 // is not less than multiplicity of this prime factor for D.
4112 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004113 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004114
4115 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4116 // modulo (N / D).
4117 //
4118 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4119 // bit width during computations.
4120 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4121 APInt Mod(BW + 1, 0);
4122 Mod.set(BW - Mult2); // Mod = N / D
4123 APInt I = AD.multiplicativeInverse(Mod);
4124
4125 // 4. Compute the minimum unsigned root of the equation:
4126 // I * (B / D) mod (N / D)
4127 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4128
4129 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4130 // bits.
4131 return SE.getConstant(Result.trunc(BW));
4132}
Chris Lattner53e677a2004-04-02 20:23:17 +00004133
4134/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4135/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4136/// might be the same) or two SCEVCouldNotCompute objects.
4137///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004138static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004139SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004140 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004141 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4142 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4143 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004144
Chris Lattner53e677a2004-04-02 20:23:17 +00004145 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004146 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004147 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004148 return std::make_pair(CNC, CNC);
4149 }
4150
Reid Spencere8019bb2007-03-01 07:25:48 +00004151 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004152 const APInt &L = LC->getValue()->getValue();
4153 const APInt &M = MC->getValue()->getValue();
4154 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004155 APInt Two(BitWidth, 2);
4156 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004157
Dan Gohman64a845e2009-06-24 04:48:43 +00004158 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004159 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004160 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004161 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4162 // The B coefficient is M-N/2
4163 APInt B(M);
4164 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004165
Reid Spencere8019bb2007-03-01 07:25:48 +00004166 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004167 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004168
Reid Spencere8019bb2007-03-01 07:25:48 +00004169 // Compute the B^2-4ac term.
4170 APInt SqrtTerm(B);
4171 SqrtTerm *= B;
4172 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004173
Reid Spencere8019bb2007-03-01 07:25:48 +00004174 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4175 // integer value or else APInt::sqrt() will assert.
4176 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004177
Dan Gohman64a845e2009-06-24 04:48:43 +00004178 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004179 // The divisions must be performed as signed divisions.
4180 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004181 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004182 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004183 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004184 return std::make_pair(CNC, CNC);
4185 }
4186
Owen Andersone922c022009-07-22 00:24:57 +00004187 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004188
4189 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004190 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004191 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004192 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004193
Dan Gohman64a845e2009-06-24 04:48:43 +00004194 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004195 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004196 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004197}
4198
4199/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004200/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004201const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004202 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004203 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004204 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004205 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004206 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004207 }
4208
Dan Gohman35738ac2009-05-04 22:30:44 +00004209 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004210 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004211 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004212
4213 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004214 // If this is an affine expression, the execution count of this branch is
4215 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004216 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004217 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004218 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004219 // equivalent to:
4220 //
4221 // Step*N = -Start (mod 2^BW)
4222 //
4223 // where BW is the common bit width of Start and Step.
4224
Chris Lattner53e677a2004-04-02 20:23:17 +00004225 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004226 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4227 L->getParentLoop());
4228 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4229 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004230
Dan Gohman622ed672009-05-04 22:02:23 +00004231 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004232 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004233
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004234 // First, handle unitary steps.
4235 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004236 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004237 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4238 return Start; // N = Start (as unsigned)
4239
4240 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004241 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004242 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004243 -StartC->getValue()->getValue(),
4244 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004245 }
Chris Lattner42a75512007-01-15 02:27:26 +00004246 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004247 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4248 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004249 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004250 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004251 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4252 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004253 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004254#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004255 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4256 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004257#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004258 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004259 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004260 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004261 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004262 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004263 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004264
Chris Lattner53e677a2004-04-02 20:23:17 +00004265 // We can only use this value if the chrec ends up with an exact zero
4266 // value at this index. When solving for "X*X != 5", for example, we
4267 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004268 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004269 if (Val->isZero())
4270 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004271 }
4272 }
4273 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004274
Dan Gohman1c343752009-06-27 21:21:31 +00004275 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004276}
4277
4278/// HowFarToNonZero - Return the number of times a backedge checking the
4279/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004280/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004281const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004282 // Loops that look like: while (X == 0) are very strange indeed. We don't
4283 // handle them yet except for the trivial case. This could be expanded in the
4284 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004285
Chris Lattner53e677a2004-04-02 20:23:17 +00004286 // If the value is a constant, check to see if it is known to be non-zero
4287 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004288 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004289 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004290 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004291 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004292 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004293
Chris Lattner53e677a2004-04-02 20:23:17 +00004294 // We could implement others, but I really doubt anyone writes loops like
4295 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004296 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004297}
4298
Dan Gohman859b4822009-05-18 15:36:09 +00004299/// getLoopPredecessor - If the given loop's header has exactly one unique
4300/// predecessor outside the loop, return it. Otherwise return null.
4301///
4302BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4303 BasicBlock *Header = L->getHeader();
4304 BasicBlock *Pred = 0;
4305 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4306 PI != E; ++PI)
4307 if (!L->contains(*PI)) {
4308 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4309 Pred = *PI;
4310 }
4311 return Pred;
4312}
4313
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004314/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4315/// (which may not be an immediate predecessor) which has exactly one
4316/// successor from which BB is reachable, or null if no such block is
4317/// found.
4318///
4319BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004320ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004321 // If the block has a unique predecessor, then there is no path from the
4322 // predecessor to the block that does not go through the direct edge
4323 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004324 if (BasicBlock *Pred = BB->getSinglePredecessor())
4325 return Pred;
4326
4327 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004328 // If the header has a unique predecessor outside the loop, it must be
4329 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004330 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004331 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004332
4333 return 0;
4334}
4335
Dan Gohman763bad12009-06-20 00:35:32 +00004336/// HasSameValue - SCEV structural equivalence is usually sufficient for
4337/// testing whether two expressions are equal, however for the purposes of
4338/// looking for a condition guarding a loop, it can be useful to be a little
4339/// more general, since a front-end may have replicated the controlling
4340/// expression.
4341///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004342static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004343 // Quick check to see if they are the same SCEV.
4344 if (A == B) return true;
4345
4346 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4347 // two different instructions with the same value. Check for this case.
4348 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4349 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4350 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4351 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004352 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004353 return true;
4354
4355 // Otherwise assume they may have a different value.
4356 return false;
4357}
4358
Dan Gohman85b05a22009-07-13 21:35:55 +00004359bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4360 return getSignedRange(S).getSignedMax().isNegative();
4361}
4362
4363bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4364 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4365}
4366
4367bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4368 return !getSignedRange(S).getSignedMin().isNegative();
4369}
4370
4371bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4372 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4373}
4374
4375bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4376 return isKnownNegative(S) || isKnownPositive(S);
4377}
4378
4379bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4380 const SCEV *LHS, const SCEV *RHS) {
4381
4382 if (HasSameValue(LHS, RHS))
4383 return ICmpInst::isTrueWhenEqual(Pred);
4384
4385 switch (Pred) {
4386 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004387 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004388 break;
4389 case ICmpInst::ICMP_SGT:
4390 Pred = ICmpInst::ICMP_SLT;
4391 std::swap(LHS, RHS);
4392 case ICmpInst::ICMP_SLT: {
4393 ConstantRange LHSRange = getSignedRange(LHS);
4394 ConstantRange RHSRange = getSignedRange(RHS);
4395 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4396 return true;
4397 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4398 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004399 break;
4400 }
4401 case ICmpInst::ICMP_SGE:
4402 Pred = ICmpInst::ICMP_SLE;
4403 std::swap(LHS, RHS);
4404 case ICmpInst::ICMP_SLE: {
4405 ConstantRange LHSRange = getSignedRange(LHS);
4406 ConstantRange RHSRange = getSignedRange(RHS);
4407 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4408 return true;
4409 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4410 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004411 break;
4412 }
4413 case ICmpInst::ICMP_UGT:
4414 Pred = ICmpInst::ICMP_ULT;
4415 std::swap(LHS, RHS);
4416 case ICmpInst::ICMP_ULT: {
4417 ConstantRange LHSRange = getUnsignedRange(LHS);
4418 ConstantRange RHSRange = getUnsignedRange(RHS);
4419 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4420 return true;
4421 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4422 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004423 break;
4424 }
4425 case ICmpInst::ICMP_UGE:
4426 Pred = ICmpInst::ICMP_ULE;
4427 std::swap(LHS, RHS);
4428 case ICmpInst::ICMP_ULE: {
4429 ConstantRange LHSRange = getUnsignedRange(LHS);
4430 ConstantRange RHSRange = getUnsignedRange(RHS);
4431 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4432 return true;
4433 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4434 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004435 break;
4436 }
4437 case ICmpInst::ICMP_NE: {
4438 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4439 return true;
4440 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4441 return true;
4442
4443 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4444 if (isKnownNonZero(Diff))
4445 return true;
4446 break;
4447 }
4448 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004449 // The check at the top of the function catches the case where
4450 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004451 break;
4452 }
4453 return false;
4454}
4455
4456/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4457/// protected by a conditional between LHS and RHS. This is used to
4458/// to eliminate casts.
4459bool
4460ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4461 ICmpInst::Predicate Pred,
4462 const SCEV *LHS, const SCEV *RHS) {
4463 // Interpret a null as meaning no loop, where there is obviously no guard
4464 // (interprocedural conditions notwithstanding).
4465 if (!L) return true;
4466
4467 BasicBlock *Latch = L->getLoopLatch();
4468 if (!Latch)
4469 return false;
4470
4471 BranchInst *LoopContinuePredicate =
4472 dyn_cast<BranchInst>(Latch->getTerminator());
4473 if (!LoopContinuePredicate ||
4474 LoopContinuePredicate->isUnconditional())
4475 return false;
4476
Dan Gohman0f4b2852009-07-21 23:03:19 +00004477 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4478 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004479}
4480
4481/// isLoopGuardedByCond - Test whether entry to the loop is protected
4482/// by a conditional between LHS and RHS. This is used to help avoid max
4483/// expressions in loop trip counts, and to eliminate casts.
4484bool
4485ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4486 ICmpInst::Predicate Pred,
4487 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004488 // Interpret a null as meaning no loop, where there is obviously no guard
4489 // (interprocedural conditions notwithstanding).
4490 if (!L) return false;
4491
Dan Gohman859b4822009-05-18 15:36:09 +00004492 BasicBlock *Predecessor = getLoopPredecessor(L);
4493 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004494
Dan Gohman859b4822009-05-18 15:36:09 +00004495 // Starting at the loop predecessor, climb up the predecessor chain, as long
4496 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004497 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004498 for (; Predecessor;
4499 PredecessorDest = Predecessor,
4500 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004501
4502 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004503 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004504 if (!LoopEntryPredicate ||
4505 LoopEntryPredicate->isUnconditional())
4506 continue;
4507
Dan Gohman0f4b2852009-07-21 23:03:19 +00004508 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4509 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004510 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004511 }
4512
Dan Gohman38372182008-08-12 20:17:31 +00004513 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004514}
4515
Dan Gohman0f4b2852009-07-21 23:03:19 +00004516/// isImpliedCond - Test whether the condition described by Pred, LHS,
4517/// and RHS is true whenever the given Cond value evaluates to true.
4518bool ScalarEvolution::isImpliedCond(Value *CondValue,
4519 ICmpInst::Predicate Pred,
4520 const SCEV *LHS, const SCEV *RHS,
4521 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004522 // Recursivly handle And and Or conditions.
4523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4524 if (BO->getOpcode() == Instruction::And) {
4525 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004526 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4527 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004528 } else if (BO->getOpcode() == Instruction::Or) {
4529 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004530 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4531 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004532 }
4533 }
4534
4535 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4536 if (!ICI) return false;
4537
Dan Gohman85b05a22009-07-13 21:35:55 +00004538 // Bail if the ICmp's operands' types are wider than the needed type
4539 // before attempting to call getSCEV on them. This avoids infinite
4540 // recursion, since the analysis of widening casts can require loop
4541 // exit condition information for overflow checking, which would
4542 // lead back here.
4543 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004544 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004545 return false;
4546
Dan Gohman0f4b2852009-07-21 23:03:19 +00004547 // Now that we found a conditional branch that dominates the loop, check to
4548 // see if it is the comparison we are looking for.
4549 ICmpInst::Predicate FoundPred;
4550 if (Inverse)
4551 FoundPred = ICI->getInversePredicate();
4552 else
4553 FoundPred = ICI->getPredicate();
4554
4555 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4556 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004557
4558 // Balance the types. The case where FoundLHS' type is wider than
4559 // LHS' type is checked for above.
4560 if (getTypeSizeInBits(LHS->getType()) >
4561 getTypeSizeInBits(FoundLHS->getType())) {
4562 if (CmpInst::isSigned(Pred)) {
4563 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4564 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4565 } else {
4566 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4567 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4568 }
4569 }
4570
Dan Gohman0f4b2852009-07-21 23:03:19 +00004571 // Canonicalize the query to match the way instcombine will have
4572 // canonicalized the comparison.
4573 // First, put a constant operand on the right.
4574 if (isa<SCEVConstant>(LHS)) {
4575 std::swap(LHS, RHS);
4576 Pred = ICmpInst::getSwappedPredicate(Pred);
4577 }
4578 // Then, canonicalize comparisons with boundary cases.
4579 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4580 const APInt &RA = RC->getValue()->getValue();
4581 switch (Pred) {
4582 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4583 case ICmpInst::ICMP_EQ:
4584 case ICmpInst::ICMP_NE:
4585 break;
4586 case ICmpInst::ICMP_UGE:
4587 if ((RA - 1).isMinValue()) {
4588 Pred = ICmpInst::ICMP_NE;
4589 RHS = getConstant(RA - 1);
4590 break;
4591 }
4592 if (RA.isMaxValue()) {
4593 Pred = ICmpInst::ICMP_EQ;
4594 break;
4595 }
4596 if (RA.isMinValue()) return true;
4597 break;
4598 case ICmpInst::ICMP_ULE:
4599 if ((RA + 1).isMaxValue()) {
4600 Pred = ICmpInst::ICMP_NE;
4601 RHS = getConstant(RA + 1);
4602 break;
4603 }
4604 if (RA.isMinValue()) {
4605 Pred = ICmpInst::ICMP_EQ;
4606 break;
4607 }
4608 if (RA.isMaxValue()) return true;
4609 break;
4610 case ICmpInst::ICMP_SGE:
4611 if ((RA - 1).isMinSignedValue()) {
4612 Pred = ICmpInst::ICMP_NE;
4613 RHS = getConstant(RA - 1);
4614 break;
4615 }
4616 if (RA.isMaxSignedValue()) {
4617 Pred = ICmpInst::ICMP_EQ;
4618 break;
4619 }
4620 if (RA.isMinSignedValue()) return true;
4621 break;
4622 case ICmpInst::ICMP_SLE:
4623 if ((RA + 1).isMaxSignedValue()) {
4624 Pred = ICmpInst::ICMP_NE;
4625 RHS = getConstant(RA + 1);
4626 break;
4627 }
4628 if (RA.isMinSignedValue()) {
4629 Pred = ICmpInst::ICMP_EQ;
4630 break;
4631 }
4632 if (RA.isMaxSignedValue()) return true;
4633 break;
4634 case ICmpInst::ICMP_UGT:
4635 if (RA.isMinValue()) {
4636 Pred = ICmpInst::ICMP_NE;
4637 break;
4638 }
4639 if ((RA + 1).isMaxValue()) {
4640 Pred = ICmpInst::ICMP_EQ;
4641 RHS = getConstant(RA + 1);
4642 break;
4643 }
4644 if (RA.isMaxValue()) return false;
4645 break;
4646 case ICmpInst::ICMP_ULT:
4647 if (RA.isMaxValue()) {
4648 Pred = ICmpInst::ICMP_NE;
4649 break;
4650 }
4651 if ((RA - 1).isMinValue()) {
4652 Pred = ICmpInst::ICMP_EQ;
4653 RHS = getConstant(RA - 1);
4654 break;
4655 }
4656 if (RA.isMinValue()) return false;
4657 break;
4658 case ICmpInst::ICMP_SGT:
4659 if (RA.isMinSignedValue()) {
4660 Pred = ICmpInst::ICMP_NE;
4661 break;
4662 }
4663 if ((RA + 1).isMaxSignedValue()) {
4664 Pred = ICmpInst::ICMP_EQ;
4665 RHS = getConstant(RA + 1);
4666 break;
4667 }
4668 if (RA.isMaxSignedValue()) return false;
4669 break;
4670 case ICmpInst::ICMP_SLT:
4671 if (RA.isMaxSignedValue()) {
4672 Pred = ICmpInst::ICMP_NE;
4673 break;
4674 }
4675 if ((RA - 1).isMinSignedValue()) {
4676 Pred = ICmpInst::ICMP_EQ;
4677 RHS = getConstant(RA - 1);
4678 break;
4679 }
4680 if (RA.isMinSignedValue()) return false;
4681 break;
4682 }
4683 }
4684
4685 // Check to see if we can make the LHS or RHS match.
4686 if (LHS == FoundRHS || RHS == FoundLHS) {
4687 if (isa<SCEVConstant>(RHS)) {
4688 std::swap(FoundLHS, FoundRHS);
4689 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4690 } else {
4691 std::swap(LHS, RHS);
4692 Pred = ICmpInst::getSwappedPredicate(Pred);
4693 }
4694 }
4695
4696 // Check whether the found predicate is the same as the desired predicate.
4697 if (FoundPred == Pred)
4698 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4699
4700 // Check whether swapping the found predicate makes it the same as the
4701 // desired predicate.
4702 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4703 if (isa<SCEVConstant>(RHS))
4704 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4705 else
4706 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4707 RHS, LHS, FoundLHS, FoundRHS);
4708 }
4709
4710 // Check whether the actual condition is beyond sufficient.
4711 if (FoundPred == ICmpInst::ICMP_EQ)
4712 if (ICmpInst::isTrueWhenEqual(Pred))
4713 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4714 return true;
4715 if (Pred == ICmpInst::ICMP_NE)
4716 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4717 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4718 return true;
4719
4720 // Otherwise assume the worst.
4721 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004722}
4723
Dan Gohman0f4b2852009-07-21 23:03:19 +00004724/// isImpliedCondOperands - Test whether the condition described by Pred,
4725/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4726/// and FoundRHS is true.
4727bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4728 const SCEV *LHS, const SCEV *RHS,
4729 const SCEV *FoundLHS,
4730 const SCEV *FoundRHS) {
4731 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4732 FoundLHS, FoundRHS) ||
4733 // ~x < ~y --> x > y
4734 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4735 getNotSCEV(FoundRHS),
4736 getNotSCEV(FoundLHS));
4737}
4738
4739/// isImpliedCondOperandsHelper - Test whether the condition described by
4740/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4741/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004742bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004743ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4744 const SCEV *LHS, const SCEV *RHS,
4745 const SCEV *FoundLHS,
4746 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004747 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004748 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4749 case ICmpInst::ICMP_EQ:
4750 case ICmpInst::ICMP_NE:
4751 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4752 return true;
4753 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004754 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004755 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004756 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4757 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4758 return true;
4759 break;
4760 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004761 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004762 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4763 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4764 return true;
4765 break;
4766 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004767 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004768 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4769 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4770 return true;
4771 break;
4772 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004773 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004774 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4775 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4776 return true;
4777 break;
4778 }
4779
4780 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004781}
4782
Dan Gohman51f53b72009-06-21 23:46:38 +00004783/// getBECount - Subtract the end and start values and divide by the step,
4784/// rounding up, to get the number of times the backedge is executed. Return
4785/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004786const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004787 const SCEV *End,
4788 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004789 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004790 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4791 const SCEV *Diff = getMinusSCEV(End, Start);
4792 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004793
4794 // Add an adjustment to the difference between End and Start so that
4795 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004796 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004797
4798 // Check Add for unsigned overflow.
4799 // TODO: More sophisticated things could be done here.
Owen Anderson1d0be152009-08-13 21:58:54 +00004800 const Type *WideTy = IntegerType::get(getContext(),
4801 getTypeSizeInBits(Ty) + 1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004802 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4803 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4804 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004805 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004806 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004807
4808 return getUDivExpr(Add, Step);
4809}
4810
Chris Lattnerdb25de42005-08-15 23:33:51 +00004811/// HowManyLessThans - Return the number of times a backedge containing the
4812/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004813/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004814ScalarEvolution::BackedgeTakenInfo
4815ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4816 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004817 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004818 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004819
Dan Gohman35738ac2009-05-04 22:30:44 +00004820 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004821 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004822 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004823
4824 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004825 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004826 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004827 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004828
4829 // TODO: handle non-constant strides.
4830 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4831 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004832 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004833 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004834 // With unit stride, the iteration never steps past the limit value.
4835 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4836 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4837 // Test whether a positive iteration iteration can step past the limit
4838 // value and past the maximum value for its type in a single step.
4839 if (isSigned) {
4840 APInt Max = APInt::getSignedMaxValue(BitWidth);
4841 if ((Max - CStep->getValue()->getValue())
4842 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004843 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004844 } else {
4845 APInt Max = APInt::getMaxValue(BitWidth);
4846 if ((Max - CStep->getValue()->getValue())
4847 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004848 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004849 }
4850 } else
4851 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004852 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004853 } else
4854 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004855 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004856
Dan Gohmana1af7572009-04-30 20:47:05 +00004857 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4858 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4859 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004860 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004861
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004862 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004863 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004864
Dan Gohmana1af7572009-04-30 20:47:05 +00004865 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004866 const SCEV *MinStart = getConstant(isSigned ?
4867 getSignedRange(Start).getSignedMin() :
4868 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004869
Dan Gohmana1af7572009-04-30 20:47:05 +00004870 // If we know that the condition is true in order to enter the loop,
4871 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004872 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4873 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004874 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004875 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004876 isSigned ? ICmpInst::ICMP_SLT :
4877 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004878 getMinusSCEV(Start, Step), RHS))
4879 End = isSigned ? getSMaxExpr(RHS, Start)
4880 : getUMaxExpr(RHS, Start);
4881
4882 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004883 const SCEV *MaxEnd = getConstant(isSigned ?
4884 getSignedRange(End).getSignedMax() :
4885 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004886
4887 // Finally, we subtract these two values and divide, rounding up, to get
4888 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004889 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004890
4891 // The maximum backedge count is similar, except using the minimum start
4892 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004893 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004894
4895 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004896 }
4897
Dan Gohman1c343752009-06-27 21:21:31 +00004898 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004899}
4900
Chris Lattner53e677a2004-04-02 20:23:17 +00004901/// getNumIterationsInRange - Return the number of iterations of this loop that
4902/// produce values in the specified constant range. Another way of looking at
4903/// this is that it returns the first iteration number where the value is not in
4904/// the condition, thus computing the exit count. If the iteration count can't
4905/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004906const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004907 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004908 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004909 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004910
4911 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004912 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004913 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004914 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004915 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004916 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004917 if (const SCEVAddRecExpr *ShiftedAddRec =
4918 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004919 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004920 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004921 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004922 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004923 }
4924
4925 // The only time we can solve this is when we have all constant indices.
4926 // Otherwise, we cannot determine the overflow conditions.
4927 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4928 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004929 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004930
4931
4932 // Okay at this point we know that all elements of the chrec are constants and
4933 // that the start element is zero.
4934
4935 // First check to see if the range contains zero. If not, the first
4936 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004937 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004938 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004939 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004940
Chris Lattner53e677a2004-04-02 20:23:17 +00004941 if (isAffine()) {
4942 // If this is an affine expression then we have this situation:
4943 // Solve {0,+,A} in Range === Ax in Range
4944
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004945 // We know that zero is in the range. If A is positive then we know that
4946 // the upper value of the range must be the first possible exit value.
4947 // If A is negative then the lower of the range is the last possible loop
4948 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004949 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004950 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4951 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004952
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004953 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004954 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00004955 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004956
4957 // Evaluate at the exit value. If we really did fall out of the valid
4958 // range, then we computed our trip count, otherwise wrap around or other
4959 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004960 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004961 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004962 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004963
4964 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004965 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004966 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00004967 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004968 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004969 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004970 } else if (isQuadratic()) {
4971 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4972 // quadratic equation to solve it. To do this, we must frame our problem in
4973 // terms of figuring out when zero is crossed, instead of when
4974 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004975 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004976 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004977 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004978
4979 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004980 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004981 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004982 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4983 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004984 if (R1) {
4985 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004986 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004987 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00004988 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004989 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004990 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004991
Chris Lattner53e677a2004-04-02 20:23:17 +00004992 // Make sure the root is not off by one. The returned iteration should
4993 // not be in the range, but the previous one should be. When solving
4994 // for "X*X < 5", for example, we should not return a root of 2.
4995 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004996 R1->getValue(),
4997 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004998 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004999 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005000 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005001 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005002
Dan Gohman246b2562007-10-22 18:31:58 +00005003 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005004 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005005 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005006 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005007 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005008
Chris Lattner53e677a2004-04-02 20:23:17 +00005009 // If R1 was not in the range, then it is a good return value. Make
5010 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005011 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005012 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005013 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005014 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005015 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005016 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005017 }
5018 }
5019 }
5020
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005021 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005022}
5023
5024
5025
5026//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005027// SCEVCallbackVH Class Implementation
5028//===----------------------------------------------------------------------===//
5029
Dan Gohman1959b752009-05-19 19:22:47 +00005030void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005031 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005032 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5033 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00005034 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
5035 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00005036 SE->Scalars.erase(getValPtr());
5037 // this now dangles!
5038}
5039
Dan Gohman1959b752009-05-19 19:22:47 +00005040void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005041 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005042
5043 // Forget all the expressions associated with users of the old value,
5044 // so that future queries will recompute the expressions using the new
5045 // value.
5046 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005047 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005048 Value *Old = getValPtr();
5049 bool DeleteOld = false;
5050 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5051 UI != UE; ++UI)
5052 Worklist.push_back(*UI);
5053 while (!Worklist.empty()) {
5054 User *U = Worklist.pop_back_val();
5055 // Deleting the Old value will cause this to dangle. Postpone
5056 // that until everything else is done.
5057 if (U == Old) {
5058 DeleteOld = true;
5059 continue;
5060 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005061 if (!Visited.insert(U))
5062 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005063 if (PHINode *PN = dyn_cast<PHINode>(U))
5064 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00005065 if (Instruction *I = dyn_cast<Instruction>(U))
5066 SE->ValuesAtScopes.erase(I);
Dan Gohman69fcae92009-07-14 14:34:04 +00005067 SE->Scalars.erase(U);
5068 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5069 UI != UE; ++UI)
5070 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005071 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005072 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005073 if (DeleteOld) {
5074 if (PHINode *PN = dyn_cast<PHINode>(Old))
5075 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00005076 if (Instruction *I = dyn_cast<Instruction>(Old))
5077 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00005078 SE->Scalars.erase(Old);
5079 // this now dangles!
5080 }
5081 // this may dangle!
5082}
5083
Dan Gohman1959b752009-05-19 19:22:47 +00005084ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005085 : CallbackVH(V), SE(se) {}
5086
5087//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005088// ScalarEvolution Class Implementation
5089//===----------------------------------------------------------------------===//
5090
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005091ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005092 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005093}
5094
Chris Lattner53e677a2004-04-02 20:23:17 +00005095bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005096 this->F = &F;
5097 LI = &getAnalysis<LoopInfo>();
5098 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005099 return false;
5100}
5101
5102void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005103 Scalars.clear();
5104 BackedgeTakenCounts.clear();
5105 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005106 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005107 UniqueSCEVs.clear();
5108 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005109}
5110
5111void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5112 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005113 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005114}
5115
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005116bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005117 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005118}
5119
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005120static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005121 const Loop *L) {
5122 // Print all inner loops first
5123 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5124 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005125
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005126 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005127
Devang Patelb7211a22007-08-21 00:31:24 +00005128 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005129 L->getExitBlocks(ExitBlocks);
5130 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005131 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005132
Dan Gohman46bdfb02009-02-24 18:55:53 +00005133 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5134 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005135 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005136 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005137 }
5138
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005139 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005140 OS << "Loop " << L->getHeader()->getName() << ": ";
5141
5142 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5143 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5144 } else {
5145 OS << "Unpredictable max backedge-taken count. ";
5146 }
5147
5148 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005149}
5150
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005151void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005152 // ScalarEvolution's implementaiton of the print method is to print
5153 // out SCEV values of all instructions that are interesting. Doing
5154 // this potentially causes it to create new SCEV objects though,
5155 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005156 // observable from outside the class though, so casting away the
5157 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005158 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005159
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005160 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005161 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005162 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005163 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005164 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005165 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005166 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005167
Dan Gohman0c689c52009-06-19 17:49:54 +00005168 const Loop *L = LI->getLoopFor((*I).getParent());
5169
Dan Gohman0bba49c2009-07-07 17:06:11 +00005170 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005171 if (AtUse != SV) {
5172 OS << " --> ";
5173 AtUse->print(OS);
5174 }
5175
5176 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005177 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005178 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005179 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005180 OS << "<<Unknown>>";
5181 } else {
5182 OS << *ExitValue;
5183 }
5184 }
5185
Chris Lattner53e677a2004-04-02 20:23:17 +00005186 OS << "\n";
5187 }
5188
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005189 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5190 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5191 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005192}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005193