blob: 4c58131853427d0bf4d93d1882dcc473f6f6c988 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000144 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000181 new (S) SCEVConstant(ID.Intern(SCEVAllocator), 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 Gohmanc93b4cf2010-03-18 16:16:38 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohman6e70e312009-09-27 15:26:03 +0000210bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
212}
213
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000214SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000217 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
218 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000229 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
230 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000234void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000238SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000241 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
242 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000243 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000251 assert(NumOperands > 1 && "This plus expr shouldn't exist!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000254 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
Dan Gohmanecb403a2009-05-07 14:00:19 +0000259bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
262 return false;
263 }
264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
270 return false;
271 }
272 return true;
273}
274
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000275bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
277}
278
Dan Gohman6e70e312009-09-27 15:26:03 +0000279bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
281}
282
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000283void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000284 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000285}
286
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294}
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000297 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000298 if (!QueryLoop)
299 return false;
300
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000302 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000303 return false;
304
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
306 // are variant.
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
309 return false;
310
311 // Otherwise it's loop-invariant.
312 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000313}
314
Dan Gohman39125d82010-02-13 00:19:39 +0000315bool
316SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
317 return DT->dominates(L->getHeader(), BB) &&
318 SCEVNAryExpr::dominates(BB, DT);
319}
320
321bool
322SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
323 // This uses a "dominates" query instead of "properly dominates" query because
324 // the instruction which produces the addrec's value is a PHI, and a PHI
325 // effectively properly dominates its entire containing block.
326 return DT->dominates(L->getHeader(), BB) &&
327 SCEVNAryExpr::properlyDominates(BB, DT);
328}
329
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000330void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000332 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000333 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000334 OS << "}<";
335 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
336 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
Chris Lattner53e677a2004-04-02 20:23:17 +0000338
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000339bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
340 // All non-instruction values are loop invariant. All instructions are loop
341 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000342 // Instructions are never considered invariant in the function body
343 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000344 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000345 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000346 return true;
347}
Chris Lattner53e677a2004-04-02 20:23:17 +0000348
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000349bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
350 if (Instruction *I = dyn_cast<Instruction>(getValue()))
351 return DT->dominates(I->getParent(), BB);
352 return true;
353}
354
Dan Gohman6e70e312009-09-27 15:26:03 +0000355bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
356 if (Instruction *I = dyn_cast<Instruction>(getValue()))
357 return DT->properlyDominates(I->getParent(), BB);
358 return true;
359}
360
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361const Type *SCEVUnknown::getType() const {
362 return V->getType();
363}
Chris Lattner53e677a2004-04-02 20:23:17 +0000364
Dan Gohman0f5efe52010-01-28 02:15:55 +0000365bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
366 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
367 if (VCE->getOpcode() == Instruction::PtrToInt)
368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000369 if (CE->getOpcode() == Instruction::GetElementPtr &&
370 CE->getOperand(0)->isNullValue() &&
371 CE->getNumOperands() == 2)
372 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
373 if (CI->isOne()) {
374 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
375 ->getElementType();
376 return true;
377 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000378
379 return false;
380}
381
382bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
384 if (VCE->getOpcode() == Instruction::PtrToInt)
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000386 if (CE->getOpcode() == Instruction::GetElementPtr &&
387 CE->getOperand(0)->isNullValue()) {
388 const Type *Ty =
389 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
390 if (const StructType *STy = dyn_cast<StructType>(Ty))
391 if (!STy->isPacked() &&
392 CE->getNumOperands() == 3 &&
393 CE->getOperand(1)->isNullValue()) {
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
395 if (CI->isOne() &&
396 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000397 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000398 AllocTy = STy->getElementType(1);
399 return true;
400 }
401 }
402 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000403
404 return false;
405}
406
Dan Gohman4f8eea82010-02-01 18:27:38 +0000407bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getNumOperands() == 3 &&
413 CE->getOperand(0)->isNullValue() &&
414 CE->getOperand(1)->isNullValue()) {
415 const Type *Ty =
416 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
417 // Ignore vector types here so that ScalarEvolutionExpander doesn't
418 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000419 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000420 CTy = Ty;
421 FieldNo = CE->getOperand(2);
422 return true;
423 }
424 }
425
426 return false;
427}
428
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000429void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000430 const Type *AllocTy;
431 if (isSizeOf(AllocTy)) {
432 OS << "sizeof(" << *AllocTy << ")";
433 return;
434 }
435 if (isAlignOf(AllocTy)) {
436 OS << "alignof(" << *AllocTy << ")";
437 return;
438 }
439
Dan Gohman4f8eea82010-02-01 18:27:38 +0000440 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000441 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000442 if (isOffsetOf(CTy, FieldNo)) {
443 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000444 WriteAsOperand(OS, FieldNo, false);
445 OS << ")";
446 return;
447 }
448
449 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000450 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000451}
452
Chris Lattner8d741b82004-06-20 06:23:15 +0000453//===----------------------------------------------------------------------===//
454// SCEV Utilities
455//===----------------------------------------------------------------------===//
456
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000457static bool CompareTypes(const Type *A, const Type *B) {
458 if (A->getTypeID() != B->getTypeID())
459 return A->getTypeID() < B->getTypeID();
460 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
461 const IntegerType *BI = cast<IntegerType>(B);
462 return AI->getBitWidth() < BI->getBitWidth();
463 }
464 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
465 const PointerType *BI = cast<PointerType>(B);
466 return CompareTypes(AI->getElementType(), BI->getElementType());
467 }
468 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
469 const ArrayType *BI = cast<ArrayType>(B);
470 if (AI->getNumElements() != BI->getNumElements())
471 return AI->getNumElements() < BI->getNumElements();
472 return CompareTypes(AI->getElementType(), BI->getElementType());
473 }
474 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
475 const VectorType *BI = cast<VectorType>(B);
476 if (AI->getNumElements() != BI->getNumElements())
477 return AI->getNumElements() < BI->getNumElements();
478 return CompareTypes(AI->getElementType(), BI->getElementType());
479 }
480 if (const StructType *AI = dyn_cast<StructType>(A)) {
481 const StructType *BI = cast<StructType>(B);
482 if (AI->getNumElements() != BI->getNumElements())
483 return AI->getNumElements() < BI->getNumElements();
484 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
485 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
486 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
487 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
488 }
489 return false;
490}
491
Chris Lattner8d741b82004-06-20 06:23:15 +0000492namespace {
493 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
494 /// than the complexity of the RHS. This comparator is used to canonicalize
495 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000496 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000497 LoopInfo *LI;
498 public:
499 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
500
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000501 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000502 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
503 if (LHS == RHS)
504 return false;
505
Dan Gohman72861302009-05-07 14:39:04 +0000506 // Primarily, sort the SCEVs by their getSCEVType().
507 if (LHS->getSCEVType() != RHS->getSCEVType())
508 return LHS->getSCEVType() < RHS->getSCEVType();
509
510 // Aside from the getSCEVType() ordering, the particular ordering
511 // isn't very important except that it's beneficial to be consistent,
512 // so that (a + b) and (b + a) don't end up as different expressions.
513
514 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
515 // not as complete as it could be.
516 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
517 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
518
Dan Gohman5be18e82009-05-19 02:15:55 +0000519 // Order pointer values after integer values. This helps SCEVExpander
520 // form GEPs.
Duncan Sands1df98592010-02-16 11:11:14 +0000521 if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
Dan Gohman5be18e82009-05-19 02:15:55 +0000522 return false;
Duncan Sands1df98592010-02-16 11:11:14 +0000523 if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
Dan Gohman5be18e82009-05-19 02:15:55 +0000524 return true;
525
Dan Gohman72861302009-05-07 14:39:04 +0000526 // Compare getValueID values.
527 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
528 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
529
530 // Sort arguments by their position.
531 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
532 const Argument *RA = cast<Argument>(RU->getValue());
533 return LA->getArgNo() < RA->getArgNo();
534 }
535
536 // For instructions, compare their loop depth, and their opcode.
537 // This is pretty loose.
538 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
539 Instruction *RV = cast<Instruction>(RU->getValue());
540
541 // Compare loop depths.
542 if (LI->getLoopDepth(LV->getParent()) !=
543 LI->getLoopDepth(RV->getParent()))
544 return LI->getLoopDepth(LV->getParent()) <
545 LI->getLoopDepth(RV->getParent());
546
547 // Compare opcodes.
548 if (LV->getOpcode() != RV->getOpcode())
549 return LV->getOpcode() < RV->getOpcode();
550
551 // Compare the number of operands.
552 if (LV->getNumOperands() != RV->getNumOperands())
553 return LV->getNumOperands() < RV->getNumOperands();
554 }
555
556 return false;
557 }
558
Dan Gohman4dfad292009-06-14 22:51:25 +0000559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000562 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
563 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000564 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
565 }
566
567 // Compare addrec loop depths.
568 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
569 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
570 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
571 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
572 }
Dan Gohman72861302009-05-07 14:39:04 +0000573
574 // Lexicographically compare n-ary expressions.
575 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
576 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
577 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
578 if (i >= RC->getNumOperands())
579 return false;
580 if (operator()(LC->getOperand(i), RC->getOperand(i)))
581 return true;
582 if (operator()(RC->getOperand(i), LC->getOperand(i)))
583 return false;
584 }
585 return LC->getNumOperands() < RC->getNumOperands();
586 }
587
Dan Gohmana6b35e22009-05-07 19:23:21 +0000588 // Lexicographically compare udiv expressions.
589 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
590 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
591 if (operator()(LC->getLHS(), RC->getLHS()))
592 return true;
593 if (operator()(RC->getLHS(), LC->getLHS()))
594 return false;
595 if (operator()(LC->getRHS(), RC->getRHS()))
596 return true;
597 if (operator()(RC->getRHS(), LC->getRHS()))
598 return false;
599 return false;
600 }
601
Dan Gohman72861302009-05-07 14:39:04 +0000602 // Compare cast expressions by operand.
603 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
604 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
605 return operator()(LC->getOperand(), RC->getOperand());
606 }
607
Torok Edwinc23197a2009-07-14 16:55:14 +0000608 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000609 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000610 }
611 };
612}
613
614/// GroupByComplexity - Given a list of SCEV objects, order them by their
615/// complexity, and group objects of the same complexity together by value.
616/// When this routine is finished, we know that any duplicates in the vector are
617/// consecutive and that complexity is monotonically increasing.
618///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000619/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000620/// results from this routine. In other words, we don't want the results of
621/// this to depend on where the addresses of various SCEV objects happened to
622/// land in memory.
623///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000624static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000625 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000626 if (Ops.size() < 2) return; // Noop
627 if (Ops.size() == 2) {
628 // This is the common case, which also happens to be trivially simple.
629 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000630 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000631 std::swap(Ops[0], Ops[1]);
632 return;
633 }
634
635 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000636 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000637
638 // Now that we are sorted by complexity, group elements of the same
639 // complexity. Note that this is, at worst, N^2, but the vector is likely to
640 // be extremely short in practice. Note that we take this approach because we
641 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000642 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000643 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000644 unsigned Complexity = S->getSCEVType();
645
646 // If there are any objects of the same complexity and same value as this
647 // one, group them.
648 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
649 if (Ops[j] == S) { // Found a duplicate.
650 // Move it to immediately after i'th element.
651 std::swap(Ops[i+1], Ops[j]);
652 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000653 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000654 }
655 }
656 }
657}
658
Chris Lattner53e677a2004-04-02 20:23:17 +0000659
Chris Lattner53e677a2004-04-02 20:23:17 +0000660
661//===----------------------------------------------------------------------===//
662// Simple SCEV method implementations
663//===----------------------------------------------------------------------===//
664
Eli Friedmanb42a6262008-08-04 23:49:06 +0000665/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000666/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000667static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000668 ScalarEvolution &SE,
669 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000670 // Handle the simplest case efficiently.
671 if (K == 1)
672 return SE.getTruncateOrZeroExtend(It, ResultTy);
673
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674 // We are using the following formula for BC(It, K):
675 //
676 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
677 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000678 // Suppose, W is the bitwidth of the return value. We must be prepared for
679 // overflow. Hence, we must assure that the result of our computation is
680 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
681 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000682 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000683 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000684 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000685 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
686 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000687 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000689 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000690 // This formula is trivially equivalent to the previous formula. However,
691 // this formula can be implemented much more efficiently. The trick is that
692 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
693 // arithmetic. To do exact division in modular arithmetic, all we have
694 // to do is multiply by the inverse. Therefore, this step can be done at
695 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000696 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000697 // The next issue is how to safely do the division by 2^T. The way this
698 // is done is by doing the multiplication step at a width of at least W + T
699 // bits. This way, the bottom W+T bits of the product are accurate. Then,
700 // when we perform the division by 2^T (which is equivalent to a right shift
701 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
702 // truncated out after the division by 2^T.
703 //
704 // In comparison to just directly using the first formula, this technique
705 // is much more efficient; using the first formula requires W * K bits,
706 // but this formula less than W + K bits. Also, the first formula requires
707 // a division step, whereas this formula only requires multiplies and shifts.
708 //
709 // It doesn't matter whether the subtraction step is done in the calculation
710 // width or the input iteration count's width; if the subtraction overflows,
711 // the result must be zero anyway. We prefer here to do it in the width of
712 // the induction variable because it helps a lot for certain cases; CodeGen
713 // isn't smart enough to ignore the overflow, which leads to much less
714 // efficient code if the width of the subtraction is wider than the native
715 // register width.
716 //
717 // (It's possible to not widen at all by pulling out factors of 2 before
718 // the multiplication; for example, K=2 can be calculated as
719 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
720 // extra arithmetic, so it's not an obvious win, and it gets
721 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000722
Eli Friedmanb42a6262008-08-04 23:49:06 +0000723 // Protection from insane SCEVs; this bound is conservative,
724 // but it probably doesn't matter.
725 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000726 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000727
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000728 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000729
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730 // Calculate K! / 2^T and T; we divide out the factors of two before
731 // multiplying for calculating K! / 2^T to avoid overflow.
732 // Other overflow doesn't matter because we only care about the bottom
733 // W bits of the result.
734 APInt OddFactorial(W, 1);
735 unsigned T = 1;
736 for (unsigned i = 3; i <= K; ++i) {
737 APInt Mult(W, i);
738 unsigned TwoFactors = Mult.countTrailingZeros();
739 T += TwoFactors;
740 Mult = Mult.lshr(TwoFactors);
741 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000742 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000743
Eli Friedmanb42a6262008-08-04 23:49:06 +0000744 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000745 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000746
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000747 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000748 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
749
750 // Calculate the multiplicative inverse of K! / 2^T;
751 // this multiplication factor will perform the exact division by
752 // K! / 2^T.
753 APInt Mod = APInt::getSignedMinValue(W+1);
754 APInt MultiplyFactor = OddFactorial.zext(W+1);
755 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
756 MultiplyFactor = MultiplyFactor.trunc(W);
757
758 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000759 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
760 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000761 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000762 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000763 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000764 Dividend = SE.getMulExpr(Dividend,
765 SE.getTruncateOrZeroExtend(S, CalculationTy));
766 }
767
768 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000769 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000770
771 // Truncate the result, and divide by K! / 2^T.
772
773 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
774 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000775}
776
Chris Lattner53e677a2004-04-02 20:23:17 +0000777/// evaluateAtIteration - Return the value of this chain of recurrences at
778/// the specified iteration number. We can evaluate this recurrence by
779/// multiplying each element in the chain by the binomial coefficient
780/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
781///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000782/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000783///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000784/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000785///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000786const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000787 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000788 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000790 // The computation is correct in the face of overflow provided that the
791 // multiplication is performed _after_ the evaluation of the binomial
792 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000793 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000794 if (isa<SCEVCouldNotCompute>(Coeff))
795 return Coeff;
796
797 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000798 }
799 return Result;
800}
801
Chris Lattner53e677a2004-04-02 20:23:17 +0000802//===----------------------------------------------------------------------===//
803// SCEV Expression folder implementations
804//===----------------------------------------------------------------------===//
805
Dan Gohman0bba49c2009-07-07 17:06:11 +0000806const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000807 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000808 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000809 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000810 assert(isSCEVable(Ty) &&
811 "This is not a conversion to a SCEVable type!");
812 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000813
Dan Gohmanc050fd92009-07-13 20:50:19 +0000814 FoldingSetNodeID ID;
815 ID.AddInteger(scTruncate);
816 ID.AddPointer(Op);
817 ID.AddPointer(Ty);
818 void *IP = 0;
819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
820
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000821 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000822 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000823 return getConstant(
824 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000825
Dan Gohman20900ca2009-04-22 16:20:48 +0000826 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000827 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000828 return getTruncateExpr(ST->getOperand(), Ty);
829
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000830 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000831 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000832 return getTruncateOrSignExtend(SS->getOperand(), Ty);
833
834 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000835 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000836 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
837
Dan Gohman6864db62009-06-18 16:24:47 +0000838 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000839 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000841 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000842 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
843 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000844 }
845
Dan Gohmanc050fd92009-07-13 20:50:19 +0000846 // The cast wasn't folded; create an explicit cast node.
847 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000848 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
849 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000850 new (S) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000851 UniqueSCEVs.InsertNode(S, IP);
852 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000853}
854
Dan Gohman0bba49c2009-07-07 17:06:11 +0000855const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000856 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000857 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000858 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000859 assert(isSCEVable(Ty) &&
860 "This is not a conversion to a SCEVable type!");
861 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000862
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000863 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000864 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000865 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000866 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
867 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000868 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000869 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000870
Dan Gohman20900ca2009-04-22 16:20:48 +0000871 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000872 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000873 return getZeroExtendExpr(SZ->getOperand(), Ty);
874
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000875 // Before doing any expensive analysis, check to see if we've already
876 // computed a SCEV for this Op and Ty.
877 FoldingSetNodeID ID;
878 ID.AddInteger(scZeroExtend);
879 ID.AddPointer(Op);
880 ID.AddPointer(Ty);
881 void *IP = 0;
882 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
883
Dan Gohman01ecca22009-04-27 20:16:15 +0000884 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000885 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000886 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000887 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000888 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000889 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000890 const SCEV *Start = AR->getStart();
891 const SCEV *Step = AR->getStepRecurrence(*this);
892 unsigned BitWidth = getTypeSizeInBits(AR->getType());
893 const Loop *L = AR->getLoop();
894
Dan Gohmaneb490a72009-07-25 01:22:26 +0000895 // If we have special knowledge that this addrec won't overflow,
896 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000897 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000898 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
899 getZeroExtendExpr(Step, Ty),
900 L);
901
Dan Gohman01ecca22009-04-27 20:16:15 +0000902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000910 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000912 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000913 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000914
915 // Check whether the backedge-taken count can be losslessly casted to
916 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000917 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000918 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000919 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000920 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
921 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000922 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000923 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000924 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000925 const SCEV *Add = getAddExpr(Start, ZMul);
926 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000927 getAddExpr(getZeroExtendExpr(Start, WideTy),
928 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
929 getZeroExtendExpr(Step, WideTy)));
930 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000931 // Return the expression with the addrec on the outside.
932 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
933 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000934 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000935
936 // Similar to above, only this time treat the step value as signed.
937 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000938 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000939 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000940 OperandExtendedAdd =
941 getAddExpr(getZeroExtendExpr(Start, WideTy),
942 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
943 getSignExtendExpr(Step, WideTy)));
944 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000945 // Return the expression with the addrec on the outside.
946 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
947 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000948 L);
949 }
950
951 // If the backedge is guarded by a comparison with the pre-inc value
952 // the addrec is safe. Also, if the entry is guarded by a comparison
953 // with the start value and the backedge is guarded by a comparison
954 // with the post-inc value, the addrec is safe.
955 if (isKnownPositive(Step)) {
956 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
957 getUnsignedRange(Step).getUnsignedMax());
958 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
959 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
960 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
961 AR->getPostIncExpr(*this), N)))
962 // Return the expression with the addrec on the outside.
963 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
964 getZeroExtendExpr(Step, Ty),
965 L);
966 } else if (isKnownNegative(Step)) {
967 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
968 getSignedRange(Step).getSignedMin());
969 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
970 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
971 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
972 AR->getPostIncExpr(*this), N)))
973 // Return the expression with the addrec on the outside.
974 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
975 getSignExtendExpr(Step, Ty),
976 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000977 }
978 }
979 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000980
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000981 // The cast wasn't folded; create an explicit cast node.
982 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000983 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
984 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc93b4cf2010-03-18 16:16:38 +0000985 new (S) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000986 UniqueSCEVs.InsertNode(S, IP);
987 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000988}
989
Dan Gohman0bba49c2009-07-07 17:06:11 +0000990const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000991 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000993 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000994 assert(isSCEVable(Ty) &&
995 "This is not a conversion to a SCEVable type!");
996 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000997
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000998 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001000 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001001 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1002 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001003 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +00001004 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001005
Dan Gohman20900ca2009-04-22 16:20:48 +00001006 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001007 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001008 return getSignExtendExpr(SS->getOperand(), Ty);
1009
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001010 // Before doing any expensive analysis, check to see if we've already
1011 // computed a SCEV for this Op and Ty.
1012 FoldingSetNodeID ID;
1013 ID.AddInteger(scSignExtend);
1014 ID.AddPointer(Op);
1015 ID.AddPointer(Ty);
1016 void *IP = 0;
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1018
Dan Gohman01ecca22009-04-27 20:16:15 +00001019 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001020 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001021 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001022 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001023 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001024 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001025 const SCEV *Start = AR->getStart();
1026 const SCEV *Step = AR->getStepRecurrence(*this);
1027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1028 const Loop *L = AR->getLoop();
1029
Dan Gohmaneb490a72009-07-25 01:22:26 +00001030 // If we have special knowledge that this addrec won't overflow,
1031 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001032 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001033 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1034 getSignExtendExpr(Step, Ty),
1035 L);
1036
Dan Gohman01ecca22009-04-27 20:16:15 +00001037 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1038 // Note that this serves two purposes: It filters out loops that are
1039 // simply not analyzable, and it covers the case where this code is
1040 // being called from within backedge-taken count analysis, such that
1041 // attempting to ask for the backedge-taken count would likely result
1042 // in infinite recursion. In the later case, the analysis code will
1043 // cope with a conservative value, and it will take care to purge
1044 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001045 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001046 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001047 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001048 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001049
1050 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001051 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001052 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001053 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001054 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001055 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1056 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001057 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001058 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001059 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001060 const SCEV *Add = getAddExpr(Start, SMul);
1061 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001062 getAddExpr(getSignExtendExpr(Start, WideTy),
1063 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1064 getSignExtendExpr(Step, WideTy)));
1065 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001066 // Return the expression with the addrec on the outside.
1067 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1068 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001069 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001070
1071 // Similar to above, only this time treat the step value as unsigned.
1072 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001073 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001074 Add = getAddExpr(Start, UMul);
1075 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001076 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001077 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1078 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001079 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getZeroExtendExpr(Step, Ty),
1083 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001084 }
1085
1086 // If the backedge is guarded by a comparison with the pre-inc value
1087 // the addrec is safe. Also, if the entry is guarded by a comparison
1088 // with the start value and the backedge is guarded by a comparison
1089 // with the post-inc value, the addrec is safe.
1090 if (isKnownPositive(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1092 getSignedRange(Step).getSignedMax());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1094 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1096 AR->getPostIncExpr(*this), N)))
1097 // Return the expression with the addrec on the outside.
1098 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1099 getSignExtendExpr(Step, Ty),
1100 L);
1101 } else if (isKnownNegative(Step)) {
1102 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1103 getSignedRange(Step).getSignedMin());
1104 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1105 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1106 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1107 AR->getPostIncExpr(*this), N)))
1108 // Return the expression with the addrec on the outside.
1109 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1110 getSignExtendExpr(Step, Ty),
1111 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001112 }
1113 }
1114 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001115
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001116 // The cast wasn't folded; create an explicit cast node.
1117 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1119 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00001120 new (S) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001121 UniqueSCEVs.InsertNode(S, IP);
1122 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001123}
1124
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001125/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1126/// unspecified bits out to the given type.
1127///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001128const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001129 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001130 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1131 "This is not an extending conversion!");
1132 assert(isSCEVable(Ty) &&
1133 "This is not a conversion to a SCEVable type!");
1134 Ty = getEffectiveSCEVType(Ty);
1135
1136 // Sign-extend negative constants.
1137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1138 if (SC->getValue()->getValue().isNegative())
1139 return getSignExtendExpr(Op, Ty);
1140
1141 // Peel off a truncate cast.
1142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001143 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001144 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1145 return getAnyExtendExpr(NewOp, Ty);
1146 return getTruncateOrNoop(NewOp, Ty);
1147 }
1148
1149 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001150 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001151 if (!isa<SCEVZeroExtendExpr>(ZExt))
1152 return ZExt;
1153
1154 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001155 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001156 if (!isa<SCEVSignExtendExpr>(SExt))
1157 return SExt;
1158
Dan Gohmana10756e2010-01-21 02:09:26 +00001159 // Force the cast to be folded into the operands of an addrec.
1160 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1161 SmallVector<const SCEV *, 4> Ops;
1162 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1163 I != E; ++I)
1164 Ops.push_back(getAnyExtendExpr(*I, Ty));
1165 return getAddRecExpr(Ops, AR->getLoop());
1166 }
1167
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001168 // If the expression is obviously signed, use the sext cast value.
1169 if (isa<SCEVSMaxExpr>(Op))
1170 return SExt;
1171
1172 // Absent any other information, use the zext cast value.
1173 return ZExt;
1174}
1175
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001176/// CollectAddOperandsWithScales - Process the given Ops list, which is
1177/// a list of operands to be added under the given scale, update the given
1178/// map. This is a helper function for getAddRecExpr. As an example of
1179/// what it does, given a sequence of operands that would form an add
1180/// expression like this:
1181///
1182/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1183///
1184/// where A and B are constants, update the map with these values:
1185///
1186/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1187///
1188/// and add 13 + A*B*29 to AccumulatedConstant.
1189/// This will allow getAddRecExpr to produce this:
1190///
1191/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1192///
1193/// This form often exposes folding opportunities that are hidden in
1194/// the original operand list.
1195///
1196/// Return true iff it appears that any interesting folding opportunities
1197/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1198/// the common case where no interesting opportunities are present, and
1199/// is also used as a check to avoid infinite recursion.
1200///
1201static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001202CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1203 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001204 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001205 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001206 const APInt &Scale,
1207 ScalarEvolution &SE) {
1208 bool Interesting = false;
1209
1210 // Iterate over the add operands.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001211 for (unsigned i = 0, e = NumOperands; i != e; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001212 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1213 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1214 APInt NewScale =
1215 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1216 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1217 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001218 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001219 Interesting |=
1220 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001221 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001222 NewScale, SE);
1223 } else {
1224 // A multiplication of a constant with some other value. Update
1225 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001226 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1227 const SCEV *Key = SE.getMulExpr(MulOps);
1228 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001229 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001230 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001231 NewOps.push_back(Pair.first->first);
1232 } else {
1233 Pair.first->second += NewScale;
1234 // The map already had an entry for this value, which may indicate
1235 // a folding opportunity.
1236 Interesting = true;
1237 }
1238 }
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // Pull a buried constant out to the outside.
1241 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1242 Interesting = true;
1243 AccumulatedConstant += Scale * C->getValue()->getValue();
1244 } else {
1245 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001246 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001247 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001248 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001249 NewOps.push_back(Pair.first->first);
1250 } else {
1251 Pair.first->second += Scale;
1252 // The map already had an entry for this value, which may indicate
1253 // a folding opportunity.
1254 Interesting = true;
1255 }
1256 }
1257 }
1258
1259 return Interesting;
1260}
1261
1262namespace {
1263 struct APIntCompare {
1264 bool operator()(const APInt &LHS, const APInt &RHS) const {
1265 return LHS.ult(RHS);
1266 }
1267 };
1268}
1269
Dan Gohman6c0866c2009-05-24 23:45:28 +00001270/// getAddExpr - Get a canonical add expression, or something simpler if
1271/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001272const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1273 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001274 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001275 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001276#ifndef NDEBUG
1277 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1278 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1279 getEffectiveSCEVType(Ops[0]->getType()) &&
1280 "SCEVAddExpr operand types don't match!");
1281#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001282
Dan Gohmana10756e2010-01-21 02:09:26 +00001283 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1284 if (!HasNUW && HasNSW) {
1285 bool All = true;
1286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1287 if (!isKnownNonNegative(Ops[i])) {
1288 All = false;
1289 break;
1290 }
1291 if (All) HasNUW = true;
1292 }
1293
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001295 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001296
1297 // If there are any constants, fold them together.
1298 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001301 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001304 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1305 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001306 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001307 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001308 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001309 }
1310
1311 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001312 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001313 Ops.erase(Ops.begin());
1314 --Idx;
1315 }
1316 }
1317
Chris Lattner627018b2004-04-07 16:16:11 +00001318 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001319
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 // Okay, check to see if the same value occurs in the operand list twice. If
1321 // so, merge them together into an multiply expression. Since we sorted the
1322 // list, these values are required to be adjacent.
1323 const Type *Ty = Ops[0]->getType();
1324 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1325 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1326 // Found a match, merge the two values into a multiply, and add any
1327 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001328 const SCEV *Two = getIntegerSCEV(2, Ty);
1329 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 if (Ops.size() == 2)
1331 return Mul;
1332 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1333 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001334 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 }
1336
Dan Gohman728c7f32009-05-08 21:03:19 +00001337 // Check for truncates. If all the operands are truncated from the same
1338 // type, see if factoring out the truncate would permit the result to be
1339 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1340 // if the contents of the resulting outer trunc fold to something simple.
1341 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1342 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1343 const Type *DstType = Trunc->getType();
1344 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001345 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001346 bool Ok = true;
1347 // Check all the operands to see if they can be represented in the
1348 // source type of the truncate.
1349 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1350 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1351 if (T->getOperand()->getType() != SrcType) {
1352 Ok = false;
1353 break;
1354 }
1355 LargeOps.push_back(T->getOperand());
1356 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1357 // This could be either sign or zero extension, but sign extension
1358 // is much more likely to be foldable here.
1359 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1360 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001361 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001362 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1363 if (const SCEVTruncateExpr *T =
1364 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1365 if (T->getOperand()->getType() != SrcType) {
1366 Ok = false;
1367 break;
1368 }
1369 LargeMulOps.push_back(T->getOperand());
1370 } else if (const SCEVConstant *C =
1371 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1372 // This could be either sign or zero extension, but sign extension
1373 // is much more likely to be foldable here.
1374 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1375 } else {
1376 Ok = false;
1377 break;
1378 }
1379 }
1380 if (Ok)
1381 LargeOps.push_back(getMulExpr(LargeMulOps));
1382 } else {
1383 Ok = false;
1384 break;
1385 }
1386 }
1387 if (Ok) {
1388 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001389 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001390 // If it folds to something simple, use it. Otherwise, don't.
1391 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1392 return getTruncateExpr(Fold, DstType);
1393 }
1394 }
1395
1396 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001397 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1398 ++Idx;
1399
1400 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 if (Idx < Ops.size()) {
1402 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001403 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // If we have an add, expand the add operands onto the end of the operands
1405 // list.
1406 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1407 Ops.erase(Ops.begin()+Idx);
1408 DeletedAdd = true;
1409 }
1410
1411 // If we deleted at least one add, we added operands to the end of the list,
1412 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001413 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001414 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001415 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001416 }
1417
1418 // Skip over the add expression until we get to a multiply.
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1420 ++Idx;
1421
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001422 // Check to see if there are any folding opportunities present with
1423 // operands multiplied by constant values.
1424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1425 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001426 DenseMap<const SCEV *, APInt> M;
1427 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001428 APInt AccumulatedConstant(BitWidth, 0);
1429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001430 Ops.data(), Ops.size(),
1431 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001432 // Some interesting folding opportunity is present, so its worthwhile to
1433 // re-generate the operands list. Group the operands by constant scale,
1434 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001435 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1436 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001437 E = NewOps.end(); I != E; ++I)
1438 MulOpLists[M.find(*I)->second].push_back(*I);
1439 // Re-generate the operands list.
1440 Ops.clear();
1441 if (AccumulatedConstant != 0)
1442 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001443 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1444 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001445 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001446 Ops.push_back(getMulExpr(getConstant(I->first),
1447 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001448 if (Ops.empty())
1449 return getIntegerSCEV(0, Ty);
1450 if (Ops.size() == 1)
1451 return Ops[0];
1452 return getAddExpr(Ops);
1453 }
1454 }
1455
Chris Lattner53e677a2004-04-02 20:23:17 +00001456 // If we are adding something to a multiply expression, make sure the
1457 // something is not already an operand of the multiply. If so, merge it into
1458 // the multiply.
1459 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001460 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001461 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001462 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001464 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001466 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 if (Mul->getNumOperands() != 2) {
1468 // If the multiply has more than two operands, we must get the
1469 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001470 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001472 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001473 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001474 const SCEV *One = getIntegerSCEV(1, Ty);
1475 const SCEV *AddOne = getAddExpr(InnerMul, One);
1476 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 if (Ops.size() == 2) return OuterMul;
1478 if (AddOp < Idx) {
1479 Ops.erase(Ops.begin()+AddOp);
1480 Ops.erase(Ops.begin()+Idx-1);
1481 } else {
1482 Ops.erase(Ops.begin()+Idx);
1483 Ops.erase(Ops.begin()+AddOp-1);
1484 }
1485 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001486 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001487 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001488
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 // Check this multiply against other multiplies being added together.
1490 for (unsigned OtherMulIdx = Idx+1;
1491 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1492 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001493 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 // If MulOp occurs in OtherMul, we can fold the two multiplies
1495 // together.
1496 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1497 OMulOp != e; ++OMulOp)
1498 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1499 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001500 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001501 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001502 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1503 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001505 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001506 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001507 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001509 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1510 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001512 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001514 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1515 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001516 if (Ops.size() == 2) return OuterMul;
1517 Ops.erase(Ops.begin()+Idx);
1518 Ops.erase(Ops.begin()+OtherMulIdx-1);
1519 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001520 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001521 }
1522 }
1523 }
1524 }
1525
1526 // If there are any add recurrences in the operands list, see if any other
1527 // added values are loop invariant. If so, we can fold them into the
1528 // recurrence.
1529 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1530 ++Idx;
1531
1532 // Scan over all recurrences, trying to fold loop invariants into them.
1533 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1534 // Scan all of the other operands to this add and add them to the vector if
1535 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001536 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001537 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1539 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1540 LIOps.push_back(Ops[i]);
1541 Ops.erase(Ops.begin()+i);
1542 --i; --e;
1543 }
1544
1545 // If we found some loop invariants, fold them into the recurrence.
1546 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001547 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 LIOps.push_back(AddRec->getStart());
1549
Dan Gohman0bba49c2009-07-07 17:06:11 +00001550 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001551 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001552 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001553
Dan Gohman355b4f32009-12-19 01:46:34 +00001554 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001555 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001556 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001557
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 // If all of the other operands were loop invariant, we are done.
1559 if (Ops.size() == 1) return NewRec;
1560
1561 // Otherwise, add the folded AddRec by the non-liv parts.
1562 for (unsigned i = 0;; ++i)
1563 if (Ops[i] == AddRec) {
1564 Ops[i] = NewRec;
1565 break;
1566 }
Dan Gohman246b2562007-10-22 18:31:58 +00001567 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 }
1569
1570 // Okay, if there weren't any loop invariants to be folded, check to see if
1571 // there are multiple AddRec's with the same loop induction variable being
1572 // added together. If so, we can fold them.
1573 for (unsigned OtherIdx = Idx+1;
1574 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1575 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001576 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001577 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1578 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001579 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1580 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001581 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1582 if (i >= NewOps.size()) {
1583 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1584 OtherAddRec->op_end());
1585 break;
1586 }
Dan Gohman246b2562007-10-22 18:31:58 +00001587 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001588 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001589 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001590
1591 if (Ops.size() == 2) return NewAddRec;
1592
1593 Ops.erase(Ops.begin()+Idx);
1594 Ops.erase(Ops.begin()+OtherIdx-1);
1595 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001596 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 }
1598 }
1599
1600 // Otherwise couldn't fold anything into this recurrence. Move onto the
1601 // next one.
1602 }
1603
1604 // Okay, it looks like we really DO need an add expr. Check to see if we
1605 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001606 FoldingSetNodeID ID;
1607 ID.AddInteger(scAddExpr);
1608 ID.AddInteger(Ops.size());
1609 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1610 ID.AddPointer(Ops[i]);
1611 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001612 SCEVAddExpr *S =
1613 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1614 if (!S) {
1615 S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanf9e64722010-03-18 01:17:13 +00001616 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1617 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00001618 new (S) SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001619 UniqueSCEVs.InsertNode(S, IP);
1620 }
Dan Gohman3645b012009-10-09 00:10:36 +00001621 if (HasNUW) S->setHasNoUnsignedWrap(true);
1622 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001623 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001624}
1625
Dan Gohman6c0866c2009-05-24 23:45:28 +00001626/// getMulExpr - Get a canonical multiply expression, or something simpler if
1627/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001628const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1629 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001631 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001632#ifndef NDEBUG
1633 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1634 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1635 getEffectiveSCEVType(Ops[0]->getType()) &&
1636 "SCEVMulExpr operand types don't match!");
1637#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001638
Dan Gohmana10756e2010-01-21 02:09:26 +00001639 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1640 if (!HasNUW && HasNSW) {
1641 bool All = true;
1642 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1643 if (!isKnownNonNegative(Ops[i])) {
1644 All = false;
1645 break;
1646 }
1647 if (All) HasNUW = true;
1648 }
1649
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001651 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001652
1653 // If there are any constants, fold them together.
1654 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001655 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001656
1657 // C1*(C2+V) -> C1*C2 + C1*V
1658 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001659 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001660 if (Add->getNumOperands() == 2 &&
1661 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001662 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1663 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001664
Chris Lattner53e677a2004-04-02 20:23:17 +00001665 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001666 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001667 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001668 ConstantInt *Fold = ConstantInt::get(getContext(),
1669 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001670 RHSC->getValue()->getValue());
1671 Ops[0] = getConstant(Fold);
1672 Ops.erase(Ops.begin()+1); // Erase the folded element
1673 if (Ops.size() == 1) return Ops[0];
1674 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001675 }
1676
1677 // If we are left with a constant one being multiplied, strip it off.
1678 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1679 Ops.erase(Ops.begin());
1680 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001681 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 // If we have a multiply of zero, it will always be zero.
1683 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001684 } else if (Ops[0]->isAllOnesValue()) {
1685 // If we have a mul by -1 of an add, try distributing the -1 among the
1686 // add operands.
1687 if (Ops.size() == 2)
1688 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1689 SmallVector<const SCEV *, 4> NewOps;
1690 bool AnyFolded = false;
1691 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1692 I != E; ++I) {
1693 const SCEV *Mul = getMulExpr(Ops[0], *I);
1694 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1695 NewOps.push_back(Mul);
1696 }
1697 if (AnyFolded)
1698 return getAddExpr(NewOps);
1699 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001700 }
1701 }
1702
1703 // Skip over the add expression until we get to a multiply.
1704 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1705 ++Idx;
1706
1707 if (Ops.size() == 1)
1708 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001709
Chris Lattner53e677a2004-04-02 20:23:17 +00001710 // If there are mul operands inline them all into this expression.
1711 if (Idx < Ops.size()) {
1712 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001713 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001714 // If we have an mul, expand the mul operands onto the end of the operands
1715 // list.
1716 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1717 Ops.erase(Ops.begin()+Idx);
1718 DeletedMul = true;
1719 }
1720
1721 // If we deleted at least one mul, we added operands to the end of the list,
1722 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001723 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001724 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001725 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001726 }
1727
1728 // If there are any add recurrences in the operands list, see if any other
1729 // added values are loop invariant. If so, we can fold them into the
1730 // recurrence.
1731 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1732 ++Idx;
1733
1734 // Scan over all recurrences, trying to fold loop invariants into them.
1735 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1736 // Scan all of the other operands to this mul and add them to the vector if
1737 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001738 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001739 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001740 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1741 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1742 LIOps.push_back(Ops[i]);
1743 Ops.erase(Ops.begin()+i);
1744 --i; --e;
1745 }
1746
1747 // If we found some loop invariants, fold them into the recurrence.
1748 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001749 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001750 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 NewOps.reserve(AddRec->getNumOperands());
1752 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001753 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001754 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001755 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001756 } else {
1757 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001758 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001759 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001760 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001761 }
1762 }
1763
Dan Gohman355b4f32009-12-19 01:46:34 +00001764 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001765 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001766 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1767 HasNUW && AddRec->hasNoUnsignedWrap(),
1768 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001769
1770 // If all of the other operands were loop invariant, we are done.
1771 if (Ops.size() == 1) return NewRec;
1772
1773 // Otherwise, multiply the folded AddRec by the non-liv parts.
1774 for (unsigned i = 0;; ++i)
1775 if (Ops[i] == AddRec) {
1776 Ops[i] = NewRec;
1777 break;
1778 }
Dan Gohman246b2562007-10-22 18:31:58 +00001779 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001780 }
1781
1782 // Okay, if there weren't any loop invariants to be folded, check to see if
1783 // there are multiple AddRec's with the same loop induction variable being
1784 // multiplied together. If so, we can fold them.
1785 for (unsigned OtherIdx = Idx+1;
1786 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1787 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001788 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001789 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1790 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001791 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001792 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001793 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001794 const SCEV *B = F->getStepRecurrence(*this);
1795 const SCEV *D = G->getStepRecurrence(*this);
1796 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001797 getMulExpr(G, B),
1798 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001799 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001800 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001801 if (Ops.size() == 2) return NewAddRec;
1802
1803 Ops.erase(Ops.begin()+Idx);
1804 Ops.erase(Ops.begin()+OtherIdx-1);
1805 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001806 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001807 }
1808 }
1809
1810 // Otherwise couldn't fold anything into this recurrence. Move onto the
1811 // next one.
1812 }
1813
1814 // Okay, it looks like we really DO need an mul expr. Check to see if we
1815 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001816 FoldingSetNodeID ID;
1817 ID.AddInteger(scMulExpr);
1818 ID.AddInteger(Ops.size());
1819 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1820 ID.AddPointer(Ops[i]);
1821 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001822 SCEVMulExpr *S =
1823 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1824 if (!S) {
1825 S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanf9e64722010-03-18 01:17:13 +00001826 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1827 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00001828 new (S) SCEVMulExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001829 UniqueSCEVs.InsertNode(S, IP);
1830 }
Dan Gohman3645b012009-10-09 00:10:36 +00001831 if (HasNUW) S->setHasNoUnsignedWrap(true);
1832 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001833 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001834}
1835
Andreas Bolka8a11c982009-08-07 22:55:26 +00001836/// getUDivExpr - Get a canonical unsigned division expression, or something
1837/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001838const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1839 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001840 assert(getEffectiveSCEVType(LHS->getType()) ==
1841 getEffectiveSCEVType(RHS->getType()) &&
1842 "SCEVUDivExpr operand types don't match!");
1843
Dan Gohman622ed672009-05-04 22:02:23 +00001844 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001845 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001846 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001847 if (RHSC->isZero())
1848 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001849
Dan Gohman185cf032009-05-08 20:18:49 +00001850 // Determine if the division can be folded into the operands of
1851 // its operands.
1852 // TODO: Generalize this to non-constants by using known-bits information.
1853 const Type *Ty = LHS->getType();
1854 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1855 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1856 // For non-power-of-two values, effectively round the value up to the
1857 // nearest power of two.
1858 if (!RHSC->getValue()->getValue().isPowerOf2())
1859 ++MaxShiftAmt;
1860 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001861 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001862 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1863 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1864 if (const SCEVConstant *Step =
1865 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1866 if (!Step->getValue()->getValue()
1867 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001868 getZeroExtendExpr(AR, ExtTy) ==
1869 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1870 getZeroExtendExpr(Step, ExtTy),
1871 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001872 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001873 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1874 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1875 return getAddRecExpr(Operands, AR->getLoop());
1876 }
1877 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001878 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001879 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001880 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1881 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1882 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001883 // Find an operand that's safely divisible.
1884 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001885 const SCEV *Op = M->getOperand(i);
1886 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001887 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001888 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), M->op_end());
Dan Gohman185cf032009-05-08 20:18:49 +00001889 Operands[i] = Div;
1890 return getMulExpr(Operands);
1891 }
1892 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001893 }
Dan Gohman185cf032009-05-08 20:18:49 +00001894 // (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 +00001895 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001896 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001897 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1898 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1899 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1900 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001901 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001902 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001903 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1904 break;
1905 Operands.push_back(Op);
1906 }
1907 if (Operands.size() == A->getNumOperands())
1908 return getAddExpr(Operands);
1909 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001910 }
Dan Gohman185cf032009-05-08 20:18:49 +00001911
1912 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001913 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001914 Constant *LHSCV = LHSC->getValue();
1915 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001916 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001917 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001918 }
1919 }
1920
Dan Gohman1c343752009-06-27 21:21:31 +00001921 FoldingSetNodeID ID;
1922 ID.AddInteger(scUDivExpr);
1923 ID.AddPointer(LHS);
1924 ID.AddPointer(RHS);
1925 void *IP = 0;
1926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1927 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00001928 new (S) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001929 UniqueSCEVs.InsertNode(S, IP);
1930 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001931}
1932
1933
Dan Gohman6c0866c2009-05-24 23:45:28 +00001934/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1935/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001936const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001937 const SCEV *Step, const Loop *L,
1938 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001939 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001940 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001941 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001942 if (StepChrec->getLoop() == L) {
1943 Operands.insert(Operands.end(), StepChrec->op_begin(),
1944 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001945 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001946 }
1947
1948 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001949 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001950}
1951
Dan Gohman6c0866c2009-05-24 23:45:28 +00001952/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1953/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001954const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001955ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001956 const Loop *L,
1957 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001958 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001959#ifndef NDEBUG
1960 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1961 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1962 getEffectiveSCEVType(Operands[0]->getType()) &&
1963 "SCEVAddRecExpr operand types don't match!");
1964#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001965
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001966 if (Operands.back()->isZero()) {
1967 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001968 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001969 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001970
Dan Gohmanbc028532010-02-19 18:49:22 +00001971 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1972 // use that information to infer NUW and NSW flags. However, computing a
1973 // BE count requires calling getAddRecExpr, so we may not yet have a
1974 // meaningful BE count at this point (and if we don't, we'd be stuck
1975 // with a SCEVCouldNotCompute as the cached BE count).
1976
Dan Gohmana10756e2010-01-21 02:09:26 +00001977 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1978 if (!HasNUW && HasNSW) {
1979 bool All = true;
1980 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1981 if (!isKnownNonNegative(Operands[i])) {
1982 All = false;
1983 break;
1984 }
1985 if (All) HasNUW = true;
1986 }
1987
Dan Gohmand9cc7492008-08-08 18:33:12 +00001988 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001989 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001990 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001991 if (L->contains(NestedLoop->getHeader()) ?
1992 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1993 (!NestedLoop->contains(L->getHeader()) &&
1994 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001995 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001996 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001997 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001998 // AddRecs require their operands be loop-invariant with respect to their
1999 // loops. Don't perform this transformation if it would break this
2000 // requirement.
2001 bool AllInvariant = true;
2002 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2003 if (!Operands[i]->isLoopInvariant(L)) {
2004 AllInvariant = false;
2005 break;
2006 }
2007 if (AllInvariant) {
2008 NestedOperands[0] = getAddRecExpr(Operands, L);
2009 AllInvariant = true;
2010 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2011 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2012 AllInvariant = false;
2013 break;
2014 }
2015 if (AllInvariant)
2016 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002017 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002018 }
2019 // Reset Operands to its original state.
2020 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002021 }
2022 }
2023
Dan Gohman67847532010-01-19 22:27:22 +00002024 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2025 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002026 FoldingSetNodeID ID;
2027 ID.AddInteger(scAddRecExpr);
2028 ID.AddInteger(Operands.size());
2029 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2030 ID.AddPointer(Operands[i]);
2031 ID.AddPointer(L);
2032 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002033 SCEVAddRecExpr *S =
2034 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2035 if (!S) {
2036 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanf9e64722010-03-18 01:17:13 +00002037 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2038 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00002039 new (S) SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002040 UniqueSCEVs.InsertNode(S, IP);
2041 }
Dan Gohman3645b012009-10-09 00:10:36 +00002042 if (HasNUW) S->setHasNoUnsignedWrap(true);
2043 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002044 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002045}
2046
Dan Gohman9311ef62009-06-24 14:49:00 +00002047const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2048 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002049 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002050 Ops.push_back(LHS);
2051 Ops.push_back(RHS);
2052 return getSMaxExpr(Ops);
2053}
2054
Dan Gohman0bba49c2009-07-07 17:06:11 +00002055const SCEV *
2056ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002057 assert(!Ops.empty() && "Cannot get empty smax!");
2058 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002059#ifndef NDEBUG
2060 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2061 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2062 getEffectiveSCEVType(Ops[0]->getType()) &&
2063 "SCEVSMaxExpr operand types don't match!");
2064#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002065
2066 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002067 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002068
2069 // If there are any constants, fold them together.
2070 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002071 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002072 ++Idx;
2073 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002074 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002075 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002076 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002077 APIntOps::smax(LHSC->getValue()->getValue(),
2078 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002079 Ops[0] = getConstant(Fold);
2080 Ops.erase(Ops.begin()+1); // Erase the folded element
2081 if (Ops.size() == 1) return Ops[0];
2082 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002083 }
2084
Dan Gohmane5aceed2009-06-24 14:46:22 +00002085 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002086 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2087 Ops.erase(Ops.begin());
2088 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002089 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2090 // If we have an smax with a constant maximum-int, it will always be
2091 // maximum-int.
2092 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002093 }
2094 }
2095
2096 if (Ops.size() == 1) return Ops[0];
2097
2098 // Find the first SMax
2099 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2100 ++Idx;
2101
2102 // Check to see if one of the operands is an SMax. If so, expand its operands
2103 // onto our operand list, and recurse to simplify.
2104 if (Idx < Ops.size()) {
2105 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002106 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002107 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2108 Ops.erase(Ops.begin()+Idx);
2109 DeletedSMax = true;
2110 }
2111
2112 if (DeletedSMax)
2113 return getSMaxExpr(Ops);
2114 }
2115
2116 // Okay, check to see if the same value occurs in the operand list twice. If
2117 // so, delete one. Since we sorted the list, these values are required to
2118 // be adjacent.
2119 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2120 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2121 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2122 --i; --e;
2123 }
2124
2125 if (Ops.size() == 1) return Ops[0];
2126
2127 assert(!Ops.empty() && "Reduced smax down to nothing!");
2128
Nick Lewycky3e630762008-02-20 06:48:22 +00002129 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002130 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002131 FoldingSetNodeID ID;
2132 ID.AddInteger(scSMaxExpr);
2133 ID.AddInteger(Ops.size());
2134 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2135 ID.AddPointer(Ops[i]);
2136 void *IP = 0;
2137 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2138 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanf9e64722010-03-18 01:17:13 +00002139 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2140 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00002141 new (S) SCEVSMaxExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002142 UniqueSCEVs.InsertNode(S, IP);
2143 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002144}
2145
Dan Gohman9311ef62009-06-24 14:49:00 +00002146const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2147 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002148 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002149 Ops.push_back(LHS);
2150 Ops.push_back(RHS);
2151 return getUMaxExpr(Ops);
2152}
2153
Dan Gohman0bba49c2009-07-07 17:06:11 +00002154const SCEV *
2155ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002156 assert(!Ops.empty() && "Cannot get empty umax!");
2157 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002158#ifndef NDEBUG
2159 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2160 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2161 getEffectiveSCEVType(Ops[0]->getType()) &&
2162 "SCEVUMaxExpr operand types don't match!");
2163#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002164
2165 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002166 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002167
2168 // If there are any constants, fold them together.
2169 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002170 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002171 ++Idx;
2172 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002173 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002174 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002175 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002176 APIntOps::umax(LHSC->getValue()->getValue(),
2177 RHSC->getValue()->getValue()));
2178 Ops[0] = getConstant(Fold);
2179 Ops.erase(Ops.begin()+1); // Erase the folded element
2180 if (Ops.size() == 1) return Ops[0];
2181 LHSC = cast<SCEVConstant>(Ops[0]);
2182 }
2183
Dan Gohmane5aceed2009-06-24 14:46:22 +00002184 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002185 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2186 Ops.erase(Ops.begin());
2187 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002188 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2189 // If we have an umax with a constant maximum-int, it will always be
2190 // maximum-int.
2191 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002192 }
2193 }
2194
2195 if (Ops.size() == 1) return Ops[0];
2196
2197 // Find the first UMax
2198 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2199 ++Idx;
2200
2201 // Check to see if one of the operands is a UMax. If so, expand its operands
2202 // onto our operand list, and recurse to simplify.
2203 if (Idx < Ops.size()) {
2204 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002205 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002206 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2207 Ops.erase(Ops.begin()+Idx);
2208 DeletedUMax = true;
2209 }
2210
2211 if (DeletedUMax)
2212 return getUMaxExpr(Ops);
2213 }
2214
2215 // Okay, check to see if the same value occurs in the operand list twice. If
2216 // so, delete one. Since we sorted the list, these values are required to
2217 // be adjacent.
2218 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2219 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2220 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2221 --i; --e;
2222 }
2223
2224 if (Ops.size() == 1) return Ops[0];
2225
2226 assert(!Ops.empty() && "Reduced umax down to nothing!");
2227
2228 // Okay, it looks like we really DO need a umax expr. Check to see if we
2229 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002230 FoldingSetNodeID ID;
2231 ID.AddInteger(scUMaxExpr);
2232 ID.AddInteger(Ops.size());
2233 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2234 ID.AddPointer(Ops[i]);
2235 void *IP = 0;
2236 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2237 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanf9e64722010-03-18 01:17:13 +00002238 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2239 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00002240 new (S) SCEVUMaxExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002241 UniqueSCEVs.InsertNode(S, IP);
2242 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002243}
2244
Dan Gohman9311ef62009-06-24 14:49:00 +00002245const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2246 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002247 // ~smax(~x, ~y) == smin(x, y).
2248 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2249}
2250
Dan Gohman9311ef62009-06-24 14:49:00 +00002251const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2252 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002253 // ~umax(~x, ~y) == umin(x, y)
2254 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2255}
2256
Dan Gohman4f8eea82010-02-01 18:27:38 +00002257const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2258 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2259 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2260 C = ConstantFoldConstantExpression(CE, TD);
2261 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2262 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2263}
2264
2265const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2266 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2268 C = ConstantFoldConstantExpression(CE, TD);
2269 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2270 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2271}
2272
2273const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2274 unsigned FieldNo) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002275 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2276 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2277 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002278 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002279 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002280}
2281
Dan Gohman4f8eea82010-02-01 18:27:38 +00002282const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2283 Constant *FieldNo) {
2284 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2286 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohman4f8eea82010-02-01 18:27:38 +00002287 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002288 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002289}
2290
Dan Gohman0bba49c2009-07-07 17:06:11 +00002291const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002292 // Don't attempt to do anything other than create a SCEVUnknown object
2293 // here. createSCEV only calls getUnknown after checking for all other
2294 // interesting possibilities, and any other code that calls getUnknown
2295 // is doing so in order to hide a value from SCEV canonicalization.
2296
Dan Gohman1c343752009-06-27 21:21:31 +00002297 FoldingSetNodeID ID;
2298 ID.AddInteger(scUnknown);
2299 ID.AddPointer(V);
2300 void *IP = 0;
2301 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2302 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc93b4cf2010-03-18 16:16:38 +00002303 new (S) SCEVUnknown(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +00002304 UniqueSCEVs.InsertNode(S, IP);
2305 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002306}
2307
Chris Lattner53e677a2004-04-02 20:23:17 +00002308//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002309// Basic SCEV Analysis and PHI Idiom Recognition Code
2310//
2311
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002312/// isSCEVable - Test if values of the given type are analyzable within
2313/// the SCEV framework. This primarily includes integer types, and it
2314/// can optionally include pointer types if the ScalarEvolution class
2315/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002316bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002317 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002318 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002319}
2320
2321/// getTypeSizeInBits - Return the size in bits of the specified type,
2322/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002323uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002324 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2325
2326 // If we have a TargetData, use it!
2327 if (TD)
2328 return TD->getTypeSizeInBits(Ty);
2329
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002330 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002331 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002332 return Ty->getPrimitiveSizeInBits();
2333
2334 // The only other support type is pointer. Without TargetData, conservatively
2335 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002336 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002337 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002338}
2339
2340/// getEffectiveSCEVType - Return a type with the same bitwidth as
2341/// the given type and which represents how SCEV will treat the given
2342/// type, for which isSCEVable must return true. For pointer types,
2343/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002344const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002345 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2346
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002347 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002348 return Ty;
2349
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002350 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002351 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002352 if (TD) return TD->getIntPtrType(getContext());
2353
2354 // Without TargetData, conservatively assume pointers are 64-bit.
2355 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002356}
Chris Lattner53e677a2004-04-02 20:23:17 +00002357
Dan Gohman0bba49c2009-07-07 17:06:11 +00002358const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002359 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002360}
2361
Chris Lattner53e677a2004-04-02 20:23:17 +00002362/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2363/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002364const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002365 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002366
Dan Gohman0bba49c2009-07-07 17:06:11 +00002367 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002368 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002369 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002370 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002371 return S;
2372}
2373
Dan Gohman6bbcba12009-06-24 00:54:57 +00002374/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002375/// specified signed integer value and return a SCEV for the constant.
Dan Gohman32efba62010-02-04 02:43:51 +00002376const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002377 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002378 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002379}
2380
2381/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2382///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002383const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002384 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002385 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002386 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002387
2388 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002389 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002390 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002391 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002392}
2393
2394/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002395const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002396 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002397 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002398 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002399
2400 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002401 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002402 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002403 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002404 return getMinusSCEV(AllOnes, V);
2405}
2406
2407/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2408///
Dan Gohman9311ef62009-06-24 14:49:00 +00002409const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2410 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002411 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002412 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002413}
2414
2415/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2416/// input value to the specified type. If the type must be extended, it is zero
2417/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002418const SCEV *
2419ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002420 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002421 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002422 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2423 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002424 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002425 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002426 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002427 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002428 return getTruncateExpr(V, Ty);
2429 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002430}
2431
2432/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2433/// input value to the specified type. If the type must be extended, it is sign
2434/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002435const SCEV *
2436ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002437 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002438 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002439 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2440 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002441 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002442 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002443 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002444 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002445 return getTruncateExpr(V, Ty);
2446 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002447}
2448
Dan Gohman467c4302009-05-13 03:46:30 +00002449/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2450/// input value to the specified type. If the type must be extended, it is zero
2451/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002452const SCEV *
2453ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002454 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002455 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2456 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002457 "Cannot noop or zero extend with non-integer arguments!");
2458 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2459 "getNoopOrZeroExtend cannot truncate!");
2460 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2461 return V; // No conversion
2462 return getZeroExtendExpr(V, Ty);
2463}
2464
2465/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2466/// input value to the specified type. If the type must be extended, it is sign
2467/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002468const SCEV *
2469ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002470 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002471 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2472 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002473 "Cannot noop or sign extend with non-integer arguments!");
2474 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2475 "getNoopOrSignExtend cannot truncate!");
2476 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2477 return V; // No conversion
2478 return getSignExtendExpr(V, Ty);
2479}
2480
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002481/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2482/// the input value to the specified type. If the type must be extended,
2483/// it is extended with unspecified bits. The conversion must not be
2484/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002485const SCEV *
2486ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002487 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002488 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2489 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002490 "Cannot noop or any extend with non-integer arguments!");
2491 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2492 "getNoopOrAnyExtend cannot truncate!");
2493 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2494 return V; // No conversion
2495 return getAnyExtendExpr(V, Ty);
2496}
2497
Dan Gohman467c4302009-05-13 03:46:30 +00002498/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2499/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002500const SCEV *
2501ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002502 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002505 "Cannot truncate or noop with non-integer arguments!");
2506 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2507 "getTruncateOrNoop cannot extend!");
2508 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2509 return V; // No conversion
2510 return getTruncateExpr(V, Ty);
2511}
2512
Dan Gohmana334aa72009-06-22 00:31:57 +00002513/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2514/// the types using zero-extension, and then perform a umax operation
2515/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002516const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2517 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002518 const SCEV *PromotedLHS = LHS;
2519 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002520
2521 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2522 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2523 else
2524 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2525
2526 return getUMaxExpr(PromotedLHS, PromotedRHS);
2527}
2528
Dan Gohmanc9759e82009-06-22 15:03:27 +00002529/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2530/// the types using zero-extension, and then perform a umin operation
2531/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002532const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2533 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002534 const SCEV *PromotedLHS = LHS;
2535 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002536
2537 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2538 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2539 else
2540 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2541
2542 return getUMinExpr(PromotedLHS, PromotedRHS);
2543}
2544
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002545/// PushDefUseChildren - Push users of the given Instruction
2546/// onto the given Worklist.
2547static void
2548PushDefUseChildren(Instruction *I,
2549 SmallVectorImpl<Instruction *> &Worklist) {
2550 // Push the def-use children onto the Worklist stack.
2551 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2552 UI != UE; ++UI)
2553 Worklist.push_back(cast<Instruction>(UI));
2554}
2555
2556/// ForgetSymbolicValue - This looks up computed SCEV values for all
2557/// instructions that depend on the given instruction and removes them from
2558/// the Scalars map if they reference SymName. This is used during PHI
2559/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002560void
Dan Gohman85669632010-02-25 06:57:05 +00002561ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002562 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002563 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002564
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002565 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002566 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002567 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002568 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002569 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002570
Dan Gohman5d984912009-12-18 01:14:11 +00002571 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002572 Scalars.find(static_cast<Value *>(I));
2573 if (It != Scalars.end()) {
2574 // Short-circuit the def-use traversal if the symbolic name
2575 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002576 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002577 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002578
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002579 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002580 // structure, it's a PHI that's in the progress of being computed
2581 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2582 // additional loop trip count information isn't going to change anything.
2583 // In the second case, createNodeForPHI will perform the necessary
2584 // updates on its own when it gets to that point. In the third, we do
2585 // want to forget the SCEVUnknown.
2586 if (!isa<PHINode>(I) ||
2587 !isa<SCEVUnknown>(It->second) ||
2588 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002589 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002590 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002591 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002592 }
2593
2594 PushDefUseChildren(I, Worklist);
2595 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002596}
Chris Lattner53e677a2004-04-02 20:23:17 +00002597
2598/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2599/// a loop header, making it a potential recurrence, or it doesn't.
2600///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002601const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002602 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002603 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002604 if (L->getHeader() == PN->getParent()) {
2605 // If it lives in the loop header, it has two incoming values, one
2606 // from outside the loop, and one from inside.
2607 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2608 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002609
Chris Lattner53e677a2004-04-02 20:23:17 +00002610 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002611 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002612 assert(Scalars.find(PN) == Scalars.end() &&
2613 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002614 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002615
2616 // Using this symbolic name for the PHI, analyze the value coming around
2617 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002618 Value *BEValueV = PN->getIncomingValue(BackEdge);
2619 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002620
2621 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2622 // has a special value for the first iteration of the loop.
2623
2624 // If the value coming around the backedge is an add with the symbolic
2625 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002626 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002627 // If there is a single occurrence of the symbolic value, replace it
2628 // with a recurrence.
2629 unsigned FoundIndex = Add->getNumOperands();
2630 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2631 if (Add->getOperand(i) == SymbolicName)
2632 if (FoundIndex == e) {
2633 FoundIndex = i;
2634 break;
2635 }
2636
2637 if (FoundIndex != Add->getNumOperands()) {
2638 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002639 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002640 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2641 if (i != FoundIndex)
2642 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002643 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002644
2645 // This is not a valid addrec if the step amount is varying each
2646 // loop iteration, but is not itself an addrec in this loop.
2647 if (Accum->isLoopInvariant(L) ||
2648 (isa<SCEVAddRecExpr>(Accum) &&
2649 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002650 bool HasNUW = false;
2651 bool HasNSW = false;
2652
2653 // If the increment doesn't overflow, then neither the addrec nor
2654 // the post-increment will overflow.
2655 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2656 if (OBO->hasNoUnsignedWrap())
2657 HasNUW = true;
2658 if (OBO->hasNoSignedWrap())
2659 HasNSW = true;
2660 }
2661
Dan Gohman64a845e2009-06-24 04:48:43 +00002662 const SCEV *StartVal =
2663 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002664 const SCEV *PHISCEV =
2665 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002666
Dan Gohmana10756e2010-01-21 02:09:26 +00002667 // Since the no-wrap flags are on the increment, they apply to the
2668 // post-incremented value as well.
2669 if (Accum->isLoopInvariant(L))
2670 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2671 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002672
2673 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002674 // to be symbolic. We now need to go back and purge all of the
2675 // entries for the scalars that use the symbolic expression.
2676 ForgetSymbolicName(PN, SymbolicName);
2677 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002678 return PHISCEV;
2679 }
2680 }
Dan Gohman622ed672009-05-04 22:02:23 +00002681 } else if (const SCEVAddRecExpr *AddRec =
2682 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002683 // Otherwise, this could be a loop like this:
2684 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2685 // In this case, j = {1,+,1} and BEValue is j.
2686 // Because the other in-value of i (0) fits the evolution of BEValue
2687 // i really is an addrec evolution.
2688 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002689 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002690
2691 // If StartVal = j.start - j.stride, we can use StartVal as the
2692 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002693 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002694 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002695 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002696 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002697
2698 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002699 // to be symbolic. We now need to go back and purge all of the
2700 // entries for the scalars that use the symbolic expression.
2701 ForgetSymbolicName(PN, SymbolicName);
2702 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002703 return PHISCEV;
2704 }
2705 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002706 }
2707
2708 return SymbolicName;
2709 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002710
Dan Gohman85669632010-02-25 06:57:05 +00002711 // If the PHI has a single incoming value, follow that value, unless the
2712 // PHI's incoming blocks are in a different loop, in which case doing so
2713 // risks breaking LCSSA form. Instcombine would normally zap these, but
2714 // it doesn't have DominatorTree information, so it may miss cases.
2715 if (Value *V = PN->hasConstantValue(DT)) {
2716 bool AllSameLoop = true;
2717 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2718 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2719 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2720 AllSameLoop = false;
2721 break;
2722 }
2723 if (AllSameLoop)
2724 return getSCEV(V);
2725 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002726
Chris Lattner53e677a2004-04-02 20:23:17 +00002727 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002728 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002729}
2730
Dan Gohman26466c02009-05-08 20:26:55 +00002731/// createNodeForGEP - Expand GEP instructions into add and multiply
2732/// operations. This allows them to be analyzed by regular SCEV code.
2733///
Dan Gohmand281ed22009-12-18 02:09:29 +00002734const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002735
Dan Gohmand281ed22009-12-18 02:09:29 +00002736 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002737 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002738 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002739 // Don't attempt to analyze GEPs over unsized objects.
2740 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2741 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002742 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002743 gep_type_iterator GTI = gep_type_begin(GEP);
2744 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2745 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002746 I != E; ++I) {
2747 Value *Index = *I;
2748 // Compute the (potentially symbolic) offset in bytes for this index.
2749 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2750 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002751 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002752 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002753 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002754 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002755 } else {
2756 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002757 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002758 // Getelementptr indices are signed.
Dan Gohman8db08df2010-02-02 01:38:49 +00002759 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002760 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002761 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002762 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2763 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2764 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002765 }
2766 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002767 return getAddExpr(getSCEV(Base), TotalOffset,
2768 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002769}
2770
Nick Lewycky83bb0052007-11-22 07:59:40 +00002771/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2772/// guaranteed to end in (at every loop iteration). It is, at the same time,
2773/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2774/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002775uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002776ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002777 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002778 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002779
Dan Gohman622ed672009-05-04 22:02:23 +00002780 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002781 return std::min(GetMinTrailingZeros(T->getOperand()),
2782 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002783
Dan Gohman622ed672009-05-04 22:02:23 +00002784 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002785 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2786 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2787 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002788 }
2789
Dan Gohman622ed672009-05-04 22:02:23 +00002790 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002791 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2792 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2793 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002794 }
2795
Dan Gohman622ed672009-05-04 22:02:23 +00002796 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002797 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002798 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002799 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002800 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002801 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002802 }
2803
Dan Gohman622ed672009-05-04 22:02:23 +00002804 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002805 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002806 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2807 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002808 for (unsigned i = 1, e = M->getNumOperands();
2809 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002810 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002811 BitWidth);
2812 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002813 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002814
Dan Gohman622ed672009-05-04 22:02:23 +00002815 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002816 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002817 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002818 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002819 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002820 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002821 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002822
Dan Gohman622ed672009-05-04 22:02:23 +00002823 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002824 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002825 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002826 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002827 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002828 return MinOpRes;
2829 }
2830
Dan Gohman622ed672009-05-04 22:02:23 +00002831 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002832 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002833 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002834 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002835 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002836 return MinOpRes;
2837 }
2838
Dan Gohman2c364ad2009-06-19 23:29:04 +00002839 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2840 // For a SCEVUnknown, ask ValueTracking.
2841 unsigned BitWidth = getTypeSizeInBits(U->getType());
2842 APInt Mask = APInt::getAllOnesValue(BitWidth);
2843 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2844 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2845 return Zeros.countTrailingOnes();
2846 }
2847
2848 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002849 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002850}
Chris Lattner53e677a2004-04-02 20:23:17 +00002851
Dan Gohman85b05a22009-07-13 21:35:55 +00002852/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2853///
2854ConstantRange
2855ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002856
2857 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002858 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002859
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002860 unsigned BitWidth = getTypeSizeInBits(S->getType());
2861 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2862
2863 // If the value has known zeros, the maximum unsigned value will have those
2864 // known zeros as well.
2865 uint32_t TZ = GetMinTrailingZeros(S);
2866 if (TZ != 0)
2867 ConservativeResult =
2868 ConstantRange(APInt::getMinValue(BitWidth),
2869 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2870
Dan Gohman85b05a22009-07-13 21:35:55 +00002871 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2872 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2873 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2874 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002875 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002876 }
2877
2878 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2879 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2880 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2881 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002882 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002883 }
2884
2885 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2886 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2887 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2888 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002889 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002890 }
2891
2892 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2893 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2894 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2895 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002896 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002897 }
2898
2899 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2900 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2901 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002902 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002903 }
2904
2905 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2906 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002907 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002908 }
2909
2910 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2911 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002912 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002913 }
2914
2915 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2916 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002917 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002918 }
2919
Dan Gohman85b05a22009-07-13 21:35:55 +00002920 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002921 // If there's no unsigned wrap, the value will never be less than its
2922 // initial value.
2923 if (AddRec->hasNoUnsignedWrap())
2924 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2925 ConservativeResult =
2926 ConstantRange(C->getValue()->getValue(),
2927 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002928
2929 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002930 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002931 const Type *Ty = AddRec->getType();
2932 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002933 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2934 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002935 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2936
2937 const SCEV *Start = AddRec->getStart();
2938 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2939
2940 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002941 if (!AddRec->hasNoUnsignedWrap())
2942 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002943
2944 ConstantRange StartRange = getUnsignedRange(Start);
2945 ConstantRange EndRange = getUnsignedRange(End);
2946 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2947 EndRange.getUnsignedMin());
2948 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2949 EndRange.getUnsignedMax());
2950 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002951 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002952 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002953 }
2954 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002955
2956 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002957 }
2958
2959 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2960 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002961 APInt Mask = APInt::getAllOnesValue(BitWidth);
2962 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2963 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002964 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002965 return ConservativeResult;
2966 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002967 }
2968
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002969 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002970}
2971
Dan Gohman85b05a22009-07-13 21:35:55 +00002972/// getSignedRange - Determine the signed range for a particular SCEV.
2973///
2974ConstantRange
2975ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002976
Dan Gohman85b05a22009-07-13 21:35:55 +00002977 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2978 return ConstantRange(C->getValue()->getValue());
2979
Dan Gohman52fddd32010-01-26 04:40:18 +00002980 unsigned BitWidth = getTypeSizeInBits(S->getType());
2981 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2982
2983 // If the value has known zeros, the maximum signed value will have those
2984 // known zeros as well.
2985 uint32_t TZ = GetMinTrailingZeros(S);
2986 if (TZ != 0)
2987 ConservativeResult =
2988 ConstantRange(APInt::getSignedMinValue(BitWidth),
2989 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2990
Dan Gohman85b05a22009-07-13 21:35:55 +00002991 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2992 ConstantRange X = getSignedRange(Add->getOperand(0));
2993 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2994 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002995 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002996 }
2997
Dan Gohman85b05a22009-07-13 21:35:55 +00002998 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2999 ConstantRange X = getSignedRange(Mul->getOperand(0));
3000 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3001 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003002 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003003 }
3004
Dan Gohman85b05a22009-07-13 21:35:55 +00003005 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3006 ConstantRange X = getSignedRange(SMax->getOperand(0));
3007 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3008 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003009 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003010 }
Dan Gohman62849c02009-06-24 01:05:09 +00003011
Dan Gohman85b05a22009-07-13 21:35:55 +00003012 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3013 ConstantRange X = getSignedRange(UMax->getOperand(0));
3014 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3015 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003016 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003017 }
Dan Gohman62849c02009-06-24 01:05:09 +00003018
Dan Gohman85b05a22009-07-13 21:35:55 +00003019 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3020 ConstantRange X = getSignedRange(UDiv->getLHS());
3021 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003022 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003023 }
Dan Gohman62849c02009-06-24 01:05:09 +00003024
Dan Gohman85b05a22009-07-13 21:35:55 +00003025 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3026 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003027 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003028 }
3029
3030 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3031 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003032 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003033 }
3034
3035 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3036 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003037 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003038 }
3039
Dan Gohman85b05a22009-07-13 21:35:55 +00003040 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003041 // If there's no signed wrap, and all the operands have the same sign or
3042 // zero, the value won't ever change sign.
3043 if (AddRec->hasNoSignedWrap()) {
3044 bool AllNonNeg = true;
3045 bool AllNonPos = true;
3046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3047 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3048 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3049 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003050 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003051 ConservativeResult = ConservativeResult.intersectWith(
3052 ConstantRange(APInt(BitWidth, 0),
3053 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003054 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003055 ConservativeResult = ConservativeResult.intersectWith(
3056 ConstantRange(APInt::getSignedMinValue(BitWidth),
3057 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003058 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003059
3060 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003061 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003062 const Type *Ty = AddRec->getType();
3063 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003064 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3065 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003066 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3067
3068 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003069 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3070
3071 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003072 if (!AddRec->hasNoSignedWrap())
3073 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003074
3075 ConstantRange StartRange = getSignedRange(Start);
3076 ConstantRange EndRange = getSignedRange(End);
3077 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3078 EndRange.getSignedMin());
3079 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3080 EndRange.getSignedMax());
3081 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003082 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003083 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003084 }
Dan Gohman62849c02009-06-24 01:05:09 +00003085 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003086
3087 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003088 }
3089
Dan Gohman2c364ad2009-06-19 23:29:04 +00003090 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3091 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003092 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003093 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003094 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3095 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003096 return ConservativeResult;
3097 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003098 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003099 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003100 }
3101
Dan Gohman52fddd32010-01-26 04:40:18 +00003102 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003103}
3104
Chris Lattner53e677a2004-04-02 20:23:17 +00003105/// createSCEV - We know that there is no SCEV for the specified value.
3106/// Analyze the expression.
3107///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003108const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003109 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003110 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003111
Dan Gohman6c459a22008-06-22 19:56:46 +00003112 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003113 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003114 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003115
3116 // Don't attempt to analyze instructions in blocks that aren't
3117 // reachable. Such instructions don't matter, and they aren't required
3118 // to obey basic rules for definitions dominating uses which this
3119 // analysis depends on.
3120 if (!DT->isReachableFromEntry(I->getParent()))
3121 return getUnknown(V);
3122 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003123 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003124 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3125 return getConstant(CI);
3126 else if (isa<ConstantPointerNull>(V))
3127 return getIntegerSCEV(0, V->getType());
3128 else if (isa<UndefValue>(V))
3129 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003130 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3131 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003132 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003133 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003134
Dan Gohmanca178902009-07-17 20:47:02 +00003135 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003136 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003137 case Instruction::Add:
3138 // Don't transfer the NSW and NUW bits from the Add instruction to the
3139 // Add expression, because the Instruction may be guarded by control
3140 // flow and the no-overflow bits may not be valid for the expression in
3141 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003142 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003143 getSCEV(U->getOperand(1)));
3144 case Instruction::Mul:
3145 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3146 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003147 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003148 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003149 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003150 return getUDivExpr(getSCEV(U->getOperand(0)),
3151 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003152 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003153 return getMinusSCEV(getSCEV(U->getOperand(0)),
3154 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003155 case Instruction::And:
3156 // For an expression like x&255 that merely masks off the high bits,
3157 // use zext(trunc(x)) as the SCEV expression.
3158 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003159 if (CI->isNullValue())
3160 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003161 if (CI->isAllOnesValue())
3162 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003163 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003164
3165 // Instcombine's ShrinkDemandedConstant may strip bits out of
3166 // constants, obscuring what would otherwise be a low-bits mask.
3167 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3168 // knew about to reconstruct a low-bits mask value.
3169 unsigned LZ = A.countLeadingZeros();
3170 unsigned BitWidth = A.getBitWidth();
3171 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3172 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3173 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3174
3175 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3176
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003177 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003178 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003179 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003180 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003181 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003182 }
3183 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003184
Dan Gohman6c459a22008-06-22 19:56:46 +00003185 case Instruction::Or:
3186 // If the RHS of the Or is a constant, we may have something like:
3187 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3188 // optimizations will transparently handle this case.
3189 //
3190 // In order for this transformation to be safe, the LHS must be of the
3191 // form X*(2^n) and the Or constant must be less than 2^n.
3192 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003193 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003194 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003195 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003196 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3197 // Build a plain add SCEV.
3198 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3199 // If the LHS of the add was an addrec and it has no-wrap flags,
3200 // transfer the no-wrap flags, since an or won't introduce a wrap.
3201 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3202 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3203 if (OldAR->hasNoUnsignedWrap())
3204 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3205 if (OldAR->hasNoSignedWrap())
3206 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3207 }
3208 return S;
3209 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003210 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003211 break;
3212 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003213 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003214 // If the RHS of the xor is a signbit, then this is just an add.
3215 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003216 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003217 return getAddExpr(getSCEV(U->getOperand(0)),
3218 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003219
3220 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003221 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003222 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003223
3224 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3225 // This is a variant of the check for xor with -1, and it handles
3226 // the case where instcombine has trimmed non-demanded bits out
3227 // of an xor with -1.
3228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3229 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3230 if (BO->getOpcode() == Instruction::And &&
3231 LCI->getValue() == CI->getValue())
3232 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003233 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003234 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003235 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003236 const Type *Z0Ty = Z0->getType();
3237 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3238
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003239 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003240 // mask off the high bits. Complement the operand and
3241 // re-apply the zext.
3242 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3243 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3244
3245 // If C is a single bit, it may be in the sign-bit position
3246 // before the zero-extend. In this case, represent the xor
3247 // using an add, which is equivalent, and re-apply the zext.
3248 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3249 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3250 Trunc.isSignBit())
3251 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3252 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003253 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003254 }
3255 break;
3256
3257 case Instruction::Shl:
3258 // Turn shift left of a constant amount into a multiply.
3259 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003260 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003261 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003262 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003263 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003264 }
3265 break;
3266
Nick Lewycky01eaf802008-07-07 06:15:49 +00003267 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003268 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003269 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003270 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003271 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003272 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003273 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003274 }
3275 break;
3276
Dan Gohman4ee29af2009-04-21 02:26:00 +00003277 case Instruction::AShr:
3278 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3279 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3280 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3281 if (L->getOpcode() == Instruction::Shl &&
3282 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003283 unsigned BitWidth = getTypeSizeInBits(U->getType());
3284 uint64_t Amt = BitWidth - CI->getZExtValue();
3285 if (Amt == BitWidth)
3286 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3287 if (Amt > BitWidth)
3288 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003289 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003290 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003291 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003292 U->getType());
3293 }
3294 break;
3295
Dan Gohman6c459a22008-06-22 19:56:46 +00003296 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003297 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003298
3299 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003300 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003301
3302 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003303 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003304
3305 case Instruction::BitCast:
3306 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003307 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003308 return getSCEV(U->getOperand(0));
3309 break;
3310
Dan Gohman4f8eea82010-02-01 18:27:38 +00003311 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3312 // lead to pointer expressions which cannot safely be expanded to GEPs,
3313 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3314 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003315
Dan Gohman26466c02009-05-08 20:26:55 +00003316 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003317 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003318
Dan Gohman6c459a22008-06-22 19:56:46 +00003319 case Instruction::PHI:
3320 return createNodeForPHI(cast<PHINode>(U));
3321
3322 case Instruction::Select:
3323 // This could be a smax or umax that was lowered earlier.
3324 // Try to recover it.
3325 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3326 Value *LHS = ICI->getOperand(0);
3327 Value *RHS = ICI->getOperand(1);
3328 switch (ICI->getPredicate()) {
3329 case ICmpInst::ICMP_SLT:
3330 case ICmpInst::ICMP_SLE:
3331 std::swap(LHS, RHS);
3332 // fall through
3333 case ICmpInst::ICMP_SGT:
3334 case ICmpInst::ICMP_SGE:
3335 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003336 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003337 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003338 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003339 break;
3340 case ICmpInst::ICMP_ULT:
3341 case ICmpInst::ICMP_ULE:
3342 std::swap(LHS, RHS);
3343 // fall through
3344 case ICmpInst::ICMP_UGT:
3345 case ICmpInst::ICMP_UGE:
3346 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003347 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003348 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003349 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003350 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003351 case ICmpInst::ICMP_NE:
3352 // n != 0 ? n : 1 -> umax(n, 1)
3353 if (LHS == U->getOperand(1) &&
3354 isa<ConstantInt>(U->getOperand(2)) &&
3355 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3356 isa<ConstantInt>(RHS) &&
3357 cast<ConstantInt>(RHS)->isZero())
3358 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3359 break;
3360 case ICmpInst::ICMP_EQ:
3361 // n == 0 ? 1 : n -> umax(n, 1)
3362 if (LHS == U->getOperand(2) &&
3363 isa<ConstantInt>(U->getOperand(1)) &&
3364 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3365 isa<ConstantInt>(RHS) &&
3366 cast<ConstantInt>(RHS)->isZero())
3367 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3368 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003369 default:
3370 break;
3371 }
3372 }
3373
3374 default: // We cannot analyze this expression.
3375 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003376 }
3377
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003378 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003379}
3380
3381
3382
3383//===----------------------------------------------------------------------===//
3384// Iteration Count Computation Code
3385//
3386
Dan Gohman46bdfb02009-02-24 18:55:53 +00003387/// getBackedgeTakenCount - If the specified loop has a predictable
3388/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3389/// object. The backedge-taken count is the number of times the loop header
3390/// will be branched to from within the loop. This is one less than the
3391/// trip count of the loop, since it doesn't count the first iteration,
3392/// when the header is branched to from outside the loop.
3393///
3394/// Note that it is not valid to call this method on a loop without a
3395/// loop-invariant backedge-taken count (see
3396/// hasLoopInvariantBackedgeTakenCount).
3397///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003398const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003399 return getBackedgeTakenInfo(L).Exact;
3400}
3401
3402/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3403/// return the least SCEV value that is known never to be less than the
3404/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003405const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003406 return getBackedgeTakenInfo(L).Max;
3407}
3408
Dan Gohman59ae6b92009-07-08 19:23:34 +00003409/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3410/// onto the given Worklist.
3411static void
3412PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3413 BasicBlock *Header = L->getHeader();
3414
3415 // Push all Loop-header PHIs onto the Worklist stack.
3416 for (BasicBlock::iterator I = Header->begin();
3417 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3418 Worklist.push_back(PN);
3419}
3420
Dan Gohmana1af7572009-04-30 20:47:05 +00003421const ScalarEvolution::BackedgeTakenInfo &
3422ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003423 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003424 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003425 // update the value. The temporary CouldNotCompute value tells SCEV
3426 // code elsewhere that it shouldn't attempt to request a new
3427 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003428 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003429 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3430 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003431 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3432 if (BECount.Exact != getCouldNotCompute()) {
3433 assert(BECount.Exact->isLoopInvariant(L) &&
3434 BECount.Max->isLoopInvariant(L) &&
3435 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003436 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003437
Dan Gohman01ecca22009-04-27 20:16:15 +00003438 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003439 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003440 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003441 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003442 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003443 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003444 if (isa<PHINode>(L->getHeader()->begin()))
3445 // Only count loops that have phi nodes as not being computable.
3446 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003447 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003448
3449 // Now that we know more about the trip count for this loop, forget any
3450 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003451 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003452 // information. This is similar to the code in forgetLoop, except that
3453 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003454 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003455 SmallVector<Instruction *, 16> Worklist;
3456 PushLoopPHIs(L, Worklist);
3457
3458 SmallPtrSet<Instruction *, 8> Visited;
3459 while (!Worklist.empty()) {
3460 Instruction *I = Worklist.pop_back_val();
3461 if (!Visited.insert(I)) continue;
3462
Dan Gohman5d984912009-12-18 01:14:11 +00003463 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003464 Scalars.find(static_cast<Value *>(I));
3465 if (It != Scalars.end()) {
3466 // SCEVUnknown for a PHI either means that it has an unrecognized
3467 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003468 // by createNodeForPHI. In the former case, additional loop trip
3469 // count information isn't going to change anything. In the later
3470 // case, createNodeForPHI will perform the necessary updates on its
3471 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003472 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3473 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003474 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003475 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003476 if (PHINode *PN = dyn_cast<PHINode>(I))
3477 ConstantEvolutionLoopExitValue.erase(PN);
3478 }
3479
3480 PushDefUseChildren(I, Worklist);
3481 }
3482 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003483 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003484 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003485}
3486
Dan Gohman4c7279a2009-10-31 15:04:55 +00003487/// forgetLoop - This method should be called by the client when it has
3488/// changed a loop in a way that may effect ScalarEvolution's ability to
3489/// compute a trip count, or if the loop is deleted.
3490void ScalarEvolution::forgetLoop(const Loop *L) {
3491 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003492 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003493
Dan Gohman4c7279a2009-10-31 15:04:55 +00003494 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003495 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003496 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003497
Dan Gohman59ae6b92009-07-08 19:23:34 +00003498 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003499 while (!Worklist.empty()) {
3500 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003501 if (!Visited.insert(I)) continue;
3502
Dan Gohman5d984912009-12-18 01:14:11 +00003503 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003504 Scalars.find(static_cast<Value *>(I));
3505 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003506 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003507 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003508 if (PHINode *PN = dyn_cast<PHINode>(I))
3509 ConstantEvolutionLoopExitValue.erase(PN);
3510 }
3511
3512 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003513 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003514}
3515
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003516/// forgetValue - This method should be called by the client when it has
3517/// changed a value in a way that may effect its value, or which may
3518/// disconnect it from a def-use chain linking it to a loop.
3519void ScalarEvolution::forgetValue(Value *V) {
3520 Instruction *I = dyn_cast<Instruction>(V);
3521 if (!I) return;
3522
3523 // Drop information about expressions based on loop-header PHIs.
3524 SmallVector<Instruction *, 16> Worklist;
3525 Worklist.push_back(I);
3526
3527 SmallPtrSet<Instruction *, 8> Visited;
3528 while (!Worklist.empty()) {
3529 I = Worklist.pop_back_val();
3530 if (!Visited.insert(I)) continue;
3531
3532 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3533 Scalars.find(static_cast<Value *>(I));
3534 if (It != Scalars.end()) {
3535 ValuesAtScopes.erase(It->second);
3536 Scalars.erase(It);
3537 if (PHINode *PN = dyn_cast<PHINode>(I))
3538 ConstantEvolutionLoopExitValue.erase(PN);
3539 }
3540
3541 PushDefUseChildren(I, Worklist);
3542 }
3543}
3544
Dan Gohman46bdfb02009-02-24 18:55:53 +00003545/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3546/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003547ScalarEvolution::BackedgeTakenInfo
3548ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003549 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003550 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003551
Dan Gohmana334aa72009-06-22 00:31:57 +00003552 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003553 const SCEV *BECount = getCouldNotCompute();
3554 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003555 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003556 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3557 BackedgeTakenInfo NewBTI =
3558 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003559
Dan Gohman1c343752009-06-27 21:21:31 +00003560 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003561 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003562 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003563 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003564 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003565 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003566 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003567 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003568 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003569 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003570 }
Dan Gohman1c343752009-06-27 21:21:31 +00003571 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003572 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003573 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003574 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003575 }
3576
3577 return BackedgeTakenInfo(BECount, MaxBECount);
3578}
3579
3580/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3581/// of the specified loop will execute if it exits via the specified block.
3582ScalarEvolution::BackedgeTakenInfo
3583ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3584 BasicBlock *ExitingBlock) {
3585
3586 // Okay, we've chosen an exiting block. See what condition causes us to
3587 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003588 //
3589 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003590 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003591 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003592 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003593
Chris Lattner8b0e3602007-01-07 02:24:26 +00003594 // At this point, we know we have a conditional branch that determines whether
3595 // the loop is exited. However, we don't know if the branch is executed each
3596 // time through the loop. If not, then the execution count of the branch will
3597 // not be equal to the trip count of the loop.
3598 //
3599 // Currently we check for this by checking to see if the Exit branch goes to
3600 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003601 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003602 // loop header. This is common for un-rotated loops.
3603 //
3604 // If both of those tests fail, walk up the unique predecessor chain to the
3605 // header, stopping if there is an edge that doesn't exit the loop. If the
3606 // header is reached, the execution count of the branch will be equal to the
3607 // trip count of the loop.
3608 //
3609 // More extensive analysis could be done to handle more cases here.
3610 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003611 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003612 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003613 ExitBr->getParent() != L->getHeader()) {
3614 // The simple checks failed, try climbing the unique predecessor chain
3615 // up to the header.
3616 bool Ok = false;
3617 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3618 BasicBlock *Pred = BB->getUniquePredecessor();
3619 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003620 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003621 TerminatorInst *PredTerm = Pred->getTerminator();
3622 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3623 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3624 if (PredSucc == BB)
3625 continue;
3626 // If the predecessor has a successor that isn't BB and isn't
3627 // outside the loop, assume the worst.
3628 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003629 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003630 }
3631 if (Pred == L->getHeader()) {
3632 Ok = true;
3633 break;
3634 }
3635 BB = Pred;
3636 }
3637 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003638 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003639 }
3640
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003641 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003642 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3643 ExitBr->getSuccessor(0),
3644 ExitBr->getSuccessor(1));
3645}
3646
3647/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3648/// backedge of the specified loop will execute if its exit condition
3649/// were a conditional branch of ExitCond, TBB, and FBB.
3650ScalarEvolution::BackedgeTakenInfo
3651ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3652 Value *ExitCond,
3653 BasicBlock *TBB,
3654 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003655 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003656 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3657 if (BO->getOpcode() == Instruction::And) {
3658 // Recurse on the operands of the and.
3659 BackedgeTakenInfo BTI0 =
3660 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3661 BackedgeTakenInfo BTI1 =
3662 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003663 const SCEV *BECount = getCouldNotCompute();
3664 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003665 if (L->contains(TBB)) {
3666 // Both conditions must be true for the loop to continue executing.
3667 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003668 if (BTI0.Exact == getCouldNotCompute() ||
3669 BTI1.Exact == getCouldNotCompute())
3670 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003671 else
3672 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003673 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003674 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003675 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003676 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003677 else
3678 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003679 } else {
3680 // Both conditions must be true for the loop to exit.
3681 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003682 if (BTI0.Exact != getCouldNotCompute() &&
3683 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003684 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003685 if (BTI0.Max != getCouldNotCompute() &&
3686 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003687 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3688 }
3689
3690 return BackedgeTakenInfo(BECount, MaxBECount);
3691 }
3692 if (BO->getOpcode() == Instruction::Or) {
3693 // Recurse on the operands of the or.
3694 BackedgeTakenInfo BTI0 =
3695 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3696 BackedgeTakenInfo BTI1 =
3697 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003698 const SCEV *BECount = getCouldNotCompute();
3699 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003700 if (L->contains(FBB)) {
3701 // Both conditions must be false for the loop to continue executing.
3702 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003703 if (BTI0.Exact == getCouldNotCompute() ||
3704 BTI1.Exact == getCouldNotCompute())
3705 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003706 else
3707 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003708 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003709 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003710 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003711 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003712 else
3713 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003714 } else {
3715 // Both conditions must be false for the loop to exit.
3716 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003717 if (BTI0.Exact != getCouldNotCompute() &&
3718 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003719 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003720 if (BTI0.Max != getCouldNotCompute() &&
3721 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003722 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3723 }
3724
3725 return BackedgeTakenInfo(BECount, MaxBECount);
3726 }
3727 }
3728
3729 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003730 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003731 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3732 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003733
Dan Gohman00cb5b72010-02-19 18:12:07 +00003734 // Check for a constant condition. These are normally stripped out by
3735 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3736 // preserve the CFG and is temporarily leaving constant conditions
3737 // in place.
3738 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3739 if (L->contains(FBB) == !CI->getZExtValue())
3740 // The backedge is always taken.
3741 return getCouldNotCompute();
3742 else
3743 // The backedge is never taken.
3744 return getIntegerSCEV(0, CI->getType());
3745 }
3746
Eli Friedman361e54d2009-05-09 12:32:42 +00003747 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003748 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3749}
3750
3751/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3752/// backedge of the specified loop will execute if its exit condition
3753/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3754ScalarEvolution::BackedgeTakenInfo
3755ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3756 ICmpInst *ExitCond,
3757 BasicBlock *TBB,
3758 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003759
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 // If the condition was exit on true, convert the condition to exit on false
3761 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003762 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003763 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003764 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003765 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003766
3767 // Handle common loops like: for (X = "string"; *X; ++X)
3768 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3769 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003770 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003771 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003772 if (ItCnt.hasAnyInfo())
3773 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003774 }
3775
Dan Gohman0bba49c2009-07-07 17:06:11 +00003776 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3777 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003778
3779 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003780 LHS = getSCEVAtScope(LHS, L);
3781 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003782
Dan Gohman64a845e2009-06-24 04:48:43 +00003783 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003785 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3786 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003787 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003789 }
3790
Chris Lattner53e677a2004-04-02 20:23:17 +00003791 // If we have a comparison of a chrec against a constant, try to use value
3792 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003793 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3794 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003795 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003796 // Form the constant range.
3797 ConstantRange CompRange(
3798 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003799
Dan Gohman0bba49c2009-07-07 17:06:11 +00003800 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003801 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003802 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003803
Chris Lattner53e677a2004-04-02 20:23:17 +00003804 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003806 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003807 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3808 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003809 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003810 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003811 case ICmpInst::ICMP_EQ: { // while (X == Y)
3812 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003813 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3814 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003815 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003816 }
3817 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003818 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3819 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003820 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003821 }
3822 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003823 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3824 getNotSCEV(RHS), L, true);
3825 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003826 break;
3827 }
3828 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003829 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3830 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003831 break;
3832 }
3833 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003834 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3835 getNotSCEV(RHS), L, false);
3836 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003837 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003838 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003839 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003840#if 0
David Greene25e0e872009-12-23 22:18:14 +00003841 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003842 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003843 dbgs() << "[unsigned] ";
3844 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003845 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003846 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003847#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003848 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003849 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003850 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003851 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003852}
3853
Chris Lattner673e02b2004-10-12 01:49:27 +00003854static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003855EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3856 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003857 const SCEV *InVal = SE.getConstant(C);
3858 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003859 assert(isa<SCEVConstant>(Val) &&
3860 "Evaluation of SCEV at constant didn't fold correctly?");
3861 return cast<SCEVConstant>(Val)->getValue();
3862}
3863
3864/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3865/// and a GEP expression (missing the pointer index) indexing into it, return
3866/// the addressed element of the initializer or null if the index expression is
3867/// invalid.
3868static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003869GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003870 const std::vector<ConstantInt*> &Indices) {
3871 Constant *Init = GV->getInitializer();
3872 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003873 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003874 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3875 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3876 Init = cast<Constant>(CS->getOperand(Idx));
3877 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3878 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3879 Init = cast<Constant>(CA->getOperand(Idx));
3880 } else if (isa<ConstantAggregateZero>(Init)) {
3881 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3882 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003883 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003884 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3885 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003886 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003887 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003888 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003889 }
3890 return 0;
3891 } else {
3892 return 0; // Unknown initializer type
3893 }
3894 }
3895 return Init;
3896}
3897
Dan Gohman46bdfb02009-02-24 18:55:53 +00003898/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3899/// 'icmp op load X, cst', try to see if we can compute the backedge
3900/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003901ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00003902ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3903 LoadInst *LI,
3904 Constant *RHS,
3905 const Loop *L,
3906 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003907 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003908
3909 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003910 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00003911 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003912 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003913
3914 // Make sure that it is really a constant global we are gepping, with an
3915 // initializer, and make sure the first IDX is really 0.
3916 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003917 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003918 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3919 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003920 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003921
3922 // Okay, we allow one non-constant index into the GEP instruction.
3923 Value *VarIdx = 0;
3924 std::vector<ConstantInt*> Indexes;
3925 unsigned VarIdxNum = 0;
3926 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3927 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3928 Indexes.push_back(CI);
3929 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003930 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003931 VarIdx = GEP->getOperand(i);
3932 VarIdxNum = i-2;
3933 Indexes.push_back(0);
3934 }
3935
3936 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3937 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003938 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003939 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003940
3941 // We can only recognize very limited forms of loop index expressions, in
3942 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003943 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003944 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3945 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3946 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003947 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003948
3949 unsigned MaxSteps = MaxBruteForceIterations;
3950 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003951 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003952 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003953 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003954
3955 // Form the GEP offset.
3956 Indexes[VarIdxNum] = Val;
3957
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003958 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003959 if (Result == 0) break; // Cannot compute!
3960
3961 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003962 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003963 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003964 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003965#if 0
David Greene25e0e872009-12-23 22:18:14 +00003966 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003967 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3968 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003969#endif
3970 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003971 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003972 }
3973 }
Dan Gohman1c343752009-06-27 21:21:31 +00003974 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003975}
3976
3977
Chris Lattner3221ad02004-04-17 22:58:41 +00003978/// CanConstantFold - Return true if we can constant fold an instruction of the
3979/// specified type, assuming that all operands were constants.
3980static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003981 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003982 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3983 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003984
Chris Lattner3221ad02004-04-17 22:58:41 +00003985 if (const CallInst *CI = dyn_cast<CallInst>(I))
3986 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003987 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003988 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003989}
3990
Chris Lattner3221ad02004-04-17 22:58:41 +00003991/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3992/// in the loop that V is derived from. We allow arbitrary operations along the
3993/// way, but the operands of an operation must either be constants or a value
3994/// derived from a constant PHI. If this expression does not fit with these
3995/// constraints, return null.
3996static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3997 // If this is not an instruction, or if this is an instruction outside of the
3998 // loop, it can't be derived from a loop PHI.
3999 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004000 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004001
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004002 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004003 if (L->getHeader() == I->getParent())
4004 return PN;
4005 else
4006 // We don't currently keep track of the control flow needed to evaluate
4007 // PHIs, so we cannot handle PHIs inside of loops.
4008 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004009 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004010
4011 // If we won't be able to constant fold this expression even if the operands
4012 // are constants, return early.
4013 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004014
Chris Lattner3221ad02004-04-17 22:58:41 +00004015 // Otherwise, we can evaluate this instruction if all of its operands are
4016 // constant or derived from a PHI node themselves.
4017 PHINode *PHI = 0;
4018 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4019 if (!(isa<Constant>(I->getOperand(Op)) ||
4020 isa<GlobalValue>(I->getOperand(Op)))) {
4021 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4022 if (P == 0) return 0; // Not evolving from PHI
4023 if (PHI == 0)
4024 PHI = P;
4025 else if (PHI != P)
4026 return 0; // Evolving from multiple different PHIs.
4027 }
4028
4029 // This is a expression evolving from a constant PHI!
4030 return PHI;
4031}
4032
4033/// EvaluateExpression - Given an expression that passes the
4034/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4035/// in the loop has the value PHIVal. If we can't fold this expression for some
4036/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004037static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4038 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004039 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004040 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00004041 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00004042 Instruction *I = cast<Instruction>(V);
4043
4044 std::vector<Constant*> Operands;
4045 Operands.resize(I->getNumOperands());
4046
4047 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004048 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004049 if (Operands[i] == 0) return 0;
4050 }
4051
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004052 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004053 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004054 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004055 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004056 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004057}
4058
4059/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4060/// in the header of its containing loop, we know the loop executes a
4061/// constant number of times, and the PHI node is just a recurrence
4062/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004063Constant *
4064ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004065 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004066 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004067 std::map<PHINode*, Constant*>::iterator I =
4068 ConstantEvolutionLoopExitValue.find(PN);
4069 if (I != ConstantEvolutionLoopExitValue.end())
4070 return I->second;
4071
Dan Gohman46bdfb02009-02-24 18:55:53 +00004072 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00004073 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4074
4075 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4076
4077 // Since the loop is canonicalized, the PHI node must have two entries. One
4078 // entry must be a constant (coming in from outside of the loop), and the
4079 // second must be derived from the same PHI.
4080 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4081 Constant *StartCST =
4082 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4083 if (StartCST == 0)
4084 return RetVal = 0; // Must be a constant.
4085
4086 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4087 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4088 if (PN2 != PN)
4089 return RetVal = 0; // Not derived from same PHI.
4090
4091 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004092 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004093 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004094
Dan Gohman46bdfb02009-02-24 18:55:53 +00004095 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004096 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004097 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4098 if (IterationNum == NumIterations)
4099 return RetVal = PHIVal; // Got exit value!
4100
4101 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004102 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004103 if (NextPHI == PHIVal)
4104 return RetVal = NextPHI; // Stopped evolving!
4105 if (NextPHI == 0)
4106 return 0; // Couldn't evaluate!
4107 PHIVal = NextPHI;
4108 }
4109}
4110
Dan Gohman07ad19b2009-07-27 16:09:48 +00004111/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004112/// constant number of times (the condition evolves only from constants),
4113/// try to evaluate a few iterations of the loop until we get the exit
4114/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004115/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004116const SCEV *
4117ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4118 Value *Cond,
4119 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004120 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004121 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004122
4123 // Since the loop is canonicalized, the PHI node must have two entries. One
4124 // entry must be a constant (coming in from outside of the loop), and the
4125 // second must be derived from the same PHI.
4126 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4127 Constant *StartCST =
4128 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004129 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004130
4131 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4132 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004133 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004134
4135 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4136 // the loop symbolically to determine when the condition gets a value of
4137 // "ExitWhen".
4138 unsigned IterationNum = 0;
4139 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4140 for (Constant *PHIVal = StartCST;
4141 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004142 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004143 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004144
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004145 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004146 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004147
Reid Spencere8019bb2007-03-01 07:25:48 +00004148 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004149 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004150 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004151 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004152
Chris Lattner3221ad02004-04-17 22:58:41 +00004153 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004154 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004155 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004156 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004157 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004158 }
4159
4160 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004161 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004162}
4163
Dan Gohmane7125f42009-09-03 15:00:26 +00004164/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004165/// at the specified scope in the program. The L value specifies a loop
4166/// nest to evaluate the expression at, where null is the top-level or a
4167/// specified loop is immediately inside of the loop.
4168///
4169/// This method can be used to compute the exit value for a variable defined
4170/// in a loop by querying what the value will hold in the parent loop.
4171///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004172/// In the case that a relevant loop exit value cannot be computed, the
4173/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004174const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004175 // Check to see if we've folded this expression at this loop before.
4176 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4177 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4178 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4179 if (!Pair.second)
4180 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004181
Dan Gohman42214892009-08-31 21:15:23 +00004182 // Otherwise compute it.
4183 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004184 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004185 return C;
4186}
4187
4188const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004189 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004190
Nick Lewycky3e630762008-02-20 06:48:22 +00004191 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004192 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004193 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004194 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004195 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004196 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4197 if (PHINode *PN = dyn_cast<PHINode>(I))
4198 if (PN->getParent() == LI->getHeader()) {
4199 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004200 // to see if the loop that contains it has a known backedge-taken
4201 // count. If so, we may be able to force computation of the exit
4202 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004203 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004204 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004205 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004206 // Okay, we know how many times the containing loop executes. If
4207 // this is a constant evolving PHI node, get the final value at
4208 // the specified iteration number.
4209 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004210 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004211 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004212 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004213 }
4214 }
4215
Reid Spencer09906f32006-12-04 21:33:23 +00004216 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004217 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004218 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004219 // result. This is particularly useful for computing loop exit values.
4220 if (CanConstantFold(I)) {
4221 std::vector<Constant*> Operands;
4222 Operands.reserve(I->getNumOperands());
4223 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4224 Value *Op = I->getOperand(i);
4225 if (Constant *C = dyn_cast<Constant>(Op)) {
4226 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004227 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004228 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004229 // non-integer and non-pointer, don't even try to analyze them
4230 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004231 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004232 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004233
Dan Gohman5d984912009-12-18 01:14:11 +00004234 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004235 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004236 Constant *C = SC->getValue();
4237 if (C->getType() != Op->getType())
4238 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4239 Op->getType(),
4240 false),
4241 C, Op->getType());
4242 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004243 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004244 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4245 if (C->getType() != Op->getType())
4246 C =
4247 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4248 Op->getType(),
4249 false),
4250 C, Op->getType());
4251 Operands.push_back(C);
4252 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004253 return V;
4254 } else {
4255 return V;
4256 }
4257 }
4258 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004259
Dan Gohmane177c9a2010-02-24 19:31:47 +00004260 Constant *C = 0;
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004261 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4262 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004263 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004264 else
4265 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004266 &Operands[0], Operands.size(), TD);
Dan Gohmane177c9a2010-02-24 19:31:47 +00004267 if (C)
4268 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004269 }
4270 }
4271
4272 // This is some other type of SCEVUnknown, just return it.
4273 return V;
4274 }
4275
Dan Gohman622ed672009-05-04 22:02:23 +00004276 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004277 // Avoid performing the look-up in the common case where the specified
4278 // expression has no loop-variant portions.
4279 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004280 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004281 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004282 // Okay, at least one of these operands is loop variant but might be
4283 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004284 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4285 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004286 NewOps.push_back(OpAtScope);
4287
4288 for (++i; i != e; ++i) {
4289 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004290 NewOps.push_back(OpAtScope);
4291 }
4292 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004293 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004294 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004295 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004296 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004297 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004298 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004299 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004300 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004301 }
4302 }
4303 // If we got here, all operands are loop invariant.
4304 return Comm;
4305 }
4306
Dan Gohman622ed672009-05-04 22:02:23 +00004307 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004308 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4309 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004310 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4311 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004312 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004313 }
4314
4315 // If this is a loop recurrence for a loop that does not contain L, then we
4316 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004317 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004318 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004319 // To evaluate this recurrence, we need to know how many times the AddRec
4320 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004321 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004322 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004323
Eli Friedmanb42a6262008-08-04 23:49:06 +00004324 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004325 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004326 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004327 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004328 }
4329
Dan Gohman622ed672009-05-04 22:02:23 +00004330 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004331 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004332 if (Op == Cast->getOperand())
4333 return Cast; // must be loop invariant
4334 return getZeroExtendExpr(Op, Cast->getType());
4335 }
4336
Dan Gohman622ed672009-05-04 22:02:23 +00004337 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004338 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004339 if (Op == Cast->getOperand())
4340 return Cast; // must be loop invariant
4341 return getSignExtendExpr(Op, Cast->getType());
4342 }
4343
Dan Gohman622ed672009-05-04 22:02:23 +00004344 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004345 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004346 if (Op == Cast->getOperand())
4347 return Cast; // must be loop invariant
4348 return getTruncateExpr(Op, Cast->getType());
4349 }
4350
Torok Edwinc23197a2009-07-14 16:55:14 +00004351 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004352 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004353}
4354
Dan Gohman66a7e852009-05-08 20:38:54 +00004355/// getSCEVAtScope - This is a convenience function which does
4356/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004357const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004358 return getSCEVAtScope(getSCEV(V), L);
4359}
4360
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004361/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4362/// following equation:
4363///
4364/// A * X = B (mod N)
4365///
4366/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4367/// A and B isn't important.
4368///
4369/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004370static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004371 ScalarEvolution &SE) {
4372 uint32_t BW = A.getBitWidth();
4373 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4374 assert(A != 0 && "A must be non-zero.");
4375
4376 // 1. D = gcd(A, N)
4377 //
4378 // The gcd of A and N may have only one prime factor: 2. The number of
4379 // trailing zeros in A is its multiplicity
4380 uint32_t Mult2 = A.countTrailingZeros();
4381 // D = 2^Mult2
4382
4383 // 2. Check if B is divisible by D.
4384 //
4385 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4386 // is not less than multiplicity of this prime factor for D.
4387 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004388 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004389
4390 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4391 // modulo (N / D).
4392 //
4393 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4394 // bit width during computations.
4395 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4396 APInt Mod(BW + 1, 0);
4397 Mod.set(BW - Mult2); // Mod = N / D
4398 APInt I = AD.multiplicativeInverse(Mod);
4399
4400 // 4. Compute the minimum unsigned root of the equation:
4401 // I * (B / D) mod (N / D)
4402 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4403
4404 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4405 // bits.
4406 return SE.getConstant(Result.trunc(BW));
4407}
Chris Lattner53e677a2004-04-02 20:23:17 +00004408
4409/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4410/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4411/// might be the same) or two SCEVCouldNotCompute objects.
4412///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004413static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004414SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004415 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004416 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4417 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4418 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004419
Chris Lattner53e677a2004-04-02 20:23:17 +00004420 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004421 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004422 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004423 return std::make_pair(CNC, CNC);
4424 }
4425
Reid Spencere8019bb2007-03-01 07:25:48 +00004426 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004427 const APInt &L = LC->getValue()->getValue();
4428 const APInt &M = MC->getValue()->getValue();
4429 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004430 APInt Two(BitWidth, 2);
4431 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004432
Dan Gohman64a845e2009-06-24 04:48:43 +00004433 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004434 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004435 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004436 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4437 // The B coefficient is M-N/2
4438 APInt B(M);
4439 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004440
Reid Spencere8019bb2007-03-01 07:25:48 +00004441 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004442 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004443
Reid Spencere8019bb2007-03-01 07:25:48 +00004444 // Compute the B^2-4ac term.
4445 APInt SqrtTerm(B);
4446 SqrtTerm *= B;
4447 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004448
Reid Spencere8019bb2007-03-01 07:25:48 +00004449 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4450 // integer value or else APInt::sqrt() will assert.
4451 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004452
Dan Gohman64a845e2009-06-24 04:48:43 +00004453 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004454 // The divisions must be performed as signed divisions.
4455 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004456 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004457 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004458 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004459 return std::make_pair(CNC, CNC);
4460 }
4461
Owen Andersone922c022009-07-22 00:24:57 +00004462 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004463
4464 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004465 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004466 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004467 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004468
Dan Gohman64a845e2009-06-24 04:48:43 +00004469 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004470 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004471 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004472}
4473
4474/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004475/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004476ScalarEvolution::BackedgeTakenInfo
4477ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004478 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004479 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004480 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004481 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004482 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004483 }
4484
Dan Gohman35738ac2009-05-04 22:30:44 +00004485 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004486 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004487 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004488
4489 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004490 // If this is an affine expression, the execution count of this branch is
4491 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004492 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004493 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004494 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004495 // equivalent to:
4496 //
4497 // Step*N = -Start (mod 2^BW)
4498 //
4499 // where BW is the common bit width of Start and Step.
4500
Chris Lattner53e677a2004-04-02 20:23:17 +00004501 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004502 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4503 L->getParentLoop());
4504 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4505 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004506
Dan Gohman622ed672009-05-04 22:02:23 +00004507 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004508 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004509
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004510 // First, handle unitary steps.
4511 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004512 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004513 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4514 return Start; // N = Start (as unsigned)
4515
4516 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004517 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004518 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004519 -StartC->getValue()->getValue(),
4520 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004521 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004522 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004523 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4524 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004525 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004526 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004527 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4528 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004529 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004530#if 0
David Greene25e0e872009-12-23 22:18:14 +00004531 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004532 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004533#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004534 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004535 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004536 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004537 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004538 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004539 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004540
Chris Lattner53e677a2004-04-02 20:23:17 +00004541 // We can only use this value if the chrec ends up with an exact zero
4542 // value at this index. When solving for "X*X != 5", for example, we
4543 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004544 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004545 if (Val->isZero())
4546 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004547 }
4548 }
4549 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004550
Dan Gohman1c343752009-06-27 21:21:31 +00004551 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004552}
4553
4554/// HowFarToNonZero - Return the number of times a backedge checking the
4555/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004556/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004557ScalarEvolution::BackedgeTakenInfo
4558ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004559 // Loops that look like: while (X == 0) are very strange indeed. We don't
4560 // handle them yet except for the trivial case. This could be expanded in the
4561 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004562
Chris Lattner53e677a2004-04-02 20:23:17 +00004563 // If the value is a constant, check to see if it is known to be non-zero
4564 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004565 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004566 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004567 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004568 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004569 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004570
Chris Lattner53e677a2004-04-02 20:23:17 +00004571 // We could implement others, but I really doubt anyone writes loops like
4572 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004573 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004574}
4575
Dan Gohman859b4822009-05-18 15:36:09 +00004576/// getLoopPredecessor - If the given loop's header has exactly one unique
4577/// predecessor outside the loop, return it. Otherwise return null.
4578///
4579BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4580 BasicBlock *Header = L->getHeader();
4581 BasicBlock *Pred = 0;
4582 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4583 PI != E; ++PI)
4584 if (!L->contains(*PI)) {
4585 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4586 Pred = *PI;
4587 }
4588 return Pred;
4589}
4590
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004591/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4592/// (which may not be an immediate predecessor) which has exactly one
4593/// successor from which BB is reachable, or null if no such block is
4594/// found.
4595///
4596BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004597ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004598 // If the block has a unique predecessor, then there is no path from the
4599 // predecessor to the block that does not go through the direct edge
4600 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004601 if (BasicBlock *Pred = BB->getSinglePredecessor())
4602 return Pred;
4603
4604 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004605 // If the header has a unique predecessor outside the loop, it must be
4606 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004607 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004608 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004609
4610 return 0;
4611}
4612
Dan Gohman763bad12009-06-20 00:35:32 +00004613/// HasSameValue - SCEV structural equivalence is usually sufficient for
4614/// testing whether two expressions are equal, however for the purposes of
4615/// looking for a condition guarding a loop, it can be useful to be a little
4616/// more general, since a front-end may have replicated the controlling
4617/// expression.
4618///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004619static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004620 // Quick check to see if they are the same SCEV.
4621 if (A == B) return true;
4622
4623 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4624 // two different instructions with the same value. Check for this case.
4625 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4626 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4627 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4628 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004629 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004630 return true;
4631
4632 // Otherwise assume they may have a different value.
4633 return false;
4634}
4635
Dan Gohman85b05a22009-07-13 21:35:55 +00004636bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4637 return getSignedRange(S).getSignedMax().isNegative();
4638}
4639
4640bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4641 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4642}
4643
4644bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4645 return !getSignedRange(S).getSignedMin().isNegative();
4646}
4647
4648bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4649 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4650}
4651
4652bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4653 return isKnownNegative(S) || isKnownPositive(S);
4654}
4655
4656bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4657 const SCEV *LHS, const SCEV *RHS) {
4658
4659 if (HasSameValue(LHS, RHS))
4660 return ICmpInst::isTrueWhenEqual(Pred);
4661
4662 switch (Pred) {
4663 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004664 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004665 break;
4666 case ICmpInst::ICMP_SGT:
4667 Pred = ICmpInst::ICMP_SLT;
4668 std::swap(LHS, RHS);
4669 case ICmpInst::ICMP_SLT: {
4670 ConstantRange LHSRange = getSignedRange(LHS);
4671 ConstantRange RHSRange = getSignedRange(RHS);
4672 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4673 return true;
4674 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4675 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004676 break;
4677 }
4678 case ICmpInst::ICMP_SGE:
4679 Pred = ICmpInst::ICMP_SLE;
4680 std::swap(LHS, RHS);
4681 case ICmpInst::ICMP_SLE: {
4682 ConstantRange LHSRange = getSignedRange(LHS);
4683 ConstantRange RHSRange = getSignedRange(RHS);
4684 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4685 return true;
4686 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4687 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004688 break;
4689 }
4690 case ICmpInst::ICMP_UGT:
4691 Pred = ICmpInst::ICMP_ULT;
4692 std::swap(LHS, RHS);
4693 case ICmpInst::ICMP_ULT: {
4694 ConstantRange LHSRange = getUnsignedRange(LHS);
4695 ConstantRange RHSRange = getUnsignedRange(RHS);
4696 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4697 return true;
4698 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4699 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004700 break;
4701 }
4702 case ICmpInst::ICMP_UGE:
4703 Pred = ICmpInst::ICMP_ULE;
4704 std::swap(LHS, RHS);
4705 case ICmpInst::ICMP_ULE: {
4706 ConstantRange LHSRange = getUnsignedRange(LHS);
4707 ConstantRange RHSRange = getUnsignedRange(RHS);
4708 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4709 return true;
4710 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4711 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004712 break;
4713 }
4714 case ICmpInst::ICMP_NE: {
4715 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4716 return true;
4717 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4718 return true;
4719
4720 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4721 if (isKnownNonZero(Diff))
4722 return true;
4723 break;
4724 }
4725 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004726 // The check at the top of the function catches the case where
4727 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004728 break;
4729 }
4730 return false;
4731}
4732
4733/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4734/// protected by a conditional between LHS and RHS. This is used to
4735/// to eliminate casts.
4736bool
4737ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4738 ICmpInst::Predicate Pred,
4739 const SCEV *LHS, const SCEV *RHS) {
4740 // Interpret a null as meaning no loop, where there is obviously no guard
4741 // (interprocedural conditions notwithstanding).
4742 if (!L) return true;
4743
4744 BasicBlock *Latch = L->getLoopLatch();
4745 if (!Latch)
4746 return false;
4747
4748 BranchInst *LoopContinuePredicate =
4749 dyn_cast<BranchInst>(Latch->getTerminator());
4750 if (!LoopContinuePredicate ||
4751 LoopContinuePredicate->isUnconditional())
4752 return false;
4753
Dan Gohman0f4b2852009-07-21 23:03:19 +00004754 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4755 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004756}
4757
4758/// isLoopGuardedByCond - Test whether entry to the loop is protected
4759/// by a conditional between LHS and RHS. This is used to help avoid max
4760/// expressions in loop trip counts, and to eliminate casts.
4761bool
4762ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4763 ICmpInst::Predicate Pred,
4764 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004765 // Interpret a null as meaning no loop, where there is obviously no guard
4766 // (interprocedural conditions notwithstanding).
4767 if (!L) return false;
4768
Dan Gohman859b4822009-05-18 15:36:09 +00004769 BasicBlock *Predecessor = getLoopPredecessor(L);
4770 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004771
Dan Gohman859b4822009-05-18 15:36:09 +00004772 // Starting at the loop predecessor, climb up the predecessor chain, as long
4773 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004774 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004775 for (; Predecessor;
4776 PredecessorDest = Predecessor,
4777 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004778
4779 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004780 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004781 if (!LoopEntryPredicate ||
4782 LoopEntryPredicate->isUnconditional())
4783 continue;
4784
Dan Gohman0f4b2852009-07-21 23:03:19 +00004785 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4786 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004787 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004788 }
4789
Dan Gohman38372182008-08-12 20:17:31 +00004790 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004791}
4792
Dan Gohman0f4b2852009-07-21 23:03:19 +00004793/// isImpliedCond - Test whether the condition described by Pred, LHS,
4794/// and RHS is true whenever the given Cond value evaluates to true.
4795bool ScalarEvolution::isImpliedCond(Value *CondValue,
4796 ICmpInst::Predicate Pred,
4797 const SCEV *LHS, const SCEV *RHS,
4798 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004799 // Recursively handle And and Or conditions.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004800 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4801 if (BO->getOpcode() == Instruction::And) {
4802 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004803 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4804 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004805 } else if (BO->getOpcode() == Instruction::Or) {
4806 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004807 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4808 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004809 }
4810 }
4811
4812 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4813 if (!ICI) return false;
4814
Dan Gohman85b05a22009-07-13 21:35:55 +00004815 // Bail if the ICmp's operands' types are wider than the needed type
4816 // before attempting to call getSCEV on them. This avoids infinite
4817 // recursion, since the analysis of widening casts can require loop
4818 // exit condition information for overflow checking, which would
4819 // lead back here.
4820 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004821 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004822 return false;
4823
Dan Gohman0f4b2852009-07-21 23:03:19 +00004824 // Now that we found a conditional branch that dominates the loop, check to
4825 // see if it is the comparison we are looking for.
4826 ICmpInst::Predicate FoundPred;
4827 if (Inverse)
4828 FoundPred = ICI->getInversePredicate();
4829 else
4830 FoundPred = ICI->getPredicate();
4831
4832 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4833 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004834
4835 // Balance the types. The case where FoundLHS' type is wider than
4836 // LHS' type is checked for above.
4837 if (getTypeSizeInBits(LHS->getType()) >
4838 getTypeSizeInBits(FoundLHS->getType())) {
4839 if (CmpInst::isSigned(Pred)) {
4840 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4841 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4842 } else {
4843 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4844 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4845 }
4846 }
4847
Dan Gohman0f4b2852009-07-21 23:03:19 +00004848 // Canonicalize the query to match the way instcombine will have
4849 // canonicalized the comparison.
4850 // First, put a constant operand on the right.
4851 if (isa<SCEVConstant>(LHS)) {
4852 std::swap(LHS, RHS);
4853 Pred = ICmpInst::getSwappedPredicate(Pred);
4854 }
4855 // Then, canonicalize comparisons with boundary cases.
4856 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4857 const APInt &RA = RC->getValue()->getValue();
4858 switch (Pred) {
4859 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4860 case ICmpInst::ICMP_EQ:
4861 case ICmpInst::ICMP_NE:
4862 break;
4863 case ICmpInst::ICMP_UGE:
4864 if ((RA - 1).isMinValue()) {
4865 Pred = ICmpInst::ICMP_NE;
4866 RHS = getConstant(RA - 1);
4867 break;
4868 }
4869 if (RA.isMaxValue()) {
4870 Pred = ICmpInst::ICMP_EQ;
4871 break;
4872 }
4873 if (RA.isMinValue()) return true;
4874 break;
4875 case ICmpInst::ICMP_ULE:
4876 if ((RA + 1).isMaxValue()) {
4877 Pred = ICmpInst::ICMP_NE;
4878 RHS = getConstant(RA + 1);
4879 break;
4880 }
4881 if (RA.isMinValue()) {
4882 Pred = ICmpInst::ICMP_EQ;
4883 break;
4884 }
4885 if (RA.isMaxValue()) return true;
4886 break;
4887 case ICmpInst::ICMP_SGE:
4888 if ((RA - 1).isMinSignedValue()) {
4889 Pred = ICmpInst::ICMP_NE;
4890 RHS = getConstant(RA - 1);
4891 break;
4892 }
4893 if (RA.isMaxSignedValue()) {
4894 Pred = ICmpInst::ICMP_EQ;
4895 break;
4896 }
4897 if (RA.isMinSignedValue()) return true;
4898 break;
4899 case ICmpInst::ICMP_SLE:
4900 if ((RA + 1).isMaxSignedValue()) {
4901 Pred = ICmpInst::ICMP_NE;
4902 RHS = getConstant(RA + 1);
4903 break;
4904 }
4905 if (RA.isMinSignedValue()) {
4906 Pred = ICmpInst::ICMP_EQ;
4907 break;
4908 }
4909 if (RA.isMaxSignedValue()) return true;
4910 break;
4911 case ICmpInst::ICMP_UGT:
4912 if (RA.isMinValue()) {
4913 Pred = ICmpInst::ICMP_NE;
4914 break;
4915 }
4916 if ((RA + 1).isMaxValue()) {
4917 Pred = ICmpInst::ICMP_EQ;
4918 RHS = getConstant(RA + 1);
4919 break;
4920 }
4921 if (RA.isMaxValue()) return false;
4922 break;
4923 case ICmpInst::ICMP_ULT:
4924 if (RA.isMaxValue()) {
4925 Pred = ICmpInst::ICMP_NE;
4926 break;
4927 }
4928 if ((RA - 1).isMinValue()) {
4929 Pred = ICmpInst::ICMP_EQ;
4930 RHS = getConstant(RA - 1);
4931 break;
4932 }
4933 if (RA.isMinValue()) return false;
4934 break;
4935 case ICmpInst::ICMP_SGT:
4936 if (RA.isMinSignedValue()) {
4937 Pred = ICmpInst::ICMP_NE;
4938 break;
4939 }
4940 if ((RA + 1).isMaxSignedValue()) {
4941 Pred = ICmpInst::ICMP_EQ;
4942 RHS = getConstant(RA + 1);
4943 break;
4944 }
4945 if (RA.isMaxSignedValue()) return false;
4946 break;
4947 case ICmpInst::ICMP_SLT:
4948 if (RA.isMaxSignedValue()) {
4949 Pred = ICmpInst::ICMP_NE;
4950 break;
4951 }
4952 if ((RA - 1).isMinSignedValue()) {
4953 Pred = ICmpInst::ICMP_EQ;
4954 RHS = getConstant(RA - 1);
4955 break;
4956 }
4957 if (RA.isMinSignedValue()) return false;
4958 break;
4959 }
4960 }
4961
4962 // Check to see if we can make the LHS or RHS match.
4963 if (LHS == FoundRHS || RHS == FoundLHS) {
4964 if (isa<SCEVConstant>(RHS)) {
4965 std::swap(FoundLHS, FoundRHS);
4966 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4967 } else {
4968 std::swap(LHS, RHS);
4969 Pred = ICmpInst::getSwappedPredicate(Pred);
4970 }
4971 }
4972
4973 // Check whether the found predicate is the same as the desired predicate.
4974 if (FoundPred == Pred)
4975 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4976
4977 // Check whether swapping the found predicate makes it the same as the
4978 // desired predicate.
4979 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4980 if (isa<SCEVConstant>(RHS))
4981 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4982 else
4983 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4984 RHS, LHS, FoundLHS, FoundRHS);
4985 }
4986
4987 // Check whether the actual condition is beyond sufficient.
4988 if (FoundPred == ICmpInst::ICMP_EQ)
4989 if (ICmpInst::isTrueWhenEqual(Pred))
4990 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4991 return true;
4992 if (Pred == ICmpInst::ICMP_NE)
4993 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4994 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4995 return true;
4996
4997 // Otherwise assume the worst.
4998 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004999}
5000
Dan Gohman0f4b2852009-07-21 23:03:19 +00005001/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005002/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005003/// and FoundRHS is true.
5004bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5005 const SCEV *LHS, const SCEV *RHS,
5006 const SCEV *FoundLHS,
5007 const SCEV *FoundRHS) {
5008 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5009 FoundLHS, FoundRHS) ||
5010 // ~x < ~y --> x > y
5011 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5012 getNotSCEV(FoundRHS),
5013 getNotSCEV(FoundLHS));
5014}
5015
5016/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005017/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005018/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005019bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005020ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5021 const SCEV *LHS, const SCEV *RHS,
5022 const SCEV *FoundLHS,
5023 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005024 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005025 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5026 case ICmpInst::ICMP_EQ:
5027 case ICmpInst::ICMP_NE:
5028 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5029 return true;
5030 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005031 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005032 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005033 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5034 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5035 return true;
5036 break;
5037 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005038 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005039 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5040 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5041 return true;
5042 break;
5043 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005044 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005045 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5046 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5047 return true;
5048 break;
5049 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005050 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005051 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5052 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5053 return true;
5054 break;
5055 }
5056
5057 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005058}
5059
Dan Gohman51f53b72009-06-21 23:46:38 +00005060/// getBECount - Subtract the end and start values and divide by the step,
5061/// rounding up, to get the number of times the backedge is executed. Return
5062/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005063const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005064 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005065 const SCEV *Step,
5066 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005067 assert(!isKnownNegative(Step) &&
5068 "This code doesn't handle negative strides yet!");
5069
Dan Gohman51f53b72009-06-21 23:46:38 +00005070 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00005071 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
5072 const SCEV *Diff = getMinusSCEV(End, Start);
5073 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005074
5075 // Add an adjustment to the difference between End and Start so that
5076 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005077 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005078
Dan Gohman1f96e672009-09-17 18:05:20 +00005079 if (!NoWrap) {
5080 // Check Add for unsigned overflow.
5081 // TODO: More sophisticated things could be done here.
5082 const Type *WideTy = IntegerType::get(getContext(),
5083 getTypeSizeInBits(Ty) + 1);
5084 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5085 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5086 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5087 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5088 return getCouldNotCompute();
5089 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005090
5091 return getUDivExpr(Add, Step);
5092}
5093
Chris Lattnerdb25de42005-08-15 23:33:51 +00005094/// HowManyLessThans - Return the number of times a backedge containing the
5095/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005096/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005097ScalarEvolution::BackedgeTakenInfo
5098ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5099 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005100 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005101 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005102
Dan Gohman35738ac2009-05-04 22:30:44 +00005103 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005104 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005105 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005106
Dan Gohman1f96e672009-09-17 18:05:20 +00005107 // Check to see if we have a flag which makes analysis easy.
5108 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5109 AddRec->hasNoUnsignedWrap();
5110
Chris Lattnerdb25de42005-08-15 23:33:51 +00005111 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005112 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005113 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005114
Dan Gohman52fddd32010-01-26 04:40:18 +00005115 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005116 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005117 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005118 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005119 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005120 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005121 // value and past the maximum value for its type in a single step.
5122 // Note that it's not sufficient to check NoWrap here, because even
5123 // though the value after a wrap is undefined, it's not undefined
5124 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005125 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005126 // iterate at least until the iteration where the wrapping occurs.
5127 const SCEV *One = getIntegerSCEV(1, Step->getType());
5128 if (isSigned) {
5129 APInt Max = APInt::getSignedMaxValue(BitWidth);
5130 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5131 .slt(getSignedRange(RHS).getSignedMax()))
5132 return getCouldNotCompute();
5133 } else {
5134 APInt Max = APInt::getMaxValue(BitWidth);
5135 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5136 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5137 return getCouldNotCompute();
5138 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005139 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005140 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005141 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005142
Dan Gohmana1af7572009-04-30 20:47:05 +00005143 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5144 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5145 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005146 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005147
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005148 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005149 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005150
Dan Gohmana1af7572009-04-30 20:47:05 +00005151 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005152 const SCEV *MinStart = getConstant(isSigned ?
5153 getSignedRange(Start).getSignedMin() :
5154 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005155
Dan Gohmana1af7572009-04-30 20:47:05 +00005156 // If we know that the condition is true in order to enter the loop,
5157 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005158 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5159 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005160 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005161 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005162 isSigned ? ICmpInst::ICMP_SLT :
5163 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005164 getMinusSCEV(Start, Step), RHS))
5165 End = isSigned ? getSMaxExpr(RHS, Start)
5166 : getUMaxExpr(RHS, Start);
5167
5168 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005169 const SCEV *MaxEnd = getConstant(isSigned ?
5170 getSignedRange(End).getSignedMax() :
5171 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005172
Dan Gohman52fddd32010-01-26 04:40:18 +00005173 // If MaxEnd is within a step of the maximum integer value in its type,
5174 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005175 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005176 // compute the correct value.
5177 const SCEV *StepMinusOne = getMinusSCEV(Step,
5178 getIntegerSCEV(1, Step->getType()));
5179 MaxEnd = isSigned ?
5180 getSMinExpr(MaxEnd,
5181 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5182 StepMinusOne)) :
5183 getUMinExpr(MaxEnd,
5184 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5185 StepMinusOne));
5186
Dan Gohmana1af7572009-04-30 20:47:05 +00005187 // Finally, we subtract these two values and divide, rounding up, to get
5188 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005189 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005190
5191 // The maximum backedge count is similar, except using the minimum start
5192 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005193 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005194
5195 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005196 }
5197
Dan Gohman1c343752009-06-27 21:21:31 +00005198 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005199}
5200
Chris Lattner53e677a2004-04-02 20:23:17 +00005201/// getNumIterationsInRange - Return the number of iterations of this loop that
5202/// produce values in the specified constant range. Another way of looking at
5203/// this is that it returns the first iteration number where the value is not in
5204/// the condition, thus computing the exit count. If the iteration count can't
5205/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005206const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005207 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005208 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005209 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005210
5211 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005212 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005213 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005214 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005215 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005216 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005217 if (const SCEVAddRecExpr *ShiftedAddRec =
5218 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005219 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005220 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005221 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005222 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005223 }
5224
5225 // The only time we can solve this is when we have all constant indices.
5226 // Otherwise, we cannot determine the overflow conditions.
5227 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5228 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005229 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005230
5231
5232 // Okay at this point we know that all elements of the chrec are constants and
5233 // that the start element is zero.
5234
5235 // First check to see if the range contains zero. If not, the first
5236 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005237 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005238 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005239 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005240
Chris Lattner53e677a2004-04-02 20:23:17 +00005241 if (isAffine()) {
5242 // If this is an affine expression then we have this situation:
5243 // Solve {0,+,A} in Range === Ax in Range
5244
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005245 // We know that zero is in the range. If A is positive then we know that
5246 // the upper value of the range must be the first possible exit value.
5247 // If A is negative then the lower of the range is the last possible loop
5248 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005249 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005250 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5251 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005252
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005253 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005254 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005255 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005256
5257 // Evaluate at the exit value. If we really did fall out of the valid
5258 // range, then we computed our trip count, otherwise wrap around or other
5259 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005260 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005261 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005262 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005263
5264 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005265 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005266 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005267 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005268 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005269 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005270 } else if (isQuadratic()) {
5271 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5272 // quadratic equation to solve it. To do this, we must frame our problem in
5273 // terms of figuring out when zero is crossed, instead of when
5274 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005275 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005276 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005277 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005278
5279 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005280 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005281 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005282 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5283 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005284 if (R1) {
5285 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005286 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005287 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005288 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005289 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005290 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005291
Chris Lattner53e677a2004-04-02 20:23:17 +00005292 // Make sure the root is not off by one. The returned iteration should
5293 // not be in the range, but the previous one should be. When solving
5294 // for "X*X < 5", for example, we should not return a root of 2.
5295 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005296 R1->getValue(),
5297 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005298 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005299 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005300 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005301 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005302
Dan Gohman246b2562007-10-22 18:31:58 +00005303 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005304 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005305 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005306 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005307 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005308
Chris Lattner53e677a2004-04-02 20:23:17 +00005309 // If R1 was not in the range, then it is a good return value. Make
5310 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005311 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005312 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005313 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005314 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005315 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005316 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005317 }
5318 }
5319 }
5320
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005321 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005322}
5323
5324
5325
5326//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005327// SCEVCallbackVH Class Implementation
5328//===----------------------------------------------------------------------===//
5329
Dan Gohman1959b752009-05-19 19:22:47 +00005330void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005331 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005332 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5333 SE->ConstantEvolutionLoopExitValue.erase(PN);
5334 SE->Scalars.erase(getValPtr());
5335 // this now dangles!
5336}
5337
Dan Gohman1959b752009-05-19 19:22:47 +00005338void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005339 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005340
5341 // Forget all the expressions associated with users of the old value,
5342 // so that future queries will recompute the expressions using the new
5343 // value.
5344 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005345 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005346 Value *Old = getValPtr();
5347 bool DeleteOld = false;
5348 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5349 UI != UE; ++UI)
5350 Worklist.push_back(*UI);
5351 while (!Worklist.empty()) {
5352 User *U = Worklist.pop_back_val();
5353 // Deleting the Old value will cause this to dangle. Postpone
5354 // that until everything else is done.
5355 if (U == Old) {
5356 DeleteOld = true;
5357 continue;
5358 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005359 if (!Visited.insert(U))
5360 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005361 if (PHINode *PN = dyn_cast<PHINode>(U))
5362 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005363 SE->Scalars.erase(U);
5364 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5365 UI != UE; ++UI)
5366 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005367 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005368 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005369 if (DeleteOld) {
5370 if (PHINode *PN = dyn_cast<PHINode>(Old))
5371 SE->ConstantEvolutionLoopExitValue.erase(PN);
5372 SE->Scalars.erase(Old);
5373 // this now dangles!
5374 }
5375 // this may dangle!
5376}
5377
Dan Gohman1959b752009-05-19 19:22:47 +00005378ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005379 : CallbackVH(V), SE(se) {}
5380
5381//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005382// ScalarEvolution Class Implementation
5383//===----------------------------------------------------------------------===//
5384
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005385ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005386 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005387}
5388
Chris Lattner53e677a2004-04-02 20:23:17 +00005389bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005390 this->F = &F;
5391 LI = &getAnalysis<LoopInfo>();
5392 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005393 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005394 return false;
5395}
5396
5397void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005398 Scalars.clear();
5399 BackedgeTakenCounts.clear();
5400 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005401 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005402 UniqueSCEVs.clear();
5403 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005404}
5405
5406void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5407 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005408 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005409 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005410}
5411
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005412bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005413 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005414}
5415
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005416static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005417 const Loop *L) {
5418 // Print all inner loops first
5419 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5420 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005421
Dan Gohman30733292010-01-09 18:17:45 +00005422 OS << "Loop ";
5423 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5424 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005425
Dan Gohman5d984912009-12-18 01:14:11 +00005426 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005427 L->getExitBlocks(ExitBlocks);
5428 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005429 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005430
Dan Gohman46bdfb02009-02-24 18:55:53 +00005431 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5432 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005433 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005434 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005435 }
5436
Dan Gohman30733292010-01-09 18:17:45 +00005437 OS << "\n"
5438 "Loop ";
5439 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5440 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005441
5442 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5443 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5444 } else {
5445 OS << "Unpredictable max backedge-taken count. ";
5446 }
5447
5448 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005449}
5450
Dan Gohman5d984912009-12-18 01:14:11 +00005451void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005452 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005453 // out SCEV values of all instructions that are interesting. Doing
5454 // this potentially causes it to create new SCEV objects though,
5455 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005456 // observable from outside the class though, so casting away the
5457 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005458 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005459
Dan Gohman30733292010-01-09 18:17:45 +00005460 OS << "Classifying expressions for: ";
5461 WriteAsOperand(OS, F, /*PrintType=*/false);
5462 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005463 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005464 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005465 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005466 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005467 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005468 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005469
Dan Gohman0c689c52009-06-19 17:49:54 +00005470 const Loop *L = LI->getLoopFor((*I).getParent());
5471
Dan Gohman0bba49c2009-07-07 17:06:11 +00005472 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005473 if (AtUse != SV) {
5474 OS << " --> ";
5475 AtUse->print(OS);
5476 }
5477
5478 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005479 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005480 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005481 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005482 OS << "<<Unknown>>";
5483 } else {
5484 OS << *ExitValue;
5485 }
5486 }
5487
Chris Lattner53e677a2004-04-02 20:23:17 +00005488 OS << "\n";
5489 }
5490
Dan Gohman30733292010-01-09 18:17:45 +00005491 OS << "Determining loop execution counts for: ";
5492 WriteAsOperand(OS, F, /*PrintType=*/false);
5493 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005494 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5495 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005496}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005497