blob: cbeda2d3ae696488866f0b139399e53defe1d0e0 [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 Gohman0bba49c2009-07-07 17:06:11 +000017// can handle. These classes are reference counted, managed by the const SCEV *
Chris Lattner53e677a2004-04-02 20:23:17 +000018// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/ConstantRange.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000121 print(errs());
122 errs() << '\n';
123}
124
125void SCEV::print(std::ostream &o) const {
126 raw_os_ostream OS(o);
127 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000128}
129
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000130bool SCEV::isZero() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isZero();
133 return false;
134}
135
Dan Gohman70a1fe72009-05-18 15:22:39 +0000136bool SCEV::isOne() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isOne();
139 return false;
140}
Chris Lattner53e677a2004-04-02 20:23:17 +0000141
Dan Gohman4d289bf2009-06-24 00:30:26 +0000142bool SCEV::isAllOnesValue() const {
143 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
144 return SC->getValue()->isAllOnesValue();
145 return false;
146}
147
Owen Anderson753ad612009-06-22 21:57:23 +0000148SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000149 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000150
Chris Lattner53e677a2004-04-02 20:23:17 +0000151bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) 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 false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000158 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000159}
160
161bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000163 return false;
164}
165
Dan Gohman64a845e2009-06-24 04:48:43 +0000166const SCEV *
167SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
168 const SCEV *Sym,
169 const SCEV *Conc,
170 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000171 return this;
172}
173
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000174void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000175 OS << "***COULDNOTCOMPUTE***";
176}
177
178bool SCEVCouldNotCompute::classof(const SCEV *S) {
179 return S->getSCEVType() == scCouldNotCompute;
180}
181
Dan Gohman0bba49c2009-07-07 17:06:11 +0000182const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000183 FoldingSetNodeID ID;
184 ID.AddInteger(scConstant);
185 ID.AddPointer(V);
186 void *IP = 0;
187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
188 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000189 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000190 UniqueSCEVs.InsertNode(S, IP);
191 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Dan Gohman0bba49c2009-07-07 17:06:11 +0000194const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersone922c022009-07-22 00:24:57 +0000195 return getConstant(getContext().getConstantInt(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000196}
197
Dan Gohman0bba49c2009-07-07 17:06:11 +0000198const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000199ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000200 return getConstant(
Owen Andersone922c022009-07-22 00:24:57 +0000201 getContext().getConstantInt(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000202}
203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000205
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000206void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207 WriteAsOperand(OS, V, false);
208}
Chris Lattner53e677a2004-04-02 20:23:17 +0000209
Dan Gohmanc050fd92009-07-13 20:50:19 +0000210SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
211 unsigned SCEVTy, const SCEV *op, const Type *ty)
212 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000213
Dan Gohman84923602009-04-21 01:25:57 +0000214bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
215 return Op->dominates(BB, DT);
216}
217
Dan Gohmanc050fd92009-07-13 20:50:19 +0000218SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
219 const SCEV *op, const Type *ty)
220 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000221 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
222 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
Chris Lattner53e677a2004-04-02 20:23:17 +0000225
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000226void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000227 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228}
229
Dan Gohmanc050fd92009-07-13 20:50:19 +0000230SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
231 const SCEV *op, const Type *ty)
232 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000238void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000239 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000240}
241
Dan Gohmanc050fd92009-07-13 20:50:19 +0000242SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
243 const SCEV *op, const Type *ty)
244 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000245 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
246 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000247 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000251 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000252}
253
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000254void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
256 const char *OpStr = getOperationStr();
257 OS << "(" << *Operands[0];
258 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
259 OS << OpStr << *Operands[i];
260 OS << ")";
261}
262
Dan Gohman64a845e2009-06-24 04:48:43 +0000263const SCEV *
264SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
265 const SCEV *Sym,
266 const SCEV *Conc,
267 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000269 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000270 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000271 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000272 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000273 NewOps.reserve(getNumOperands());
274 for (unsigned j = 0; j != i; ++j)
275 NewOps.push_back(getOperand(j));
276 NewOps.push_back(H);
277 for (++i; i != e; ++i)
278 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000279 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000280
281 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000282 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000283 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000284 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000285 else if (isa<SCEVSMaxExpr>(this))
286 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000287 else if (isa<SCEVUMaxExpr>(this))
288 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000289 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000290 llvm_unreachable("Unknown commutative expr!");
Chris Lattner4dc534c2005-02-13 04:37:18 +0000291 }
292 }
293 return this;
294}
295
Dan Gohmanecb403a2009-05-07 14:00:19 +0000296bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000297 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
298 if (!getOperand(i)->dominates(BB, DT))
299 return false;
300 }
301 return true;
302}
303
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000304bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
305 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
306}
307
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000308void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000309 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000310}
311
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000312const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000313 // In most cases the types of LHS and RHS will be the same, but in some
314 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
315 // depend on the type for correctness, but handling types carefully can
316 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
317 // a pointer type than the RHS, so use the RHS' type here.
318 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000319}
320
Dan Gohman64a845e2009-06-24 04:48:43 +0000321const SCEV *
322SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
323 const SCEV *Conc,
324 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000325 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000326 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000327 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000328 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000329 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000330 NewOps.reserve(getNumOperands());
331 for (unsigned j = 0; j != i; ++j)
332 NewOps.push_back(getOperand(j));
333 NewOps.push_back(H);
334 for (++i; i != e; ++i)
335 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000336 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000337
Dan Gohman246b2562007-10-22 18:31:58 +0000338 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000339 }
340 }
341 return this;
342}
343
344
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000346 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000347 if (!QueryLoop)
348 return false;
349
350 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
351 if (QueryLoop->contains(L->getHeader()))
352 return false;
353
354 // This recurrence is variant w.r.t. QueryLoop if any of its operands
355 // are variant.
356 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
357 if (!getOperand(i)->isLoopInvariant(QueryLoop))
358 return false;
359
360 // Otherwise it's loop-invariant.
361 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000362}
363
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000364void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000365 OS << "{" << *Operands[0];
366 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
367 OS << ",+," << *Operands[i];
368 OS << "}<" << L->getHeader()->getName() + ">";
369}
Chris Lattner53e677a2004-04-02 20:23:17 +0000370
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000371bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
372 // All non-instruction values are loop invariant. All instructions are loop
373 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000374 // Instructions are never considered invariant in the function body
375 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000376 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000377 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000378 return true;
379}
Chris Lattner53e677a2004-04-02 20:23:17 +0000380
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000381bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
382 if (Instruction *I = dyn_cast<Instruction>(getValue()))
383 return DT->dominates(I->getParent(), BB);
384 return true;
385}
386
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000387const Type *SCEVUnknown::getType() const {
388 return V->getType();
389}
Chris Lattner53e677a2004-04-02 20:23:17 +0000390
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000391void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000392 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000393}
394
Chris Lattner8d741b82004-06-20 06:23:15 +0000395//===----------------------------------------------------------------------===//
396// SCEV Utilities
397//===----------------------------------------------------------------------===//
398
399namespace {
400 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
401 /// than the complexity of the RHS. This comparator is used to canonicalize
402 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000403 class VISIBILITY_HIDDEN SCEVComplexityCompare {
404 LoopInfo *LI;
405 public:
406 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
407
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000408 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000409 // Primarily, sort the SCEVs by their getSCEVType().
410 if (LHS->getSCEVType() != RHS->getSCEVType())
411 return LHS->getSCEVType() < RHS->getSCEVType();
412
413 // Aside from the getSCEVType() ordering, the particular ordering
414 // isn't very important except that it's beneficial to be consistent,
415 // so that (a + b) and (b + a) don't end up as different expressions.
416
417 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
418 // not as complete as it could be.
419 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
420 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
421
Dan Gohman5be18e82009-05-19 02:15:55 +0000422 // Order pointer values after integer values. This helps SCEVExpander
423 // form GEPs.
424 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
425 return false;
426 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
427 return true;
428
Dan Gohman72861302009-05-07 14:39:04 +0000429 // Compare getValueID values.
430 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
431 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
432
433 // Sort arguments by their position.
434 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
435 const Argument *RA = cast<Argument>(RU->getValue());
436 return LA->getArgNo() < RA->getArgNo();
437 }
438
439 // For instructions, compare their loop depth, and their opcode.
440 // This is pretty loose.
441 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
442 Instruction *RV = cast<Instruction>(RU->getValue());
443
444 // Compare loop depths.
445 if (LI->getLoopDepth(LV->getParent()) !=
446 LI->getLoopDepth(RV->getParent()))
447 return LI->getLoopDepth(LV->getParent()) <
448 LI->getLoopDepth(RV->getParent());
449
450 // Compare opcodes.
451 if (LV->getOpcode() != RV->getOpcode())
452 return LV->getOpcode() < RV->getOpcode();
453
454 // Compare the number of operands.
455 if (LV->getNumOperands() != RV->getNumOperands())
456 return LV->getNumOperands() < RV->getNumOperands();
457 }
458
459 return false;
460 }
461
Dan Gohman4dfad292009-06-14 22:51:25 +0000462 // Compare constant values.
463 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
464 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000465 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
466 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000467 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
468 }
469
470 // Compare addrec loop depths.
471 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
472 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
473 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
474 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
475 }
Dan Gohman72861302009-05-07 14:39:04 +0000476
477 // Lexicographically compare n-ary expressions.
478 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
479 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
480 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
481 if (i >= RC->getNumOperands())
482 return false;
483 if (operator()(LC->getOperand(i), RC->getOperand(i)))
484 return true;
485 if (operator()(RC->getOperand(i), LC->getOperand(i)))
486 return false;
487 }
488 return LC->getNumOperands() < RC->getNumOperands();
489 }
490
Dan Gohmana6b35e22009-05-07 19:23:21 +0000491 // Lexicographically compare udiv expressions.
492 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
493 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
494 if (operator()(LC->getLHS(), RC->getLHS()))
495 return true;
496 if (operator()(RC->getLHS(), LC->getLHS()))
497 return false;
498 if (operator()(LC->getRHS(), RC->getRHS()))
499 return true;
500 if (operator()(RC->getRHS(), LC->getRHS()))
501 return false;
502 return false;
503 }
504
Dan Gohman72861302009-05-07 14:39:04 +0000505 // Compare cast expressions by operand.
506 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
507 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
508 return operator()(LC->getOperand(), RC->getOperand());
509 }
510
Torok Edwinc23197a2009-07-14 16:55:14 +0000511 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000512 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000513 }
514 };
515}
516
517/// GroupByComplexity - Given a list of SCEV objects, order them by their
518/// complexity, and group objects of the same complexity together by value.
519/// When this routine is finished, we know that any duplicates in the vector are
520/// consecutive and that complexity is monotonically increasing.
521///
522/// Note that we go take special precautions to ensure that we get determinstic
523/// results from this routine. In other words, we don't want the results of
524/// this to depend on where the addresses of various SCEV objects happened to
525/// land in memory.
526///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000527static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000528 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000529 if (Ops.size() < 2) return; // Noop
530 if (Ops.size() == 2) {
531 // This is the common case, which also happens to be trivially simple.
532 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000533 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000534 std::swap(Ops[0], Ops[1]);
535 return;
536 }
537
538 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000539 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000540
541 // Now that we are sorted by complexity, group elements of the same
542 // complexity. Note that this is, at worst, N^2, but the vector is likely to
543 // be extremely short in practice. Note that we take this approach because we
544 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000545 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000546 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000547 unsigned Complexity = S->getSCEVType();
548
549 // If there are any objects of the same complexity and same value as this
550 // one, group them.
551 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
552 if (Ops[j] == S) { // Found a duplicate.
553 // Move it to immediately after i'th element.
554 std::swap(Ops[i+1], Ops[j]);
555 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000556 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000557 }
558 }
559 }
560}
561
Chris Lattner53e677a2004-04-02 20:23:17 +0000562
Chris Lattner53e677a2004-04-02 20:23:17 +0000563
564//===----------------------------------------------------------------------===//
565// Simple SCEV method implementations
566//===----------------------------------------------------------------------===//
567
Eli Friedmanb42a6262008-08-04 23:49:06 +0000568/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000569/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000570static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000571 ScalarEvolution &SE,
572 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000573 // Handle the simplest case efficiently.
574 if (K == 1)
575 return SE.getTruncateOrZeroExtend(It, ResultTy);
576
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000577 // We are using the following formula for BC(It, K):
578 //
579 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
580 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000581 // Suppose, W is the bitwidth of the return value. We must be prepared for
582 // overflow. Hence, we must assure that the result of our computation is
583 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
584 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000585 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000587 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000588 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
589 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000590 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000591 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000592 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000593 // This formula is trivially equivalent to the previous formula. However,
594 // this formula can be implemented much more efficiently. The trick is that
595 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
596 // arithmetic. To do exact division in modular arithmetic, all we have
597 // to do is multiply by the inverse. Therefore, this step can be done at
598 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000599 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000600 // The next issue is how to safely do the division by 2^T. The way this
601 // is done is by doing the multiplication step at a width of at least W + T
602 // bits. This way, the bottom W+T bits of the product are accurate. Then,
603 // when we perform the division by 2^T (which is equivalent to a right shift
604 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
605 // truncated out after the division by 2^T.
606 //
607 // In comparison to just directly using the first formula, this technique
608 // is much more efficient; using the first formula requires W * K bits,
609 // but this formula less than W + K bits. Also, the first formula requires
610 // a division step, whereas this formula only requires multiplies and shifts.
611 //
612 // It doesn't matter whether the subtraction step is done in the calculation
613 // width or the input iteration count's width; if the subtraction overflows,
614 // the result must be zero anyway. We prefer here to do it in the width of
615 // the induction variable because it helps a lot for certain cases; CodeGen
616 // isn't smart enough to ignore the overflow, which leads to much less
617 // efficient code if the width of the subtraction is wider than the native
618 // register width.
619 //
620 // (It's possible to not widen at all by pulling out factors of 2 before
621 // the multiplication; for example, K=2 can be calculated as
622 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
623 // extra arithmetic, so it's not an obvious win, and it gets
624 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000625
Eli Friedmanb42a6262008-08-04 23:49:06 +0000626 // Protection from insane SCEVs; this bound is conservative,
627 // but it probably doesn't matter.
628 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000629 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000630
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000631 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632
Eli Friedmanb42a6262008-08-04 23:49:06 +0000633 // Calculate K! / 2^T and T; we divide out the factors of two before
634 // multiplying for calculating K! / 2^T to avoid overflow.
635 // Other overflow doesn't matter because we only care about the bottom
636 // W bits of the result.
637 APInt OddFactorial(W, 1);
638 unsigned T = 1;
639 for (unsigned i = 3; i <= K; ++i) {
640 APInt Mult(W, i);
641 unsigned TwoFactors = Mult.countTrailingZeros();
642 T += TwoFactors;
643 Mult = Mult.lshr(TwoFactors);
644 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000645 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000646
Eli Friedmanb42a6262008-08-04 23:49:06 +0000647 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000648 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000649
650 // Calcuate 2^T, at width T+W.
651 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
652
653 // Calculate the multiplicative inverse of K! / 2^T;
654 // this multiplication factor will perform the exact division by
655 // K! / 2^T.
656 APInt Mod = APInt::getSignedMinValue(W+1);
657 APInt MultiplyFactor = OddFactorial.zext(W+1);
658 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
659 MultiplyFactor = MultiplyFactor.trunc(W);
660
661 // Calculate the product, at width T+W
662 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000663 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000664 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000665 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000666 Dividend = SE.getMulExpr(Dividend,
667 SE.getTruncateOrZeroExtend(S, CalculationTy));
668 }
669
670 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000671 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000672
673 // Truncate the result, and divide by K! / 2^T.
674
675 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
676 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000677}
678
Chris Lattner53e677a2004-04-02 20:23:17 +0000679/// evaluateAtIteration - Return the value of this chain of recurrences at
680/// the specified iteration number. We can evaluate this recurrence by
681/// multiplying each element in the chain by the binomial coefficient
682/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
683///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000684/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000685///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000686/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000687///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000688const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000689 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000690 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000691 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000692 // The computation is correct in the face of overflow provided that the
693 // multiplication is performed _after_ the evaluation of the binomial
694 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000695 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000696 if (isa<SCEVCouldNotCompute>(Coeff))
697 return Coeff;
698
699 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000700 }
701 return Result;
702}
703
Chris Lattner53e677a2004-04-02 20:23:17 +0000704//===----------------------------------------------------------------------===//
705// SCEV Expression folder implementations
706//===----------------------------------------------------------------------===//
707
Dan Gohman0bba49c2009-07-07 17:06:11 +0000708const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000709 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000710 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000711 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000712 assert(isSCEVable(Ty) &&
713 "This is not a conversion to a SCEVable type!");
714 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000715
Dan Gohmanc050fd92009-07-13 20:50:19 +0000716 FoldingSetNodeID ID;
717 ID.AddInteger(scTruncate);
718 ID.AddPointer(Op);
719 ID.AddPointer(Ty);
720 void *IP = 0;
721 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
722
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000723 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000724 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000725 return getConstant(
726 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000727
Dan Gohman20900ca2009-04-22 16:20:48 +0000728 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000729 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000730 return getTruncateExpr(ST->getOperand(), Ty);
731
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000732 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000733 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000734 return getTruncateOrSignExtend(SS->getOperand(), Ty);
735
736 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000737 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000738 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
739
Dan Gohman6864db62009-06-18 16:24:47 +0000740 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000741 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000742 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000743 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000744 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
745 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000746 }
747
Dan Gohmanc050fd92009-07-13 20:50:19 +0000748 // The cast wasn't folded; create an explicit cast node.
749 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000750 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
751 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000752 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000753 UniqueSCEVs.InsertNode(S, IP);
754 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000755}
756
Dan Gohman0bba49c2009-07-07 17:06:11 +0000757const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000758 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000759 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000760 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000761 assert(isSCEVable(Ty) &&
762 "This is not a conversion to a SCEVable type!");
763 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000764
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000765 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000766 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000767 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000768 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
769 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000770 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000771 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000772
Dan Gohman20900ca2009-04-22 16:20:48 +0000773 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000774 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000775 return getZeroExtendExpr(SZ->getOperand(), Ty);
776
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000777 // Before doing any expensive analysis, check to see if we've already
778 // computed a SCEV for this Op and Ty.
779 FoldingSetNodeID ID;
780 ID.AddInteger(scZeroExtend);
781 ID.AddPointer(Op);
782 ID.AddPointer(Ty);
783 void *IP = 0;
784 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
785
Dan Gohman01ecca22009-04-27 20:16:15 +0000786 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000787 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000788 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000790 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000791 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000792 const SCEV *Start = AR->getStart();
793 const SCEV *Step = AR->getStepRecurrence(*this);
794 unsigned BitWidth = getTypeSizeInBits(AR->getType());
795 const Loop *L = AR->getLoop();
796
Dan Gohman01ecca22009-04-27 20:16:15 +0000797 // Check whether the backedge-taken count is SCEVCouldNotCompute.
798 // Note that this serves two purposes: It filters out loops that are
799 // simply not analyzable, and it covers the case where this code is
800 // being called from within backedge-taken count analysis, such that
801 // attempting to ask for the backedge-taken count would likely result
802 // in infinite recursion. In the later case, the analysis code will
803 // cope with a conservative value, and it will take care to purge
804 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000805 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000806 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000807 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000808 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000809
810 // Check whether the backedge-taken count can be losslessly casted to
811 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000812 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000813 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000814 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000815 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
816 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000817 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000818 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000819 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000820 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000821 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000822 const SCEV *Add = getAddExpr(Start, ZMul);
823 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000824 getAddExpr(getZeroExtendExpr(Start, WideTy),
825 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
826 getZeroExtendExpr(Step, WideTy)));
827 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000828 // Return the expression with the addrec on the outside.
829 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
830 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000831 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000832
833 // Similar to above, only this time treat the step value as signed.
834 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000835 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000836 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000837 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000838 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000839 OperandExtendedAdd =
840 getAddExpr(getZeroExtendExpr(Start, WideTy),
841 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
842 getSignExtendExpr(Step, WideTy)));
843 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000844 // Return the expression with the addrec on the outside.
845 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
846 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000847 L);
848 }
849
850 // If the backedge is guarded by a comparison with the pre-inc value
851 // the addrec is safe. Also, if the entry is guarded by a comparison
852 // with the start value and the backedge is guarded by a comparison
853 // with the post-inc value, the addrec is safe.
854 if (isKnownPositive(Step)) {
855 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
856 getUnsignedRange(Step).getUnsignedMax());
857 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
858 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
859 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
860 AR->getPostIncExpr(*this), N)))
861 // Return the expression with the addrec on the outside.
862 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
863 getZeroExtendExpr(Step, Ty),
864 L);
865 } else if (isKnownNegative(Step)) {
866 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
867 getSignedRange(Step).getSignedMin());
868 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
869 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
870 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
871 AR->getPostIncExpr(*this), N)))
872 // Return the expression with the addrec on the outside.
873 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
874 getSignExtendExpr(Step, Ty),
875 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000876 }
877 }
878 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000879
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000880 // The cast wasn't folded; create an explicit cast node.
881 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000882 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
883 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000884 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000885 UniqueSCEVs.InsertNode(S, IP);
886 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000887}
888
Dan Gohman0bba49c2009-07-07 17:06:11 +0000889const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000890 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000891 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000892 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000893 assert(isSCEVable(Ty) &&
894 "This is not a conversion to a SCEVable type!");
895 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000896
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000897 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000898 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000899 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000900 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
901 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000902 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000903 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000904
Dan Gohman20900ca2009-04-22 16:20:48 +0000905 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000906 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000907 return getSignExtendExpr(SS->getOperand(), Ty);
908
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000909 // Before doing any expensive analysis, check to see if we've already
910 // computed a SCEV for this Op and Ty.
911 FoldingSetNodeID ID;
912 ID.AddInteger(scSignExtend);
913 ID.AddPointer(Op);
914 ID.AddPointer(Ty);
915 void *IP = 0;
916 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
917
Dan Gohman01ecca22009-04-27 20:16:15 +0000918 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000919 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000920 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000921 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000922 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000923 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000924 const SCEV *Start = AR->getStart();
925 const SCEV *Step = AR->getStepRecurrence(*this);
926 unsigned BitWidth = getTypeSizeInBits(AR->getType());
927 const Loop *L = AR->getLoop();
928
Dan Gohman01ecca22009-04-27 20:16:15 +0000929 // Check whether the backedge-taken count is SCEVCouldNotCompute.
930 // Note that this serves two purposes: It filters out loops that are
931 // simply not analyzable, and it covers the case where this code is
932 // being called from within backedge-taken count analysis, such that
933 // attempting to ask for the backedge-taken count would likely result
934 // in infinite recursion. In the later case, the analysis code will
935 // cope with a conservative value, and it will take care to purge
936 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000937 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000938 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000939 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000940 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000941
942 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000943 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000944 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000945 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000946 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000947 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
948 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000949 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000950 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000951 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000952 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000953 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000954 const SCEV *Add = getAddExpr(Start, SMul);
955 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000956 getAddExpr(getSignExtendExpr(Start, WideTy),
957 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
958 getSignExtendExpr(Step, WideTy)));
959 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000960 // Return the expression with the addrec on the outside.
961 return getAddRecExpr(getSignExtendExpr(Start, Ty),
962 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000963 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000964
965 // Similar to above, only this time treat the step value as unsigned.
966 // This covers loops that count up with an unsigned step.
967 const SCEV *UMul =
968 getMulExpr(CastedMaxBECount,
969 getTruncateOrZeroExtend(Step, Start->getType()));
970 Add = getAddExpr(Start, UMul);
971 OperandExtendedAdd =
972 getAddExpr(getZeroExtendExpr(Start, WideTy),
973 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
974 getZeroExtendExpr(Step, WideTy)));
975 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
976 // Return the expression with the addrec on the outside.
977 return getAddRecExpr(getSignExtendExpr(Start, Ty),
978 getZeroExtendExpr(Step, Ty),
979 L);
Dan Gohman85b05a22009-07-13 21:35:55 +0000980 }
981
982 // If the backedge is guarded by a comparison with the pre-inc value
983 // the addrec is safe. Also, if the entry is guarded by a comparison
984 // with the start value and the backedge is guarded by a comparison
985 // with the post-inc value, the addrec is safe.
986 if (isKnownPositive(Step)) {
987 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
988 getSignedRange(Step).getSignedMax());
989 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
990 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
991 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
992 AR->getPostIncExpr(*this), N)))
993 // Return the expression with the addrec on the outside.
994 return getAddRecExpr(getSignExtendExpr(Start, Ty),
995 getSignExtendExpr(Step, Ty),
996 L);
997 } else if (isKnownNegative(Step)) {
998 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
999 getSignedRange(Step).getSignedMin());
1000 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1001 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1002 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1003 AR->getPostIncExpr(*this), N)))
1004 // Return the expression with the addrec on the outside.
1005 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1006 getSignExtendExpr(Step, Ty),
1007 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001008 }
1009 }
1010 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001011
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001012 // The cast wasn't folded; create an explicit cast node.
1013 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001014 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1015 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001016 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001017 UniqueSCEVs.InsertNode(S, IP);
1018 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001019}
1020
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001021/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1022/// unspecified bits out to the given type.
1023///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001024const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001025 const Type *Ty) {
1026 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1027 "This is not an extending conversion!");
1028 assert(isSCEVable(Ty) &&
1029 "This is not a conversion to a SCEVable type!");
1030 Ty = getEffectiveSCEVType(Ty);
1031
1032 // Sign-extend negative constants.
1033 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1034 if (SC->getValue()->getValue().isNegative())
1035 return getSignExtendExpr(Op, Ty);
1036
1037 // Peel off a truncate cast.
1038 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001039 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001040 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1041 return getAnyExtendExpr(NewOp, Ty);
1042 return getTruncateOrNoop(NewOp, Ty);
1043 }
1044
1045 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001046 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001047 if (!isa<SCEVZeroExtendExpr>(ZExt))
1048 return ZExt;
1049
1050 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001051 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001052 if (!isa<SCEVSignExtendExpr>(SExt))
1053 return SExt;
1054
1055 // If the expression is obviously signed, use the sext cast value.
1056 if (isa<SCEVSMaxExpr>(Op))
1057 return SExt;
1058
1059 // Absent any other information, use the zext cast value.
1060 return ZExt;
1061}
1062
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001063/// CollectAddOperandsWithScales - Process the given Ops list, which is
1064/// a list of operands to be added under the given scale, update the given
1065/// map. This is a helper function for getAddRecExpr. As an example of
1066/// what it does, given a sequence of operands that would form an add
1067/// expression like this:
1068///
1069/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1070///
1071/// where A and B are constants, update the map with these values:
1072///
1073/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1074///
1075/// and add 13 + A*B*29 to AccumulatedConstant.
1076/// This will allow getAddRecExpr to produce this:
1077///
1078/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1079///
1080/// This form often exposes folding opportunities that are hidden in
1081/// the original operand list.
1082///
1083/// Return true iff it appears that any interesting folding opportunities
1084/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1085/// the common case where no interesting opportunities are present, and
1086/// is also used as a check to avoid infinite recursion.
1087///
1088static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001089CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1090 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001091 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001092 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001093 const APInt &Scale,
1094 ScalarEvolution &SE) {
1095 bool Interesting = false;
1096
1097 // Iterate over the add operands.
1098 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1099 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1100 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1101 APInt NewScale =
1102 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1103 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1104 // A multiplication of a constant with another add; recurse.
1105 Interesting |=
1106 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1107 cast<SCEVAddExpr>(Mul->getOperand(1))
1108 ->getOperands(),
1109 NewScale, SE);
1110 } else {
1111 // A multiplication of a constant with some other value. Update
1112 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001113 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1114 const SCEV *Key = SE.getMulExpr(MulOps);
1115 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001116 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001117 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001118 NewOps.push_back(Pair.first->first);
1119 } else {
1120 Pair.first->second += NewScale;
1121 // The map already had an entry for this value, which may indicate
1122 // a folding opportunity.
1123 Interesting = true;
1124 }
1125 }
1126 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1127 // Pull a buried constant out to the outside.
1128 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1129 Interesting = true;
1130 AccumulatedConstant += Scale * C->getValue()->getValue();
1131 } else {
1132 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001133 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001134 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001135 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001136 NewOps.push_back(Pair.first->first);
1137 } else {
1138 Pair.first->second += Scale;
1139 // The map already had an entry for this value, which may indicate
1140 // a folding opportunity.
1141 Interesting = true;
1142 }
1143 }
1144 }
1145
1146 return Interesting;
1147}
1148
1149namespace {
1150 struct APIntCompare {
1151 bool operator()(const APInt &LHS, const APInt &RHS) const {
1152 return LHS.ult(RHS);
1153 }
1154 };
1155}
1156
Dan Gohman6c0866c2009-05-24 23:45:28 +00001157/// getAddExpr - Get a canonical add expression, or something simpler if
1158/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001159const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001160 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001161 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001162#ifndef NDEBUG
1163 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1164 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1165 getEffectiveSCEVType(Ops[0]->getType()) &&
1166 "SCEVAddExpr operand types don't match!");
1167#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001168
1169 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001170 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001171
1172 // If there are any constants, fold them together.
1173 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001174 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001176 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001177 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001178 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001179 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1180 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001181 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001182 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001183 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001184 }
1185
1186 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001187 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001188 Ops.erase(Ops.begin());
1189 --Idx;
1190 }
1191 }
1192
Chris Lattner627018b2004-04-07 16:16:11 +00001193 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001194
Chris Lattner53e677a2004-04-02 20:23:17 +00001195 // Okay, check to see if the same value occurs in the operand list twice. If
1196 // so, merge them together into an multiply expression. Since we sorted the
1197 // list, these values are required to be adjacent.
1198 const Type *Ty = Ops[0]->getType();
1199 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1200 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1201 // Found a match, merge the two values into a multiply, and add any
1202 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001203 const SCEV *Two = getIntegerSCEV(2, Ty);
1204 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001205 if (Ops.size() == 2)
1206 return Mul;
1207 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1208 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001209 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001210 }
1211
Dan Gohman728c7f32009-05-08 21:03:19 +00001212 // Check for truncates. If all the operands are truncated from the same
1213 // type, see if factoring out the truncate would permit the result to be
1214 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1215 // if the contents of the resulting outer trunc fold to something simple.
1216 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1217 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1218 const Type *DstType = Trunc->getType();
1219 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001220 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001221 bool Ok = true;
1222 // Check all the operands to see if they can be represented in the
1223 // source type of the truncate.
1224 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1225 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1226 if (T->getOperand()->getType() != SrcType) {
1227 Ok = false;
1228 break;
1229 }
1230 LargeOps.push_back(T->getOperand());
1231 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1232 // This could be either sign or zero extension, but sign extension
1233 // is much more likely to be foldable here.
1234 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1235 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001236 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001237 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1238 if (const SCEVTruncateExpr *T =
1239 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1240 if (T->getOperand()->getType() != SrcType) {
1241 Ok = false;
1242 break;
1243 }
1244 LargeMulOps.push_back(T->getOperand());
1245 } else if (const SCEVConstant *C =
1246 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1247 // This could be either sign or zero extension, but sign extension
1248 // is much more likely to be foldable here.
1249 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1250 } else {
1251 Ok = false;
1252 break;
1253 }
1254 }
1255 if (Ok)
1256 LargeOps.push_back(getMulExpr(LargeMulOps));
1257 } else {
1258 Ok = false;
1259 break;
1260 }
1261 }
1262 if (Ok) {
1263 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001264 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001265 // If it folds to something simple, use it. Otherwise, don't.
1266 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1267 return getTruncateExpr(Fold, DstType);
1268 }
1269 }
1270
1271 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001272 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1273 ++Idx;
1274
1275 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001276 if (Idx < Ops.size()) {
1277 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001278 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001279 // If we have an add, expand the add operands onto the end of the operands
1280 // list.
1281 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1282 Ops.erase(Ops.begin()+Idx);
1283 DeletedAdd = true;
1284 }
1285
1286 // If we deleted at least one add, we added operands to the end of the list,
1287 // and they are not necessarily sorted. Recurse to resort and resimplify
1288 // any operands we just aquired.
1289 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001290 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001291 }
1292
1293 // Skip over the add expression until we get to a multiply.
1294 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1295 ++Idx;
1296
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001297 // Check to see if there are any folding opportunities present with
1298 // operands multiplied by constant values.
1299 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1300 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001301 DenseMap<const SCEV *, APInt> M;
1302 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001303 APInt AccumulatedConstant(BitWidth, 0);
1304 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1305 Ops, APInt(BitWidth, 1), *this)) {
1306 // Some interesting folding opportunity is present, so its worthwhile to
1307 // re-generate the operands list. Group the operands by constant scale,
1308 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001309 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1310 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001311 E = NewOps.end(); I != E; ++I)
1312 MulOpLists[M.find(*I)->second].push_back(*I);
1313 // Re-generate the operands list.
1314 Ops.clear();
1315 if (AccumulatedConstant != 0)
1316 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001317 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1318 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001319 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001320 Ops.push_back(getMulExpr(getConstant(I->first),
1321 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001322 if (Ops.empty())
1323 return getIntegerSCEV(0, Ty);
1324 if (Ops.size() == 1)
1325 return Ops[0];
1326 return getAddExpr(Ops);
1327 }
1328 }
1329
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 // If we are adding something to a multiply expression, make sure the
1331 // something is not already an operand of the multiply. If so, merge it into
1332 // the multiply.
1333 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001334 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001336 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001337 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001338 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001339 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001340 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001341 if (Mul->getNumOperands() != 2) {
1342 // If the multiply has more than two operands, we must get the
1343 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001344 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001345 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001346 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001347 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001348 const SCEV *One = getIntegerSCEV(1, Ty);
1349 const SCEV *AddOne = getAddExpr(InnerMul, One);
1350 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001351 if (Ops.size() == 2) return OuterMul;
1352 if (AddOp < Idx) {
1353 Ops.erase(Ops.begin()+AddOp);
1354 Ops.erase(Ops.begin()+Idx-1);
1355 } else {
1356 Ops.erase(Ops.begin()+Idx);
1357 Ops.erase(Ops.begin()+AddOp-1);
1358 }
1359 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001360 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001361 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001362
Chris Lattner53e677a2004-04-02 20:23:17 +00001363 // Check this multiply against other multiplies being added together.
1364 for (unsigned OtherMulIdx = Idx+1;
1365 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1366 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001367 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001368 // If MulOp occurs in OtherMul, we can fold the two multiplies
1369 // together.
1370 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1371 OMulOp != e; ++OMulOp)
1372 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1373 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001374 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001375 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001376 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1377 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001379 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001380 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001381 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001383 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1384 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001385 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001386 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001387 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001388 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1389 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001390 if (Ops.size() == 2) return OuterMul;
1391 Ops.erase(Ops.begin()+Idx);
1392 Ops.erase(Ops.begin()+OtherMulIdx-1);
1393 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001394 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 }
1396 }
1397 }
1398 }
1399
1400 // If there are any add recurrences in the operands list, see if any other
1401 // added values are loop invariant. If so, we can fold them into the
1402 // recurrence.
1403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1404 ++Idx;
1405
1406 // Scan over all recurrences, trying to fold loop invariants into them.
1407 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1408 // Scan all of the other operands to this add and add them to the vector if
1409 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001410 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001411 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001412 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1413 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1414 LIOps.push_back(Ops[i]);
1415 Ops.erase(Ops.begin()+i);
1416 --i; --e;
1417 }
1418
1419 // If we found some loop invariants, fold them into the recurrence.
1420 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001421 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001422 LIOps.push_back(AddRec->getStart());
1423
Dan Gohman0bba49c2009-07-07 17:06:11 +00001424 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001425 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001426 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001427
Dan Gohman0bba49c2009-07-07 17:06:11 +00001428 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001429 // If all of the other operands were loop invariant, we are done.
1430 if (Ops.size() == 1) return NewRec;
1431
1432 // Otherwise, add the folded AddRec by the non-liv parts.
1433 for (unsigned i = 0;; ++i)
1434 if (Ops[i] == AddRec) {
1435 Ops[i] = NewRec;
1436 break;
1437 }
Dan Gohman246b2562007-10-22 18:31:58 +00001438 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001439 }
1440
1441 // Okay, if there weren't any loop invariants to be folded, check to see if
1442 // there are multiple AddRec's with the same loop induction variable being
1443 // added together. If so, we can fold them.
1444 for (unsigned OtherIdx = Idx+1;
1445 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1446 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001447 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001448 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1449 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001450 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1451 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001452 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1453 if (i >= NewOps.size()) {
1454 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1455 OtherAddRec->op_end());
1456 break;
1457 }
Dan Gohman246b2562007-10-22 18:31:58 +00001458 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001459 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001460 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001461
1462 if (Ops.size() == 2) return NewAddRec;
1463
1464 Ops.erase(Ops.begin()+Idx);
1465 Ops.erase(Ops.begin()+OtherIdx-1);
1466 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001467 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 }
1469 }
1470
1471 // Otherwise couldn't fold anything into this recurrence. Move onto the
1472 // next one.
1473 }
1474
1475 // Okay, it looks like we really DO need an add expr. Check to see if we
1476 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001477 FoldingSetNodeID ID;
1478 ID.AddInteger(scAddExpr);
1479 ID.AddInteger(Ops.size());
1480 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1481 ID.AddPointer(Ops[i]);
1482 void *IP = 0;
1483 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1484 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001485 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001486 UniqueSCEVs.InsertNode(S, IP);
1487 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001488}
1489
1490
Dan Gohman6c0866c2009-05-24 23:45:28 +00001491/// getMulExpr - Get a canonical multiply expression, or something simpler if
1492/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001493const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001495#ifndef NDEBUG
1496 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1497 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1498 getEffectiveSCEVType(Ops[0]->getType()) &&
1499 "SCEVMulExpr operand types don't match!");
1500#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001501
1502 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001503 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504
1505 // If there are any constants, fold them together.
1506 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001507 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001508
1509 // C1*(C2+V) -> C1*C2 + C1*V
1510 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001511 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001512 if (Add->getNumOperands() == 2 &&
1513 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001514 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1515 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001516
1517
1518 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001519 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 // We found two constants, fold them together!
Owen Andersone922c022009-07-22 00:24:57 +00001521 ConstantInt *Fold = getContext().getConstantInt(LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001522 RHSC->getValue()->getValue());
1523 Ops[0] = getConstant(Fold);
1524 Ops.erase(Ops.begin()+1); // Erase the folded element
1525 if (Ops.size() == 1) return Ops[0];
1526 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001527 }
1528
1529 // If we are left with a constant one being multiplied, strip it off.
1530 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1531 Ops.erase(Ops.begin());
1532 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001533 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001534 // If we have a multiply of zero, it will always be zero.
1535 return Ops[0];
1536 }
1537 }
1538
1539 // Skip over the add expression until we get to a multiply.
1540 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1541 ++Idx;
1542
1543 if (Ops.size() == 1)
1544 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001545
Chris Lattner53e677a2004-04-02 20:23:17 +00001546 // If there are mul operands inline them all into this expression.
1547 if (Idx < Ops.size()) {
1548 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001549 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 // If we have an mul, expand the mul operands onto the end of the operands
1551 // list.
1552 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1553 Ops.erase(Ops.begin()+Idx);
1554 DeletedMul = true;
1555 }
1556
1557 // If we deleted at least one mul, we added operands to the end of the list,
1558 // and they are not necessarily sorted. Recurse to resort and resimplify
1559 // any operands we just aquired.
1560 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001561 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001562 }
1563
1564 // If there are any add recurrences in the operands list, see if any other
1565 // added values are loop invariant. If so, we can fold them into the
1566 // recurrence.
1567 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1568 ++Idx;
1569
1570 // Scan over all recurrences, trying to fold loop invariants into them.
1571 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1572 // Scan all of the other operands to this mul and add them to the vector if
1573 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001574 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001575 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001576 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1577 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1578 LIOps.push_back(Ops[i]);
1579 Ops.erase(Ops.begin()+i);
1580 --i; --e;
1581 }
1582
1583 // If we found some loop invariants, fold them into the recurrence.
1584 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001585 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001586 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 NewOps.reserve(AddRec->getNumOperands());
1588 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001589 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001591 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001592 } else {
1593 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001594 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001596 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 }
1598 }
1599
Dan Gohman0bba49c2009-07-07 17:06:11 +00001600 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001601
1602 // If all of the other operands were loop invariant, we are done.
1603 if (Ops.size() == 1) return NewRec;
1604
1605 // Otherwise, multiply the folded AddRec by the non-liv parts.
1606 for (unsigned i = 0;; ++i)
1607 if (Ops[i] == AddRec) {
1608 Ops[i] = NewRec;
1609 break;
1610 }
Dan Gohman246b2562007-10-22 18:31:58 +00001611 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001612 }
1613
1614 // Okay, if there weren't any loop invariants to be folded, check to see if
1615 // there are multiple AddRec's with the same loop induction variable being
1616 // multiplied together. If so, we can fold them.
1617 for (unsigned OtherIdx = Idx+1;
1618 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1619 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001620 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001621 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1622 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001623 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001624 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001625 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001626 const SCEV *B = F->getStepRecurrence(*this);
1627 const SCEV *D = G->getStepRecurrence(*this);
1628 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001629 getMulExpr(G, B),
1630 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001631 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001632 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001633 if (Ops.size() == 2) return NewAddRec;
1634
1635 Ops.erase(Ops.begin()+Idx);
1636 Ops.erase(Ops.begin()+OtherIdx-1);
1637 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001638 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001639 }
1640 }
1641
1642 // Otherwise couldn't fold anything into this recurrence. Move onto the
1643 // next one.
1644 }
1645
1646 // Okay, it looks like we really DO need an mul expr. Check to see if we
1647 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001648 FoldingSetNodeID ID;
1649 ID.AddInteger(scMulExpr);
1650 ID.AddInteger(Ops.size());
1651 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1652 ID.AddPointer(Ops[i]);
1653 void *IP = 0;
1654 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1655 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001656 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001657 UniqueSCEVs.InsertNode(S, IP);
1658 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001659}
1660
Dan Gohman6c0866c2009-05-24 23:45:28 +00001661/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1662/// possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001663const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1664 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001665 assert(getEffectiveSCEVType(LHS->getType()) ==
1666 getEffectiveSCEVType(RHS->getType()) &&
1667 "SCEVUDivExpr operand types don't match!");
1668
Dan Gohman622ed672009-05-04 22:02:23 +00001669 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001670 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001671 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001672 if (RHSC->isZero())
1673 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001674
Dan Gohman185cf032009-05-08 20:18:49 +00001675 // Determine if the division can be folded into the operands of
1676 // its operands.
1677 // TODO: Generalize this to non-constants by using known-bits information.
1678 const Type *Ty = LHS->getType();
1679 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1680 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1681 // For non-power-of-two values, effectively round the value up to the
1682 // nearest power of two.
1683 if (!RHSC->getValue()->getValue().isPowerOf2())
1684 ++MaxShiftAmt;
1685 const IntegerType *ExtTy =
1686 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1687 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1688 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1689 if (const SCEVConstant *Step =
1690 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1691 if (!Step->getValue()->getValue()
1692 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001693 getZeroExtendExpr(AR, ExtTy) ==
1694 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1695 getZeroExtendExpr(Step, ExtTy),
1696 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001697 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001698 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1699 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1700 return getAddRecExpr(Operands, AR->getLoop());
1701 }
1702 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001703 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001704 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001705 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1706 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1707 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001708 // Find an operand that's safely divisible.
1709 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001710 const SCEV *Op = M->getOperand(i);
1711 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001712 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001713 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1714 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001715 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001716 Operands[i] = Div;
1717 return getMulExpr(Operands);
1718 }
1719 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001720 }
Dan Gohman185cf032009-05-08 20:18:49 +00001721 // (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 +00001722 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001723 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001724 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1725 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1726 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1727 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001728 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001729 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001730 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1731 break;
1732 Operands.push_back(Op);
1733 }
1734 if (Operands.size() == A->getNumOperands())
1735 return getAddExpr(Operands);
1736 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001737 }
Dan Gohman185cf032009-05-08 20:18:49 +00001738
1739 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001740 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001741 Constant *LHSCV = LHSC->getValue();
1742 Constant *RHSCV = RHSC->getValue();
Owen Andersone922c022009-07-22 00:24:57 +00001743 return getConstant(cast<ConstantInt>(getContext().getConstantExprUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001744 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 }
1746 }
1747
Dan Gohman1c343752009-06-27 21:21:31 +00001748 FoldingSetNodeID ID;
1749 ID.AddInteger(scUDivExpr);
1750 ID.AddPointer(LHS);
1751 ID.AddPointer(RHS);
1752 void *IP = 0;
1753 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1754 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001755 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001756 UniqueSCEVs.InsertNode(S, IP);
1757 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001758}
1759
1760
Dan Gohman6c0866c2009-05-24 23:45:28 +00001761/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1762/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001763const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1764 const SCEV *Step, const Loop *L) {
1765 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001766 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001767 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001768 if (StepChrec->getLoop() == L) {
1769 Operands.insert(Operands.end(), StepChrec->op_begin(),
1770 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001771 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001772 }
1773
1774 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001775 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001776}
1777
Dan Gohman6c0866c2009-05-24 23:45:28 +00001778/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1779/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001780const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001781ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001782 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001783 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001784#ifndef NDEBUG
1785 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1786 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1787 getEffectiveSCEVType(Operands[0]->getType()) &&
1788 "SCEVAddRecExpr operand types don't match!");
1789#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001790
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001791 if (Operands.back()->isZero()) {
1792 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001793 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001794 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001795
Dan Gohmand9cc7492008-08-08 18:33:12 +00001796 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001797 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001798 const Loop* NestedLoop = NestedAR->getLoop();
1799 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001800 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001801 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001802 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001803 // AddRecs require their operands be loop-invariant with respect to their
1804 // loops. Don't perform this transformation if it would break this
1805 // requirement.
1806 bool AllInvariant = true;
1807 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1808 if (!Operands[i]->isLoopInvariant(L)) {
1809 AllInvariant = false;
1810 break;
1811 }
1812 if (AllInvariant) {
1813 NestedOperands[0] = getAddRecExpr(Operands, L);
1814 AllInvariant = true;
1815 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1816 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1817 AllInvariant = false;
1818 break;
1819 }
1820 if (AllInvariant)
1821 // Ok, both add recurrences are valid after the transformation.
1822 return getAddRecExpr(NestedOperands, NestedLoop);
1823 }
1824 // Reset Operands to its original state.
1825 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001826 }
1827 }
1828
Dan Gohman1c343752009-06-27 21:21:31 +00001829 FoldingSetNodeID ID;
1830 ID.AddInteger(scAddRecExpr);
1831 ID.AddInteger(Operands.size());
1832 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1833 ID.AddPointer(Operands[i]);
1834 ID.AddPointer(L);
1835 void *IP = 0;
1836 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1837 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001838 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001839 UniqueSCEVs.InsertNode(S, IP);
1840 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001841}
1842
Dan Gohman9311ef62009-06-24 14:49:00 +00001843const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1844 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001845 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001846 Ops.push_back(LHS);
1847 Ops.push_back(RHS);
1848 return getSMaxExpr(Ops);
1849}
1850
Dan Gohman0bba49c2009-07-07 17:06:11 +00001851const SCEV *
1852ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001853 assert(!Ops.empty() && "Cannot get empty smax!");
1854 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001855#ifndef NDEBUG
1856 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1857 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1858 getEffectiveSCEVType(Ops[0]->getType()) &&
1859 "SCEVSMaxExpr operand types don't match!");
1860#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001861
1862 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001863 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001864
1865 // If there are any constants, fold them together.
1866 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001867 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001868 ++Idx;
1869 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001870 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001871 // We found two constants, fold them together!
Owen Andersone922c022009-07-22 00:24:57 +00001872 ConstantInt *Fold = getContext().getConstantInt(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001873 APIntOps::smax(LHSC->getValue()->getValue(),
1874 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001875 Ops[0] = getConstant(Fold);
1876 Ops.erase(Ops.begin()+1); // Erase the folded element
1877 if (Ops.size() == 1) return Ops[0];
1878 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001879 }
1880
Dan Gohmane5aceed2009-06-24 14:46:22 +00001881 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001882 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1883 Ops.erase(Ops.begin());
1884 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001885 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1886 // If we have an smax with a constant maximum-int, it will always be
1887 // maximum-int.
1888 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001889 }
1890 }
1891
1892 if (Ops.size() == 1) return Ops[0];
1893
1894 // Find the first SMax
1895 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1896 ++Idx;
1897
1898 // Check to see if one of the operands is an SMax. If so, expand its operands
1899 // onto our operand list, and recurse to simplify.
1900 if (Idx < Ops.size()) {
1901 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001902 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001903 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1904 Ops.erase(Ops.begin()+Idx);
1905 DeletedSMax = true;
1906 }
1907
1908 if (DeletedSMax)
1909 return getSMaxExpr(Ops);
1910 }
1911
1912 // Okay, check to see if the same value occurs in the operand list twice. If
1913 // so, delete one. Since we sorted the list, these values are required to
1914 // be adjacent.
1915 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1916 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1917 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1918 --i; --e;
1919 }
1920
1921 if (Ops.size() == 1) return Ops[0];
1922
1923 assert(!Ops.empty() && "Reduced smax down to nothing!");
1924
Nick Lewycky3e630762008-02-20 06:48:22 +00001925 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001926 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001927 FoldingSetNodeID ID;
1928 ID.AddInteger(scSMaxExpr);
1929 ID.AddInteger(Ops.size());
1930 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1931 ID.AddPointer(Ops[i]);
1932 void *IP = 0;
1933 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1934 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001935 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001936 UniqueSCEVs.InsertNode(S, IP);
1937 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001938}
1939
Dan Gohman9311ef62009-06-24 14:49:00 +00001940const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1941 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001942 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001943 Ops.push_back(LHS);
1944 Ops.push_back(RHS);
1945 return getUMaxExpr(Ops);
1946}
1947
Dan Gohman0bba49c2009-07-07 17:06:11 +00001948const SCEV *
1949ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001950 assert(!Ops.empty() && "Cannot get empty umax!");
1951 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001952#ifndef NDEBUG
1953 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1954 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1955 getEffectiveSCEVType(Ops[0]->getType()) &&
1956 "SCEVUMaxExpr operand types don't match!");
1957#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001958
1959 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001960 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001961
1962 // If there are any constants, fold them together.
1963 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001964 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001965 ++Idx;
1966 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001967 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001968 // We found two constants, fold them together!
Owen Andersone922c022009-07-22 00:24:57 +00001969 ConstantInt *Fold = getContext().getConstantInt(
Nick Lewycky3e630762008-02-20 06:48:22 +00001970 APIntOps::umax(LHSC->getValue()->getValue(),
1971 RHSC->getValue()->getValue()));
1972 Ops[0] = getConstant(Fold);
1973 Ops.erase(Ops.begin()+1); // Erase the folded element
1974 if (Ops.size() == 1) return Ops[0];
1975 LHSC = cast<SCEVConstant>(Ops[0]);
1976 }
1977
Dan Gohmane5aceed2009-06-24 14:46:22 +00001978 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001979 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1980 Ops.erase(Ops.begin());
1981 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001982 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1983 // If we have an umax with a constant maximum-int, it will always be
1984 // maximum-int.
1985 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001986 }
1987 }
1988
1989 if (Ops.size() == 1) return Ops[0];
1990
1991 // Find the first UMax
1992 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1993 ++Idx;
1994
1995 // Check to see if one of the operands is a UMax. If so, expand its operands
1996 // onto our operand list, and recurse to simplify.
1997 if (Idx < Ops.size()) {
1998 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001999 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002000 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2001 Ops.erase(Ops.begin()+Idx);
2002 DeletedUMax = true;
2003 }
2004
2005 if (DeletedUMax)
2006 return getUMaxExpr(Ops);
2007 }
2008
2009 // Okay, check to see if the same value occurs in the operand list twice. If
2010 // so, delete one. Since we sorted the list, these values are required to
2011 // be adjacent.
2012 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2013 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2014 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2015 --i; --e;
2016 }
2017
2018 if (Ops.size() == 1) return Ops[0];
2019
2020 assert(!Ops.empty() && "Reduced umax down to nothing!");
2021
2022 // Okay, it looks like we really DO need a umax expr. Check to see if we
2023 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002024 FoldingSetNodeID ID;
2025 ID.AddInteger(scUMaxExpr);
2026 ID.AddInteger(Ops.size());
2027 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2028 ID.AddPointer(Ops[i]);
2029 void *IP = 0;
2030 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2031 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002032 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002033 UniqueSCEVs.InsertNode(S, IP);
2034 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002035}
2036
Dan Gohman9311ef62009-06-24 14:49:00 +00002037const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2038 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002039 // ~smax(~x, ~y) == smin(x, y).
2040 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2041}
2042
Dan Gohman9311ef62009-06-24 14:49:00 +00002043const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2044 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002045 // ~umax(~x, ~y) == umin(x, y)
2046 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2047}
2048
Dan Gohman0bba49c2009-07-07 17:06:11 +00002049const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002050 // Don't attempt to do anything other than create a SCEVUnknown object
2051 // here. createSCEV only calls getUnknown after checking for all other
2052 // interesting possibilities, and any other code that calls getUnknown
2053 // is doing so in order to hide a value from SCEV canonicalization.
2054
Dan Gohman1c343752009-06-27 21:21:31 +00002055 FoldingSetNodeID ID;
2056 ID.AddInteger(scUnknown);
2057 ID.AddPointer(V);
2058 void *IP = 0;
2059 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2060 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002061 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002062 UniqueSCEVs.InsertNode(S, IP);
2063 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002064}
2065
Chris Lattner53e677a2004-04-02 20:23:17 +00002066//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002067// Basic SCEV Analysis and PHI Idiom Recognition Code
2068//
2069
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002070/// isSCEVable - Test if values of the given type are analyzable within
2071/// the SCEV framework. This primarily includes integer types, and it
2072/// can optionally include pointer types if the ScalarEvolution class
2073/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002074bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002075 // Integers are always SCEVable.
2076 if (Ty->isInteger())
2077 return true;
2078
2079 // Pointers are SCEVable if TargetData information is available
2080 // to provide pointer size information.
2081 if (isa<PointerType>(Ty))
2082 return TD != NULL;
2083
2084 // Otherwise it's not SCEVable.
2085 return false;
2086}
2087
2088/// getTypeSizeInBits - Return the size in bits of the specified type,
2089/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002090uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002091 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2092
2093 // If we have a TargetData, use it!
2094 if (TD)
2095 return TD->getTypeSizeInBits(Ty);
2096
2097 // Otherwise, we support only integer types.
2098 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2099 return Ty->getPrimitiveSizeInBits();
2100}
2101
2102/// getEffectiveSCEVType - Return a type with the same bitwidth as
2103/// the given type and which represents how SCEV will treat the given
2104/// type, for which isSCEVable must return true. For pointer types,
2105/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002106const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002107 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2108
2109 if (Ty->isInteger())
2110 return Ty;
2111
2112 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2113 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002114}
Chris Lattner53e677a2004-04-02 20:23:17 +00002115
Dan Gohman0bba49c2009-07-07 17:06:11 +00002116const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002117 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002118}
2119
Chris Lattner53e677a2004-04-02 20:23:17 +00002120/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2121/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002122const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002123 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002124
Dan Gohman0bba49c2009-07-07 17:06:11 +00002125 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002126 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002127 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002128 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002129 return S;
2130}
2131
Dan Gohman6bbcba12009-06-24 00:54:57 +00002132/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002133/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002134const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002135 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersone922c022009-07-22 00:24:57 +00002136 return getConstant(getContext().getConstantInt(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002137}
2138
2139/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2140///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002141const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002142 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002143 return getConstant(
Owen Andersone922c022009-07-22 00:24:57 +00002144 cast<ConstantInt>(getContext().getConstantExprNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002145
2146 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002147 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002148 return getMulExpr(V,
Owen Andersone922c022009-07-22 00:24:57 +00002149 getConstant(cast<ConstantInt>(getContext().getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002150}
2151
2152/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002153const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002154 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002155 return getConstant(
Owen Andersone922c022009-07-22 00:24:57 +00002156 cast<ConstantInt>(getContext().getConstantExprNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002157
2158 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002159 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002160 const SCEV *AllOnes =
Owen Andersone922c022009-07-22 00:24:57 +00002161 getConstant(cast<ConstantInt>(getContext().getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002162 return getMinusSCEV(AllOnes, V);
2163}
2164
2165/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2166///
Dan Gohman9311ef62009-06-24 14:49:00 +00002167const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2168 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002169 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002170 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002171}
2172
2173/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2174/// input value to the specified type. If the type must be extended, it is zero
2175/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002176const SCEV *
2177ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002178 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002179 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002180 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2181 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002182 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002183 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002184 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002185 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002186 return getTruncateExpr(V, Ty);
2187 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002188}
2189
2190/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2191/// input value to the specified type. If the type must be extended, it is sign
2192/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002193const SCEV *
2194ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002195 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002196 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002197 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2198 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002199 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002200 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002201 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002202 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002203 return getTruncateExpr(V, Ty);
2204 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002205}
2206
Dan Gohman467c4302009-05-13 03:46:30 +00002207/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2208/// input value to the specified type. If the type must be extended, it is zero
2209/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002210const SCEV *
2211ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002212 const Type *SrcTy = V->getType();
2213 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2214 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2215 "Cannot noop or zero extend with non-integer arguments!");
2216 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2217 "getNoopOrZeroExtend cannot truncate!");
2218 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2219 return V; // No conversion
2220 return getZeroExtendExpr(V, Ty);
2221}
2222
2223/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2224/// input value to the specified type. If the type must be extended, it is sign
2225/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002226const SCEV *
2227ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002228 const Type *SrcTy = V->getType();
2229 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2230 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2231 "Cannot noop or sign extend with non-integer arguments!");
2232 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2233 "getNoopOrSignExtend cannot truncate!");
2234 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2235 return V; // No conversion
2236 return getSignExtendExpr(V, Ty);
2237}
2238
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002239/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2240/// the input value to the specified type. If the type must be extended,
2241/// it is extended with unspecified bits. The conversion must not be
2242/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002243const SCEV *
2244ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002245 const Type *SrcTy = V->getType();
2246 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2247 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2248 "Cannot noop or any extend with non-integer arguments!");
2249 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2250 "getNoopOrAnyExtend cannot truncate!");
2251 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2252 return V; // No conversion
2253 return getAnyExtendExpr(V, Ty);
2254}
2255
Dan Gohman467c4302009-05-13 03:46:30 +00002256/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2257/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002258const SCEV *
2259ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002260 const Type *SrcTy = V->getType();
2261 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2262 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2263 "Cannot truncate or noop with non-integer arguments!");
2264 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2265 "getTruncateOrNoop cannot extend!");
2266 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2267 return V; // No conversion
2268 return getTruncateExpr(V, Ty);
2269}
2270
Dan Gohmana334aa72009-06-22 00:31:57 +00002271/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2272/// the types using zero-extension, and then perform a umax operation
2273/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002274const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2275 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002276 const SCEV *PromotedLHS = LHS;
2277 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002278
2279 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2280 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2281 else
2282 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2283
2284 return getUMaxExpr(PromotedLHS, PromotedRHS);
2285}
2286
Dan Gohmanc9759e82009-06-22 15:03:27 +00002287/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2288/// the types using zero-extension, and then perform a umin operation
2289/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002290const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2291 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002292 const SCEV *PromotedLHS = LHS;
2293 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002294
2295 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2296 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2297 else
2298 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2299
2300 return getUMinExpr(PromotedLHS, PromotedRHS);
2301}
2302
Chris Lattner4dc534c2005-02-13 04:37:18 +00002303/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2304/// the specified instruction and replaces any references to the symbolic value
2305/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002306void
2307ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2308 const SCEV *SymName,
2309 const SCEV *NewVal) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002310 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002311 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002312 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002313
Dan Gohman0bba49c2009-07-07 17:06:11 +00002314 const SCEV *NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002315 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002316 if (NV == SI->second) return; // No change.
2317
2318 SI->second = NV; // Update the scalars map!
2319
2320 // Any instruction values that use this instruction might also need to be
2321 // updated!
2322 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2323 UI != E; ++UI)
2324 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2325}
Chris Lattner53e677a2004-04-02 20:23:17 +00002326
2327/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2328/// a loop header, making it a potential recurrence, or it doesn't.
2329///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002330const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002331 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002332 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002333 if (L->getHeader() == PN->getParent()) {
2334 // If it lives in the loop header, it has two incoming values, one
2335 // from outside the loop, and one from inside.
2336 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2337 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002338
Chris Lattner53e677a2004-04-02 20:23:17 +00002339 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002340 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002341 assert(Scalars.find(PN) == Scalars.end() &&
2342 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002343 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002344
2345 // Using this symbolic name for the PHI, analyze the value coming around
2346 // the back-edge.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002347 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002348
2349 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2350 // has a special value for the first iteration of the loop.
2351
2352 // If the value coming around the backedge is an add with the symbolic
2353 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002354 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002355 // If there is a single occurrence of the symbolic value, replace it
2356 // with a recurrence.
2357 unsigned FoundIndex = Add->getNumOperands();
2358 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2359 if (Add->getOperand(i) == SymbolicName)
2360 if (FoundIndex == e) {
2361 FoundIndex = i;
2362 break;
2363 }
2364
2365 if (FoundIndex != Add->getNumOperands()) {
2366 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002367 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002368 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2369 if (i != FoundIndex)
2370 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002371 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002372
2373 // This is not a valid addrec if the step amount is varying each
2374 // loop iteration, but is not itself an addrec in this loop.
2375 if (Accum->isLoopInvariant(L) ||
2376 (isa<SCEVAddRecExpr>(Accum) &&
2377 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002378 const SCEV *StartVal =
2379 getSCEV(PN->getIncomingValue(IncomingEdge));
2380 const SCEV *PHISCEV =
2381 getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002382
2383 // Okay, for the entire analysis of this edge we assumed the PHI
2384 // to be symbolic. We now need to go back and update all of the
2385 // entries for the scalars that use the PHI (except for the PHI
2386 // itself) to use the new analyzed value instead of the "symbolic"
2387 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002388 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002389 return PHISCEV;
2390 }
2391 }
Dan Gohman622ed672009-05-04 22:02:23 +00002392 } else if (const SCEVAddRecExpr *AddRec =
2393 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002394 // Otherwise, this could be a loop like this:
2395 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2396 // In this case, j = {1,+,1} and BEValue is j.
2397 // Because the other in-value of i (0) fits the evolution of BEValue
2398 // i really is an addrec evolution.
2399 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002400 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002401
2402 // If StartVal = j.start - j.stride, we can use StartVal as the
2403 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002404 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002405 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002406 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002407 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002408
2409 // Okay, for the entire analysis of this edge we assumed the PHI
2410 // to be symbolic. We now need to go back and update all of the
2411 // entries for the scalars that use the PHI (except for the PHI
2412 // itself) to use the new analyzed value instead of the "symbolic"
2413 // value.
2414 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2415 return PHISCEV;
2416 }
2417 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002418 }
2419
2420 return SymbolicName;
2421 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002422
Dan Gohmana653fc52009-07-14 14:06:25 +00002423 // It's tempting to recognize PHIs with a unique incoming value, however
2424 // this leads passes like indvars to break LCSSA form. Fortunately, such
2425 // PHIs are rare, as instcombine zaps them.
2426
Chris Lattner53e677a2004-04-02 20:23:17 +00002427 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002428 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002429}
2430
Dan Gohman26466c02009-05-08 20:26:55 +00002431/// createNodeForGEP - Expand GEP instructions into add and multiply
2432/// operations. This allows them to be analyzed by regular SCEV code.
2433///
Dan Gohmanca178902009-07-17 20:47:02 +00002434const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002435
2436 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002437 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002438 // Don't attempt to analyze GEPs over unsized objects.
2439 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2440 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002441 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002442 gep_type_iterator GTI = gep_type_begin(GEP);
2443 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2444 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002445 I != E; ++I) {
2446 Value *Index = *I;
2447 // Compute the (potentially symbolic) offset in bytes for this index.
2448 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2449 // For a struct, add the member offset.
2450 const StructLayout &SL = *TD->getStructLayout(STy);
2451 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2452 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman85b05a22009-07-13 21:35:55 +00002453 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002454 } else {
2455 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002456 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002457 if (!isa<PointerType>(LocalOffset->getType()))
2458 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002459 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman26466c02009-05-08 20:26:55 +00002460 LocalOffset =
2461 getMulExpr(LocalOffset,
Dan Gohman85b05a22009-07-13 21:35:55 +00002462 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002463 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2464 }
2465 }
2466 return getAddExpr(getSCEV(Base), TotalOffset);
2467}
2468
Nick Lewycky83bb0052007-11-22 07:59:40 +00002469/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2470/// guaranteed to end in (at every loop iteration). It is, at the same time,
2471/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2472/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002473uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002474ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002475 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002476 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002477
Dan Gohman622ed672009-05-04 22:02:23 +00002478 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002479 return std::min(GetMinTrailingZeros(T->getOperand()),
2480 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002481
Dan Gohman622ed672009-05-04 22:02:23 +00002482 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002483 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2484 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2485 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002486 }
2487
Dan Gohman622ed672009-05-04 22:02:23 +00002488 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002489 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2490 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2491 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002492 }
2493
Dan Gohman622ed672009-05-04 22:02:23 +00002494 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002495 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002496 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002497 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002499 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002500 }
2501
Dan Gohman622ed672009-05-04 22:02:23 +00002502 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002503 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002504 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2505 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002506 for (unsigned i = 1, e = M->getNumOperands();
2507 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002508 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002509 BitWidth);
2510 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002511 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002512
Dan Gohman622ed672009-05-04 22:02:23 +00002513 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002514 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002515 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002516 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002517 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002518 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002519 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002520
Dan Gohman622ed672009-05-04 22:02:23 +00002521 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002522 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002523 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002524 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002525 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002526 return MinOpRes;
2527 }
2528
Dan Gohman622ed672009-05-04 22:02:23 +00002529 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002530 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002531 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002532 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002533 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002534 return MinOpRes;
2535 }
2536
Dan Gohman2c364ad2009-06-19 23:29:04 +00002537 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2538 // For a SCEVUnknown, ask ValueTracking.
2539 unsigned BitWidth = getTypeSizeInBits(U->getType());
2540 APInt Mask = APInt::getAllOnesValue(BitWidth);
2541 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2542 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2543 return Zeros.countTrailingOnes();
2544 }
2545
2546 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002547 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002548}
Chris Lattner53e677a2004-04-02 20:23:17 +00002549
Dan Gohman85b05a22009-07-13 21:35:55 +00002550/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2551///
2552ConstantRange
2553ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002554
2555 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002556 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002557
Dan Gohman85b05a22009-07-13 21:35:55 +00002558 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2559 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2560 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2561 X = X.add(getUnsignedRange(Add->getOperand(i)));
2562 return X;
2563 }
2564
2565 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2566 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2567 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2568 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2569 return X;
2570 }
2571
2572 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2573 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2574 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2575 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2576 return X;
2577 }
2578
2579 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2580 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2581 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2582 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2583 return X;
2584 }
2585
2586 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2587 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2588 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2589 return X.udiv(Y);
2590 }
2591
2592 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2593 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2594 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2595 }
2596
2597 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2598 ConstantRange X = getUnsignedRange(SExt->getOperand());
2599 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2600 }
2601
2602 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2603 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2604 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2605 }
2606
2607 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2608
2609 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2610 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2611 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2612 if (!Trip) return FullSet;
2613
2614 // TODO: non-affine addrec
2615 if (AddRec->isAffine()) {
2616 const Type *Ty = AddRec->getType();
2617 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2618 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2619 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2620
2621 const SCEV *Start = AddRec->getStart();
Dan Gohmana16b5762009-07-21 00:42:47 +00002622 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002623 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2624
2625 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002626 // TODO: This is very conservative.
2627 if (!(Step->isOne() &&
2628 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2629 !(Step->isAllOnesValue() &&
2630 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
Dan Gohman85b05a22009-07-13 21:35:55 +00002631 return FullSet;
2632
2633 ConstantRange StartRange = getUnsignedRange(Start);
2634 ConstantRange EndRange = getUnsignedRange(End);
2635 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2636 EndRange.getUnsignedMin());
2637 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2638 EndRange.getUnsignedMax());
2639 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman0d5bae42009-07-20 22:41:51 +00002640 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002641 return ConstantRange(Min, Max+1);
2642 }
2643 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002644 }
2645
2646 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2647 // For a SCEVUnknown, ask ValueTracking.
2648 unsigned BitWidth = getTypeSizeInBits(U->getType());
2649 APInt Mask = APInt::getAllOnesValue(BitWidth);
2650 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2651 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002652 if (Ones == ~Zeros + 1)
2653 return FullSet;
2654 return ConstantRange(Ones, ~Zeros + 1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002655 }
2656
Dan Gohman85b05a22009-07-13 21:35:55 +00002657 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002658}
2659
Dan Gohman85b05a22009-07-13 21:35:55 +00002660/// getSignedRange - Determine the signed range for a particular SCEV.
2661///
2662ConstantRange
2663ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002664
Dan Gohman85b05a22009-07-13 21:35:55 +00002665 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2666 return ConstantRange(C->getValue()->getValue());
2667
2668 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2669 ConstantRange X = getSignedRange(Add->getOperand(0));
2670 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2671 X = X.add(getSignedRange(Add->getOperand(i)));
2672 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002673 }
2674
Dan Gohman85b05a22009-07-13 21:35:55 +00002675 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2676 ConstantRange X = getSignedRange(Mul->getOperand(0));
2677 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2678 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2679 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002680 }
2681
Dan Gohman85b05a22009-07-13 21:35:55 +00002682 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2683 ConstantRange X = getSignedRange(SMax->getOperand(0));
2684 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2685 X = X.smax(getSignedRange(SMax->getOperand(i)));
2686 return X;
2687 }
Dan Gohman62849c02009-06-24 01:05:09 +00002688
Dan Gohman85b05a22009-07-13 21:35:55 +00002689 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2690 ConstantRange X = getSignedRange(UMax->getOperand(0));
2691 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2692 X = X.umax(getSignedRange(UMax->getOperand(i)));
2693 return X;
2694 }
Dan Gohman62849c02009-06-24 01:05:09 +00002695
Dan Gohman85b05a22009-07-13 21:35:55 +00002696 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2697 ConstantRange X = getSignedRange(UDiv->getLHS());
2698 ConstantRange Y = getSignedRange(UDiv->getRHS());
2699 return X.udiv(Y);
2700 }
Dan Gohman62849c02009-06-24 01:05:09 +00002701
Dan Gohman85b05a22009-07-13 21:35:55 +00002702 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2703 ConstantRange X = getSignedRange(ZExt->getOperand());
2704 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2705 }
2706
2707 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2708 ConstantRange X = getSignedRange(SExt->getOperand());
2709 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2710 }
2711
2712 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2713 ConstantRange X = getSignedRange(Trunc->getOperand());
2714 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2715 }
2716
2717 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2718
2719 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2720 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2721 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2722 if (!Trip) return FullSet;
2723
2724 // TODO: non-affine addrec
2725 if (AddRec->isAffine()) {
2726 const Type *Ty = AddRec->getType();
2727 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2728 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2729 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2730
2731 const SCEV *Start = AddRec->getStart();
2732 const SCEV *Step = AddRec->getStepRecurrence(*this);
2733 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2734
2735 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002736 // TODO: This is very conservative.
2737 if (!(Step->isOne() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002738 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
Dan Gohmana16b5762009-07-21 00:42:47 +00002739 !(Step->isAllOnesValue() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002740 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2741 return FullSet;
2742
2743 ConstantRange StartRange = getSignedRange(Start);
2744 ConstantRange EndRange = getSignedRange(End);
2745 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2746 EndRange.getSignedMin());
2747 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2748 EndRange.getSignedMax());
2749 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmanc268e7c2009-07-21 00:37:45 +00002750 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002751 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002752 }
Dan Gohman62849c02009-06-24 01:05:09 +00002753 }
Dan Gohman62849c02009-06-24 01:05:09 +00002754 }
2755
Dan Gohman2c364ad2009-06-19 23:29:04 +00002756 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2757 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002758 unsigned BitWidth = getTypeSizeInBits(U->getType());
2759 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2760 if (NS == 1)
2761 return FullSet;
2762 return
2763 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2764 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002765 }
2766
Dan Gohman85b05a22009-07-13 21:35:55 +00002767 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002768}
2769
Chris Lattner53e677a2004-04-02 20:23:17 +00002770/// createSCEV - We know that there is no SCEV for the specified value.
2771/// Analyze the expression.
2772///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002773const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002774 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002775 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002776
Dan Gohman6c459a22008-06-22 19:56:46 +00002777 unsigned Opcode = Instruction::UserOp1;
2778 if (Instruction *I = dyn_cast<Instruction>(V))
2779 Opcode = I->getOpcode();
2780 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2781 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002782 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2783 return getConstant(CI);
2784 else if (isa<ConstantPointerNull>(V))
2785 return getIntegerSCEV(0, V->getType());
2786 else if (isa<UndefValue>(V))
2787 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002788 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002789 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002790
Dan Gohmanca178902009-07-17 20:47:02 +00002791 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00002792 switch (Opcode) {
2793 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002794 return getAddExpr(getSCEV(U->getOperand(0)),
2795 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002796 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002797 return getMulExpr(getSCEV(U->getOperand(0)),
2798 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002799 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002800 return getUDivExpr(getSCEV(U->getOperand(0)),
2801 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002802 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002803 return getMinusSCEV(getSCEV(U->getOperand(0)),
2804 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002805 case Instruction::And:
2806 // For an expression like x&255 that merely masks off the high bits,
2807 // use zext(trunc(x)) as the SCEV expression.
2808 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002809 if (CI->isNullValue())
2810 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002811 if (CI->isAllOnesValue())
2812 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002813 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002814
2815 // Instcombine's ShrinkDemandedConstant may strip bits out of
2816 // constants, obscuring what would otherwise be a low-bits mask.
2817 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2818 // knew about to reconstruct a low-bits mask value.
2819 unsigned LZ = A.countLeadingZeros();
2820 unsigned BitWidth = A.getBitWidth();
2821 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2822 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2823 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2824
2825 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2826
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002827 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002828 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002829 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002830 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002831 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002832 }
2833 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002834
Dan Gohman6c459a22008-06-22 19:56:46 +00002835 case Instruction::Or:
2836 // If the RHS of the Or is a constant, we may have something like:
2837 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2838 // optimizations will transparently handle this case.
2839 //
2840 // In order for this transformation to be safe, the LHS must be of the
2841 // form X*(2^n) and the Or constant must be less than 2^n.
2842 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002843 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002844 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002845 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002846 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002847 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002848 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002849 break;
2850 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002851 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002852 // If the RHS of the xor is a signbit, then this is just an add.
2853 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002854 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002855 return getAddExpr(getSCEV(U->getOperand(0)),
2856 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002857
2858 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002859 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002860 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002861
2862 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2863 // This is a variant of the check for xor with -1, and it handles
2864 // the case where instcombine has trimmed non-demanded bits out
2865 // of an xor with -1.
2866 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2867 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2868 if (BO->getOpcode() == Instruction::And &&
2869 LCI->getValue() == CI->getValue())
2870 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002871 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002872 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002873 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002874 const Type *Z0Ty = Z0->getType();
2875 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2876
2877 // If C is a low-bits mask, the zero extend is zerving to
2878 // mask off the high bits. Complement the operand and
2879 // re-apply the zext.
2880 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2881 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2882
2883 // If C is a single bit, it may be in the sign-bit position
2884 // before the zero-extend. In this case, represent the xor
2885 // using an add, which is equivalent, and re-apply the zext.
2886 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2887 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2888 Trunc.isSignBit())
2889 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2890 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002891 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002892 }
2893 break;
2894
2895 case Instruction::Shl:
2896 // Turn shift left of a constant amount into a multiply.
2897 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2898 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersone922c022009-07-22 00:24:57 +00002899 Constant *X = getContext().getConstantInt(
Dan Gohman6c459a22008-06-22 19:56:46 +00002900 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002901 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002902 }
2903 break;
2904
Nick Lewycky01eaf802008-07-07 06:15:49 +00002905 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002906 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002907 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2908 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersone922c022009-07-22 00:24:57 +00002909 Constant *X = getContext().getConstantInt(
Nick Lewycky01eaf802008-07-07 06:15:49 +00002910 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002911 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002912 }
2913 break;
2914
Dan Gohman4ee29af2009-04-21 02:26:00 +00002915 case Instruction::AShr:
2916 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2917 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2918 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2919 if (L->getOpcode() == Instruction::Shl &&
2920 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002921 unsigned BitWidth = getTypeSizeInBits(U->getType());
2922 uint64_t Amt = BitWidth - CI->getZExtValue();
2923 if (Amt == BitWidth)
2924 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2925 if (Amt > BitWidth)
2926 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002927 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002928 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002929 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002930 U->getType());
2931 }
2932 break;
2933
Dan Gohman6c459a22008-06-22 19:56:46 +00002934 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002935 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002936
2937 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002938 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002939
2940 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002941 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002942
2943 case Instruction::BitCast:
2944 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002945 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002946 return getSCEV(U->getOperand(0));
2947 break;
2948
Dan Gohmanf2411742009-07-20 17:43:30 +00002949 // It's tempting to handle inttoptr and ptrtoint, however this can
2950 // lead to pointer expressions which cannot be expanded to GEPs
2951 // (because they may overflow). For now, the only pointer-typed
2952 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00002953
Dan Gohman26466c02009-05-08 20:26:55 +00002954 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002955 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002956 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002957
Dan Gohman6c459a22008-06-22 19:56:46 +00002958 case Instruction::PHI:
2959 return createNodeForPHI(cast<PHINode>(U));
2960
2961 case Instruction::Select:
2962 // This could be a smax or umax that was lowered earlier.
2963 // Try to recover it.
2964 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2965 Value *LHS = ICI->getOperand(0);
2966 Value *RHS = ICI->getOperand(1);
2967 switch (ICI->getPredicate()) {
2968 case ICmpInst::ICMP_SLT:
2969 case ICmpInst::ICMP_SLE:
2970 std::swap(LHS, RHS);
2971 // fall through
2972 case ICmpInst::ICMP_SGT:
2973 case ICmpInst::ICMP_SGE:
2974 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002975 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002976 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002977 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002978 break;
2979 case ICmpInst::ICMP_ULT:
2980 case ICmpInst::ICMP_ULE:
2981 std::swap(LHS, RHS);
2982 // fall through
2983 case ICmpInst::ICMP_UGT:
2984 case ICmpInst::ICMP_UGE:
2985 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002986 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002987 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002988 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002989 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002990 case ICmpInst::ICMP_NE:
2991 // n != 0 ? n : 1 -> umax(n, 1)
2992 if (LHS == U->getOperand(1) &&
2993 isa<ConstantInt>(U->getOperand(2)) &&
2994 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2995 isa<ConstantInt>(RHS) &&
2996 cast<ConstantInt>(RHS)->isZero())
2997 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2998 break;
2999 case ICmpInst::ICMP_EQ:
3000 // n == 0 ? 1 : n -> umax(n, 1)
3001 if (LHS == U->getOperand(2) &&
3002 isa<ConstantInt>(U->getOperand(1)) &&
3003 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3004 isa<ConstantInt>(RHS) &&
3005 cast<ConstantInt>(RHS)->isZero())
3006 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3007 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003008 default:
3009 break;
3010 }
3011 }
3012
3013 default: // We cannot analyze this expression.
3014 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003015 }
3016
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003017 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003018}
3019
3020
3021
3022//===----------------------------------------------------------------------===//
3023// Iteration Count Computation Code
3024//
3025
Dan Gohman46bdfb02009-02-24 18:55:53 +00003026/// getBackedgeTakenCount - If the specified loop has a predictable
3027/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3028/// object. The backedge-taken count is the number of times the loop header
3029/// will be branched to from within the loop. This is one less than the
3030/// trip count of the loop, since it doesn't count the first iteration,
3031/// when the header is branched to from outside the loop.
3032///
3033/// Note that it is not valid to call this method on a loop without a
3034/// loop-invariant backedge-taken count (see
3035/// hasLoopInvariantBackedgeTakenCount).
3036///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003037const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003038 return getBackedgeTakenInfo(L).Exact;
3039}
3040
3041/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3042/// return the least SCEV value that is known never to be less than the
3043/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003044const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003045 return getBackedgeTakenInfo(L).Max;
3046}
3047
Dan Gohman59ae6b92009-07-08 19:23:34 +00003048/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3049/// onto the given Worklist.
3050static void
3051PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3052 BasicBlock *Header = L->getHeader();
3053
3054 // Push all Loop-header PHIs onto the Worklist stack.
3055 for (BasicBlock::iterator I = Header->begin();
3056 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3057 Worklist.push_back(PN);
3058}
3059
3060/// PushDefUseChildren - Push users of the given Instruction
3061/// onto the given Worklist.
3062static void
3063PushDefUseChildren(Instruction *I,
3064 SmallVectorImpl<Instruction *> &Worklist) {
3065 // Push the def-use children onto the Worklist stack.
3066 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3067 UI != UE; ++UI)
3068 Worklist.push_back(cast<Instruction>(UI));
3069}
3070
Dan Gohmana1af7572009-04-30 20:47:05 +00003071const ScalarEvolution::BackedgeTakenInfo &
3072ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003073 // Initially insert a CouldNotCompute for this loop. If the insertion
3074 // succeeds, procede to actually compute a backedge-taken count and
3075 // update the value. The temporary CouldNotCompute value tells SCEV
3076 // code elsewhere that it shouldn't attempt to request a new
3077 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003078 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003079 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3080 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003081 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003082 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003083 assert(ItCount.Exact->isLoopInvariant(L) &&
3084 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003085 "Computed trip count isn't loop invariant for loop!");
3086 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003087
Dan Gohman01ecca22009-04-27 20:16:15 +00003088 // Update the value in the map.
3089 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003090 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003091 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003092 // Update the value in the map.
3093 Pair.first->second = ItCount;
3094 if (isa<PHINode>(L->getHeader()->begin()))
3095 // Only count loops that have phi nodes as not being computable.
3096 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003097 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003098
3099 // Now that we know more about the trip count for this loop, forget any
3100 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003101 // conservative estimates made without the benefit of trip count
3102 // information. This is similar to the code in
3103 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3104 // nodes specially.
3105 if (ItCount.hasAnyInfo()) {
3106 SmallVector<Instruction *, 16> Worklist;
3107 PushLoopPHIs(L, Worklist);
3108
3109 SmallPtrSet<Instruction *, 8> Visited;
3110 while (!Worklist.empty()) {
3111 Instruction *I = Worklist.pop_back_val();
3112 if (!Visited.insert(I)) continue;
3113
3114 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3115 Scalars.find(static_cast<Value *>(I));
3116 if (It != Scalars.end()) {
3117 // SCEVUnknown for a PHI either means that it has an unrecognized
3118 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003119 // by createNodeForPHI. In the former case, additional loop trip
3120 // count information isn't going to change anything. In the later
3121 // case, createNodeForPHI will perform the necessary updates on its
3122 // own when it gets to that point.
Dan Gohman59ae6b92009-07-08 19:23:34 +00003123 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3124 Scalars.erase(It);
3125 ValuesAtScopes.erase(I);
3126 if (PHINode *PN = dyn_cast<PHINode>(I))
3127 ConstantEvolutionLoopExitValue.erase(PN);
3128 }
3129
3130 PushDefUseChildren(I, Worklist);
3131 }
3132 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003133 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003134 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003135}
3136
Dan Gohman46bdfb02009-02-24 18:55:53 +00003137/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003138/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003139/// ScalarEvolution's ability to compute a trip count, or if the loop
3140/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003141void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003142 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003143
Dan Gohman35738ac2009-05-04 22:30:44 +00003144 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003145 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003146
Dan Gohman59ae6b92009-07-08 19:23:34 +00003147 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003148 while (!Worklist.empty()) {
3149 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003150 if (!Visited.insert(I)) continue;
3151
3152 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3153 Scalars.find(static_cast<Value *>(I));
3154 if (It != Scalars.end()) {
3155 Scalars.erase(It);
3156 ValuesAtScopes.erase(I);
3157 if (PHINode *PN = dyn_cast<PHINode>(I))
3158 ConstantEvolutionLoopExitValue.erase(PN);
3159 }
3160
3161 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003162 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003163}
3164
Dan Gohman46bdfb02009-02-24 18:55:53 +00003165/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3166/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003167ScalarEvolution::BackedgeTakenInfo
3168ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003169 SmallVector<BasicBlock*, 8> ExitingBlocks;
3170 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003171
Dan Gohmana334aa72009-06-22 00:31:57 +00003172 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003173 const SCEV *BECount = getCouldNotCompute();
3174 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003175 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003176 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3177 BackedgeTakenInfo NewBTI =
3178 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003179
Dan Gohman1c343752009-06-27 21:21:31 +00003180 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003181 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003182 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003183 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003184 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003185 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003186 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003187 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003188 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003189 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003190 }
Dan Gohman1c343752009-06-27 21:21:31 +00003191 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003192 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003193 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003194 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003195 }
3196
3197 return BackedgeTakenInfo(BECount, MaxBECount);
3198}
3199
3200/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3201/// of the specified loop will execute if it exits via the specified block.
3202ScalarEvolution::BackedgeTakenInfo
3203ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3204 BasicBlock *ExitingBlock) {
3205
3206 // Okay, we've chosen an exiting block. See what condition causes us to
3207 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003208 //
3209 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003210 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003211 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003212 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003213
Chris Lattner8b0e3602007-01-07 02:24:26 +00003214 // At this point, we know we have a conditional branch that determines whether
3215 // the loop is exited. However, we don't know if the branch is executed each
3216 // time through the loop. If not, then the execution count of the branch will
3217 // not be equal to the trip count of the loop.
3218 //
3219 // Currently we check for this by checking to see if the Exit branch goes to
3220 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003221 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003222 // loop header. This is common for un-rotated loops.
3223 //
3224 // If both of those tests fail, walk up the unique predecessor chain to the
3225 // header, stopping if there is an edge that doesn't exit the loop. If the
3226 // header is reached, the execution count of the branch will be equal to the
3227 // trip count of the loop.
3228 //
3229 // More extensive analysis could be done to handle more cases here.
3230 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003231 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003232 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003233 ExitBr->getParent() != L->getHeader()) {
3234 // The simple checks failed, try climbing the unique predecessor chain
3235 // up to the header.
3236 bool Ok = false;
3237 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3238 BasicBlock *Pred = BB->getUniquePredecessor();
3239 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003240 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003241 TerminatorInst *PredTerm = Pred->getTerminator();
3242 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3243 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3244 if (PredSucc == BB)
3245 continue;
3246 // If the predecessor has a successor that isn't BB and isn't
3247 // outside the loop, assume the worst.
3248 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003249 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003250 }
3251 if (Pred == L->getHeader()) {
3252 Ok = true;
3253 break;
3254 }
3255 BB = Pred;
3256 }
3257 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003258 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003259 }
3260
3261 // Procede to the next level to examine the exit condition expression.
3262 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3263 ExitBr->getSuccessor(0),
3264 ExitBr->getSuccessor(1));
3265}
3266
3267/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3268/// backedge of the specified loop will execute if its exit condition
3269/// were a conditional branch of ExitCond, TBB, and FBB.
3270ScalarEvolution::BackedgeTakenInfo
3271ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3272 Value *ExitCond,
3273 BasicBlock *TBB,
3274 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003275 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3277 if (BO->getOpcode() == Instruction::And) {
3278 // Recurse on the operands of the and.
3279 BackedgeTakenInfo BTI0 =
3280 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3281 BackedgeTakenInfo BTI1 =
3282 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003283 const SCEV *BECount = getCouldNotCompute();
3284 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003285 if (L->contains(TBB)) {
3286 // Both conditions must be true for the loop to continue executing.
3287 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003288 if (BTI0.Exact == getCouldNotCompute() ||
3289 BTI1.Exact == getCouldNotCompute())
3290 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003291 else
3292 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003293 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003294 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003295 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003296 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003297 else
3298 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003299 } else {
3300 // Both conditions must be true for the loop to exit.
3301 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003302 if (BTI0.Exact != getCouldNotCompute() &&
3303 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003304 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003305 if (BTI0.Max != getCouldNotCompute() &&
3306 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003307 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3308 }
3309
3310 return BackedgeTakenInfo(BECount, MaxBECount);
3311 }
3312 if (BO->getOpcode() == Instruction::Or) {
3313 // Recurse on the operands of the or.
3314 BackedgeTakenInfo BTI0 =
3315 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3316 BackedgeTakenInfo BTI1 =
3317 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003318 const SCEV *BECount = getCouldNotCompute();
3319 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003320 if (L->contains(FBB)) {
3321 // Both conditions must be false for the loop to continue executing.
3322 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003323 if (BTI0.Exact == getCouldNotCompute() ||
3324 BTI1.Exact == getCouldNotCompute())
3325 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003326 else
3327 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003328 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003329 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003330 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003331 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003332 else
3333 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003334 } else {
3335 // Both conditions must be false for the loop to exit.
3336 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003337 if (BTI0.Exact != getCouldNotCompute() &&
3338 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003339 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003340 if (BTI0.Max != getCouldNotCompute() &&
3341 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003342 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3343 }
3344
3345 return BackedgeTakenInfo(BECount, MaxBECount);
3346 }
3347 }
3348
3349 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3350 // Procede to the next level to examine the icmp.
3351 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3352 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003353
Eli Friedman361e54d2009-05-09 12:32:42 +00003354 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003355 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3356}
3357
3358/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3359/// backedge of the specified loop will execute if its exit condition
3360/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3361ScalarEvolution::BackedgeTakenInfo
3362ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3363 ICmpInst *ExitCond,
3364 BasicBlock *TBB,
3365 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003366
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367 // If the condition was exit on true, convert the condition to exit on false
3368 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003369 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003371 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003373
3374 // Handle common loops like: for (X = "string"; *X; ++X)
3375 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3376 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003377 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003378 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003379 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3380 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3381 return BackedgeTakenInfo(ItCnt,
3382 isa<SCEVConstant>(ItCnt) ? ItCnt :
3383 getConstant(APInt::getMaxValue(BitWidth)-1));
3384 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003385 }
3386
Dan Gohman0bba49c2009-07-07 17:06:11 +00003387 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3388 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003389
3390 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003391 LHS = getSCEVAtScope(LHS, L);
3392 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003393
Dan Gohman64a845e2009-06-24 04:48:43 +00003394 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003396 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3397 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003398 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003400 }
3401
Chris Lattner53e677a2004-04-02 20:23:17 +00003402 // If we have a comparison of a chrec against a constant, try to use value
3403 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003404 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3405 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003406 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003407 // Form the constant range.
3408 ConstantRange CompRange(
3409 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003410
Dan Gohman0bba49c2009-07-07 17:06:11 +00003411 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003412 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003413 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003414
Chris Lattner53e677a2004-04-02 20:23:17 +00003415 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003417 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003418 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003420 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003421 }
3422 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003423 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003424 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003426 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003427 }
3428 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003429 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3430 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003431 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003432 }
3433 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003434 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3435 getNotSCEV(RHS), L, true);
3436 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003437 break;
3438 }
3439 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003440 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3441 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003442 break;
3443 }
3444 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003445 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3446 getNotSCEV(RHS), L, false);
3447 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003448 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003450 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003451#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003452 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003453 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003454 errs() << "[unsigned] ";
3455 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003456 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003458#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003459 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003460 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003461 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003462 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003463}
3464
Chris Lattner673e02b2004-10-12 01:49:27 +00003465static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003466EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3467 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003468 const SCEV *InVal = SE.getConstant(C);
3469 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003470 assert(isa<SCEVConstant>(Val) &&
3471 "Evaluation of SCEV at constant didn't fold correctly?");
3472 return cast<SCEVConstant>(Val)->getValue();
3473}
3474
3475/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3476/// and a GEP expression (missing the pointer index) indexing into it, return
3477/// the addressed element of the initializer or null if the index expression is
3478/// invalid.
3479static Constant *
Owen Andersone922c022009-07-22 00:24:57 +00003480GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003481 const std::vector<ConstantInt*> &Indices) {
3482 Constant *Init = GV->getInitializer();
3483 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003484 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003485 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3486 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3487 Init = cast<Constant>(CS->getOperand(Idx));
3488 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3489 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3490 Init = cast<Constant>(CA->getOperand(Idx));
3491 } else if (isa<ConstantAggregateZero>(Init)) {
3492 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3493 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersone922c022009-07-22 00:24:57 +00003494 Init = Context.getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003495 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3496 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersone922c022009-07-22 00:24:57 +00003497 Init = Context.getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003498 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003499 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003500 }
3501 return 0;
3502 } else {
3503 return 0; // Unknown initializer type
3504 }
3505 }
3506 return Init;
3507}
3508
Dan Gohman46bdfb02009-02-24 18:55:53 +00003509/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3510/// 'icmp op load X, cst', try to see if we can compute the backedge
3511/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003512const SCEV *
3513ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3514 LoadInst *LI,
3515 Constant *RHS,
3516 const Loop *L,
3517 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003518 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003519
3520 // Check to see if the loaded pointer is a getelementptr of a global.
3521 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003522 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003523
3524 // Make sure that it is really a constant global we are gepping, with an
3525 // initializer, and make sure the first IDX is really 0.
3526 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3527 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3528 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3529 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003530 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003531
3532 // Okay, we allow one non-constant index into the GEP instruction.
3533 Value *VarIdx = 0;
3534 std::vector<ConstantInt*> Indexes;
3535 unsigned VarIdxNum = 0;
3536 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3537 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3538 Indexes.push_back(CI);
3539 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003540 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003541 VarIdx = GEP->getOperand(i);
3542 VarIdxNum = i-2;
3543 Indexes.push_back(0);
3544 }
3545
3546 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3547 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003548 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003549 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003550
3551 // We can only recognize very limited forms of loop index expressions, in
3552 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003553 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003554 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3555 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3556 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003557 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003558
3559 unsigned MaxSteps = MaxBruteForceIterations;
3560 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersone922c022009-07-22 00:24:57 +00003561 ConstantInt *ItCst = getContext().getConstantInt(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003562 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003563 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003564
3565 // Form the GEP offset.
3566 Indexes[VarIdxNum] = Val;
3567
Owen Andersone922c022009-07-22 00:24:57 +00003568 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003569 if (Result == 0) break; // Cannot compute!
3570
3571 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003572 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003573 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003574 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003575#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003576 errs() << "\n***\n*** Computed loop count " << *ItCst
3577 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3578 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003579#endif
3580 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003581 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003582 }
3583 }
Dan Gohman1c343752009-06-27 21:21:31 +00003584 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003585}
3586
3587
Chris Lattner3221ad02004-04-17 22:58:41 +00003588/// CanConstantFold - Return true if we can constant fold an instruction of the
3589/// specified type, assuming that all operands were constants.
3590static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003591 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003592 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3593 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003594
Chris Lattner3221ad02004-04-17 22:58:41 +00003595 if (const CallInst *CI = dyn_cast<CallInst>(I))
3596 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003597 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003598 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003599}
3600
Chris Lattner3221ad02004-04-17 22:58:41 +00003601/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3602/// in the loop that V is derived from. We allow arbitrary operations along the
3603/// way, but the operands of an operation must either be constants or a value
3604/// derived from a constant PHI. If this expression does not fit with these
3605/// constraints, return null.
3606static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3607 // If this is not an instruction, or if this is an instruction outside of the
3608 // loop, it can't be derived from a loop PHI.
3609 Instruction *I = dyn_cast<Instruction>(V);
3610 if (I == 0 || !L->contains(I->getParent())) return 0;
3611
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003612 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003613 if (L->getHeader() == I->getParent())
3614 return PN;
3615 else
3616 // We don't currently keep track of the control flow needed to evaluate
3617 // PHIs, so we cannot handle PHIs inside of loops.
3618 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003619 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003620
3621 // If we won't be able to constant fold this expression even if the operands
3622 // are constants, return early.
3623 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003624
Chris Lattner3221ad02004-04-17 22:58:41 +00003625 // Otherwise, we can evaluate this instruction if all of its operands are
3626 // constant or derived from a PHI node themselves.
3627 PHINode *PHI = 0;
3628 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3629 if (!(isa<Constant>(I->getOperand(Op)) ||
3630 isa<GlobalValue>(I->getOperand(Op)))) {
3631 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3632 if (P == 0) return 0; // Not evolving from PHI
3633 if (PHI == 0)
3634 PHI = P;
3635 else if (PHI != P)
3636 return 0; // Evolving from multiple different PHIs.
3637 }
3638
3639 // This is a expression evolving from a constant PHI!
3640 return PHI;
3641}
3642
3643/// EvaluateExpression - Given an expression that passes the
3644/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3645/// in the loop has the value PHIVal. If we can't fold this expression for some
3646/// reason, return null.
3647static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3648 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003649 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003650 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003651 Instruction *I = cast<Instruction>(V);
Owen Andersone922c022009-07-22 00:24:57 +00003652 LLVMContext &Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003653
3654 std::vector<Constant*> Operands;
3655 Operands.resize(I->getNumOperands());
3656
3657 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3658 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3659 if (Operands[i] == 0) return 0;
3660 }
3661
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003662 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3663 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003664 &Operands[0], Operands.size(),
3665 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003666 else
3667 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003668 &Operands[0], Operands.size(),
3669 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003670}
3671
3672/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3673/// in the header of its containing loop, we know the loop executes a
3674/// constant number of times, and the PHI node is just a recurrence
3675/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003676Constant *
3677ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3678 const APInt& BEs,
3679 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003680 std::map<PHINode*, Constant*>::iterator I =
3681 ConstantEvolutionLoopExitValue.find(PN);
3682 if (I != ConstantEvolutionLoopExitValue.end())
3683 return I->second;
3684
Dan Gohman46bdfb02009-02-24 18:55:53 +00003685 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003686 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3687
3688 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3689
3690 // Since the loop is canonicalized, the PHI node must have two entries. One
3691 // entry must be a constant (coming in from outside of the loop), and the
3692 // second must be derived from the same PHI.
3693 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3694 Constant *StartCST =
3695 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3696 if (StartCST == 0)
3697 return RetVal = 0; // Must be a constant.
3698
3699 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3700 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3701 if (PN2 != PN)
3702 return RetVal = 0; // Not derived from same PHI.
3703
3704 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003705 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003706 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003707
Dan Gohman46bdfb02009-02-24 18:55:53 +00003708 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003709 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003710 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3711 if (IterationNum == NumIterations)
3712 return RetVal = PHIVal; // Got exit value!
3713
3714 // Compute the value of the PHI node for the next iteration.
3715 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3716 if (NextPHI == PHIVal)
3717 return RetVal = NextPHI; // Stopped evolving!
3718 if (NextPHI == 0)
3719 return 0; // Couldn't evaluate!
3720 PHIVal = NextPHI;
3721 }
3722}
3723
Dan Gohman46bdfb02009-02-24 18:55:53 +00003724/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003725/// constant number of times (the condition evolves only from constants),
3726/// try to evaluate a few iterations of the loop until we get the exit
3727/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003728/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003729const SCEV *
3730ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3731 Value *Cond,
3732 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003733 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003734 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003735
3736 // Since the loop is canonicalized, the PHI node must have two entries. One
3737 // entry must be a constant (coming in from outside of the loop), and the
3738 // second must be derived from the same PHI.
3739 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3740 Constant *StartCST =
3741 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003742 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003743
3744 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3745 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003746 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003747
3748 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3749 // the loop symbolically to determine when the condition gets a value of
3750 // "ExitWhen".
3751 unsigned IterationNum = 0;
3752 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3753 for (Constant *PHIVal = StartCST;
3754 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003755 ConstantInt *CondVal =
3756 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003757
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003758 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003759 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003760
Reid Spencere8019bb2007-03-01 07:25:48 +00003761 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003762 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003763 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003764 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003765
Chris Lattner3221ad02004-04-17 22:58:41 +00003766 // Compute the value of the PHI node for the next iteration.
3767 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3768 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003769 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003770 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003771 }
3772
3773 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003774 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003775}
3776
Dan Gohman66a7e852009-05-08 20:38:54 +00003777/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3778/// at the specified scope in the program. The L value specifies a loop
3779/// nest to evaluate the expression at, where null is the top-level or a
3780/// specified loop is immediately inside of the loop.
3781///
3782/// This method can be used to compute the exit value for a variable defined
3783/// in a loop by querying what the value will hold in the parent loop.
3784///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003785/// In the case that a relevant loop exit value cannot be computed, the
3786/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003787const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003788 // FIXME: this should be turned into a virtual method on SCEV!
3789
Chris Lattner3221ad02004-04-17 22:58:41 +00003790 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003791
Nick Lewycky3e630762008-02-20 06:48:22 +00003792 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003793 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003794 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003795 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003796 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003797 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3798 if (PHINode *PN = dyn_cast<PHINode>(I))
3799 if (PN->getParent() == LI->getHeader()) {
3800 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003801 // to see if the loop that contains it has a known backedge-taken
3802 // count. If so, we may be able to force computation of the exit
3803 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003804 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003805 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003806 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003807 // Okay, we know how many times the containing loop executes. If
3808 // this is a constant evolving PHI node, get the final value at
3809 // the specified iteration number.
3810 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003811 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003812 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003813 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003814 }
3815 }
3816
Reid Spencer09906f32006-12-04 21:33:23 +00003817 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003818 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003819 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003820 // result. This is particularly useful for computing loop exit values.
3821 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003822 // Check to see if we've folded this instruction at this loop before.
3823 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3824 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3825 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3826 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003827 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003828
Chris Lattner3221ad02004-04-17 22:58:41 +00003829 std::vector<Constant*> Operands;
3830 Operands.reserve(I->getNumOperands());
3831 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3832 Value *Op = I->getOperand(i);
3833 if (Constant *C = dyn_cast<Constant>(Op)) {
3834 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003835 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003836 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003837 // non-integer and non-pointer, don't even try to analyze them
3838 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003839 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003840 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003841
Dan Gohman85b05a22009-07-13 21:35:55 +00003842 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00003843 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003844 Constant *C = SC->getValue();
3845 if (C->getType() != Op->getType())
3846 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3847 Op->getType(),
3848 false),
3849 C, Op->getType());
3850 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003851 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003852 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3853 if (C->getType() != Op->getType())
3854 C =
3855 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3856 Op->getType(),
3857 false),
3858 C, Op->getType());
3859 Operands.push_back(C);
3860 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003861 return V;
3862 } else {
3863 return V;
3864 }
3865 }
3866 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003867
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003868 Constant *C;
3869 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3870 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003871 &Operands[0], Operands.size(),
Owen Andersone922c022009-07-22 00:24:57 +00003872 getContext());
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003873 else
3874 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersone922c022009-07-22 00:24:57 +00003875 &Operands[0], Operands.size(),
3876 getContext());
Dan Gohman6bce6432009-05-08 20:47:27 +00003877 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003878 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003879 }
3880 }
3881
3882 // This is some other type of SCEVUnknown, just return it.
3883 return V;
3884 }
3885
Dan Gohman622ed672009-05-04 22:02:23 +00003886 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003887 // Avoid performing the look-up in the common case where the specified
3888 // expression has no loop-variant portions.
3889 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003890 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003891 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003892 // Okay, at least one of these operands is loop variant but might be
3893 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00003894 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3895 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003896 NewOps.push_back(OpAtScope);
3897
3898 for (++i; i != e; ++i) {
3899 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003900 NewOps.push_back(OpAtScope);
3901 }
3902 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003903 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003904 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003905 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003906 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003907 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003908 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003909 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00003910 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003911 }
3912 }
3913 // If we got here, all operands are loop invariant.
3914 return Comm;
3915 }
3916
Dan Gohman622ed672009-05-04 22:02:23 +00003917 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003918 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3919 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003920 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3921 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003922 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003923 }
3924
3925 // If this is a loop recurrence for a loop that does not contain L, then we
3926 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003927 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003928 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3929 // To evaluate this recurrence, we need to know how many times the AddRec
3930 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003931 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00003932 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003933
Eli Friedmanb42a6262008-08-04 23:49:06 +00003934 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003935 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003936 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003937 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003938 }
3939
Dan Gohman622ed672009-05-04 22:02:23 +00003940 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003941 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003942 if (Op == Cast->getOperand())
3943 return Cast; // must be loop invariant
3944 return getZeroExtendExpr(Op, Cast->getType());
3945 }
3946
Dan Gohman622ed672009-05-04 22:02:23 +00003947 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003948 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003949 if (Op == Cast->getOperand())
3950 return Cast; // must be loop invariant
3951 return getSignExtendExpr(Op, Cast->getType());
3952 }
3953
Dan Gohman622ed672009-05-04 22:02:23 +00003954 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003955 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003956 if (Op == Cast->getOperand())
3957 return Cast; // must be loop invariant
3958 return getTruncateExpr(Op, Cast->getType());
3959 }
3960
Torok Edwinc23197a2009-07-14 16:55:14 +00003961 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003962 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003963}
3964
Dan Gohman66a7e852009-05-08 20:38:54 +00003965/// getSCEVAtScope - This is a convenience function which does
3966/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00003967const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003968 return getSCEVAtScope(getSCEV(V), L);
3969}
3970
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003971/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3972/// following equation:
3973///
3974/// A * X = B (mod N)
3975///
3976/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3977/// A and B isn't important.
3978///
3979/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003980static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003981 ScalarEvolution &SE) {
3982 uint32_t BW = A.getBitWidth();
3983 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3984 assert(A != 0 && "A must be non-zero.");
3985
3986 // 1. D = gcd(A, N)
3987 //
3988 // The gcd of A and N may have only one prime factor: 2. The number of
3989 // trailing zeros in A is its multiplicity
3990 uint32_t Mult2 = A.countTrailingZeros();
3991 // D = 2^Mult2
3992
3993 // 2. Check if B is divisible by D.
3994 //
3995 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3996 // is not less than multiplicity of this prime factor for D.
3997 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003998 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003999
4000 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4001 // modulo (N / D).
4002 //
4003 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4004 // bit width during computations.
4005 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4006 APInt Mod(BW + 1, 0);
4007 Mod.set(BW - Mult2); // Mod = N / D
4008 APInt I = AD.multiplicativeInverse(Mod);
4009
4010 // 4. Compute the minimum unsigned root of the equation:
4011 // I * (B / D) mod (N / D)
4012 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4013
4014 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4015 // bits.
4016 return SE.getConstant(Result.trunc(BW));
4017}
Chris Lattner53e677a2004-04-02 20:23:17 +00004018
4019/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4020/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4021/// might be the same) or two SCEVCouldNotCompute objects.
4022///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004023static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004024SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004025 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004026 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4027 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4028 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004029
Chris Lattner53e677a2004-04-02 20:23:17 +00004030 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004031 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004032 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004033 return std::make_pair(CNC, CNC);
4034 }
4035
Reid Spencere8019bb2007-03-01 07:25:48 +00004036 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004037 const APInt &L = LC->getValue()->getValue();
4038 const APInt &M = MC->getValue()->getValue();
4039 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004040 APInt Two(BitWidth, 2);
4041 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004042
Dan Gohman64a845e2009-06-24 04:48:43 +00004043 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004044 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004045 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004046 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4047 // The B coefficient is M-N/2
4048 APInt B(M);
4049 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004050
Reid Spencere8019bb2007-03-01 07:25:48 +00004051 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004052 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004053
Reid Spencere8019bb2007-03-01 07:25:48 +00004054 // Compute the B^2-4ac term.
4055 APInt SqrtTerm(B);
4056 SqrtTerm *= B;
4057 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004058
Reid Spencere8019bb2007-03-01 07:25:48 +00004059 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4060 // integer value or else APInt::sqrt() will assert.
4061 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004062
Dan Gohman64a845e2009-06-24 04:48:43 +00004063 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004064 // The divisions must be performed as signed divisions.
4065 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004066 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004067 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004068 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004069 return std::make_pair(CNC, CNC);
4070 }
4071
Owen Andersone922c022009-07-22 00:24:57 +00004072 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004073
4074 ConstantInt *Solution1 =
Owen Andersone922c022009-07-22 00:24:57 +00004075 Context.getConstantInt((NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004076 ConstantInt *Solution2 =
Owen Andersone922c022009-07-22 00:24:57 +00004077 Context.getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004078
Dan Gohman64a845e2009-06-24 04:48:43 +00004079 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004080 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004081 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004082}
4083
4084/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004085/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004086const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004087 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004088 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004089 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004090 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004091 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004092 }
4093
Dan Gohman35738ac2009-05-04 22:30:44 +00004094 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004095 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004096 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004097
4098 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004099 // If this is an affine expression, the execution count of this branch is
4100 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004101 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004102 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004103 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004104 // equivalent to:
4105 //
4106 // Step*N = -Start (mod 2^BW)
4107 //
4108 // where BW is the common bit width of Start and Step.
4109
Chris Lattner53e677a2004-04-02 20:23:17 +00004110 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004111 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4112 L->getParentLoop());
4113 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4114 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004115
Dan Gohman622ed672009-05-04 22:02:23 +00004116 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004117 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004118
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004119 // First, handle unitary steps.
4120 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004121 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004122 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4123 return Start; // N = Start (as unsigned)
4124
4125 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004126 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004127 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004128 -StartC->getValue()->getValue(),
4129 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004130 }
Chris Lattner42a75512007-01-15 02:27:26 +00004131 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004132 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4133 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004134 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004135 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004136 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4137 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004138 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004139#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004140 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4141 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004142#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004143 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004144 if (ConstantInt *CB =
Owen Andersone922c022009-07-22 00:24:57 +00004145 dyn_cast<ConstantInt>(getContext().getConstantExprICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004146 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004147 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004148 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004149
Chris Lattner53e677a2004-04-02 20:23:17 +00004150 // We can only use this value if the chrec ends up with an exact zero
4151 // value at this index. When solving for "X*X != 5", for example, we
4152 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004153 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004154 if (Val->isZero())
4155 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004156 }
4157 }
4158 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004159
Dan Gohman1c343752009-06-27 21:21:31 +00004160 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004161}
4162
4163/// HowFarToNonZero - Return the number of times a backedge checking the
4164/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004165/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004166const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004167 // Loops that look like: while (X == 0) are very strange indeed. We don't
4168 // handle them yet except for the trivial case. This could be expanded in the
4169 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004170
Chris Lattner53e677a2004-04-02 20:23:17 +00004171 // If the value is a constant, check to see if it is known to be non-zero
4172 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004173 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004174 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004175 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004176 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004177 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004178
Chris Lattner53e677a2004-04-02 20:23:17 +00004179 // We could implement others, but I really doubt anyone writes loops like
4180 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004181 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004182}
4183
Dan Gohman859b4822009-05-18 15:36:09 +00004184/// getLoopPredecessor - If the given loop's header has exactly one unique
4185/// predecessor outside the loop, return it. Otherwise return null.
4186///
4187BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4188 BasicBlock *Header = L->getHeader();
4189 BasicBlock *Pred = 0;
4190 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4191 PI != E; ++PI)
4192 if (!L->contains(*PI)) {
4193 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4194 Pred = *PI;
4195 }
4196 return Pred;
4197}
4198
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004199/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4200/// (which may not be an immediate predecessor) which has exactly one
4201/// successor from which BB is reachable, or null if no such block is
4202/// found.
4203///
4204BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004205ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004206 // If the block has a unique predecessor, then there is no path from the
4207 // predecessor to the block that does not go through the direct edge
4208 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004209 if (BasicBlock *Pred = BB->getSinglePredecessor())
4210 return Pred;
4211
4212 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004213 // If the header has a unique predecessor outside the loop, it must be
4214 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004215 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004216 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004217
4218 return 0;
4219}
4220
Dan Gohman763bad12009-06-20 00:35:32 +00004221/// HasSameValue - SCEV structural equivalence is usually sufficient for
4222/// testing whether two expressions are equal, however for the purposes of
4223/// looking for a condition guarding a loop, it can be useful to be a little
4224/// more general, since a front-end may have replicated the controlling
4225/// expression.
4226///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004227static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004228 // Quick check to see if they are the same SCEV.
4229 if (A == B) return true;
4230
4231 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4232 // two different instructions with the same value. Check for this case.
4233 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4234 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4235 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4236 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4237 if (AI->isIdenticalTo(BI))
4238 return true;
4239
4240 // Otherwise assume they may have a different value.
4241 return false;
4242}
4243
Dan Gohman85b05a22009-07-13 21:35:55 +00004244bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4245 return getSignedRange(S).getSignedMax().isNegative();
4246}
4247
4248bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4249 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4250}
4251
4252bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4253 return !getSignedRange(S).getSignedMin().isNegative();
4254}
4255
4256bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4257 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4258}
4259
4260bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4261 return isKnownNegative(S) || isKnownPositive(S);
4262}
4263
4264bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4265 const SCEV *LHS, const SCEV *RHS) {
4266
4267 if (HasSameValue(LHS, RHS))
4268 return ICmpInst::isTrueWhenEqual(Pred);
4269
4270 switch (Pred) {
4271 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004272 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004273 break;
4274 case ICmpInst::ICMP_SGT:
4275 Pred = ICmpInst::ICMP_SLT;
4276 std::swap(LHS, RHS);
4277 case ICmpInst::ICMP_SLT: {
4278 ConstantRange LHSRange = getSignedRange(LHS);
4279 ConstantRange RHSRange = getSignedRange(RHS);
4280 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4281 return true;
4282 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4283 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004284 break;
4285 }
4286 case ICmpInst::ICMP_SGE:
4287 Pred = ICmpInst::ICMP_SLE;
4288 std::swap(LHS, RHS);
4289 case ICmpInst::ICMP_SLE: {
4290 ConstantRange LHSRange = getSignedRange(LHS);
4291 ConstantRange RHSRange = getSignedRange(RHS);
4292 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4293 return true;
4294 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4295 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004296 break;
4297 }
4298 case ICmpInst::ICMP_UGT:
4299 Pred = ICmpInst::ICMP_ULT;
4300 std::swap(LHS, RHS);
4301 case ICmpInst::ICMP_ULT: {
4302 ConstantRange LHSRange = getUnsignedRange(LHS);
4303 ConstantRange RHSRange = getUnsignedRange(RHS);
4304 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4305 return true;
4306 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4307 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004308 break;
4309 }
4310 case ICmpInst::ICMP_UGE:
4311 Pred = ICmpInst::ICMP_ULE;
4312 std::swap(LHS, RHS);
4313 case ICmpInst::ICMP_ULE: {
4314 ConstantRange LHSRange = getUnsignedRange(LHS);
4315 ConstantRange RHSRange = getUnsignedRange(RHS);
4316 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4317 return true;
4318 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4319 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004320 break;
4321 }
4322 case ICmpInst::ICMP_NE: {
4323 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4324 return true;
4325 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4326 return true;
4327
4328 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4329 if (isKnownNonZero(Diff))
4330 return true;
4331 break;
4332 }
4333 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004334 // The check at the top of the function catches the case where
4335 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004336 break;
4337 }
4338 return false;
4339}
4340
4341/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4342/// protected by a conditional between LHS and RHS. This is used to
4343/// to eliminate casts.
4344bool
4345ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4346 ICmpInst::Predicate Pred,
4347 const SCEV *LHS, const SCEV *RHS) {
4348 // Interpret a null as meaning no loop, where there is obviously no guard
4349 // (interprocedural conditions notwithstanding).
4350 if (!L) return true;
4351
4352 BasicBlock *Latch = L->getLoopLatch();
4353 if (!Latch)
4354 return false;
4355
4356 BranchInst *LoopContinuePredicate =
4357 dyn_cast<BranchInst>(Latch->getTerminator());
4358 if (!LoopContinuePredicate ||
4359 LoopContinuePredicate->isUnconditional())
4360 return false;
4361
Dan Gohman0f4b2852009-07-21 23:03:19 +00004362 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4363 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004364}
4365
4366/// isLoopGuardedByCond - Test whether entry to the loop is protected
4367/// by a conditional between LHS and RHS. This is used to help avoid max
4368/// expressions in loop trip counts, and to eliminate casts.
4369bool
4370ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4371 ICmpInst::Predicate Pred,
4372 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004373 // Interpret a null as meaning no loop, where there is obviously no guard
4374 // (interprocedural conditions notwithstanding).
4375 if (!L) return false;
4376
Dan Gohman859b4822009-05-18 15:36:09 +00004377 BasicBlock *Predecessor = getLoopPredecessor(L);
4378 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004379
Dan Gohman859b4822009-05-18 15:36:09 +00004380 // Starting at the loop predecessor, climb up the predecessor chain, as long
4381 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004382 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004383 for (; Predecessor;
4384 PredecessorDest = Predecessor,
4385 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004386
4387 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004388 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004389 if (!LoopEntryPredicate ||
4390 LoopEntryPredicate->isUnconditional())
4391 continue;
4392
Dan Gohman0f4b2852009-07-21 23:03:19 +00004393 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4394 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004395 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004396 }
4397
Dan Gohman38372182008-08-12 20:17:31 +00004398 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004399}
4400
Dan Gohman0f4b2852009-07-21 23:03:19 +00004401/// isImpliedCond - Test whether the condition described by Pred, LHS,
4402/// and RHS is true whenever the given Cond value evaluates to true.
4403bool ScalarEvolution::isImpliedCond(Value *CondValue,
4404 ICmpInst::Predicate Pred,
4405 const SCEV *LHS, const SCEV *RHS,
4406 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004407 // Recursivly handle And and Or conditions.
4408 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4409 if (BO->getOpcode() == Instruction::And) {
4410 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004411 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4412 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004413 } else if (BO->getOpcode() == Instruction::Or) {
4414 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004415 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4416 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004417 }
4418 }
4419
4420 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4421 if (!ICI) return false;
4422
Dan Gohman85b05a22009-07-13 21:35:55 +00004423 // Bail if the ICmp's operands' types are wider than the needed type
4424 // before attempting to call getSCEV on them. This avoids infinite
4425 // recursion, since the analysis of widening casts can require loop
4426 // exit condition information for overflow checking, which would
4427 // lead back here.
4428 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004429 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004430 return false;
4431
Dan Gohman0f4b2852009-07-21 23:03:19 +00004432 // Now that we found a conditional branch that dominates the loop, check to
4433 // see if it is the comparison we are looking for.
4434 ICmpInst::Predicate FoundPred;
4435 if (Inverse)
4436 FoundPred = ICI->getInversePredicate();
4437 else
4438 FoundPred = ICI->getPredicate();
4439
4440 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4441 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004442
4443 // Balance the types. The case where FoundLHS' type is wider than
4444 // LHS' type is checked for above.
4445 if (getTypeSizeInBits(LHS->getType()) >
4446 getTypeSizeInBits(FoundLHS->getType())) {
4447 if (CmpInst::isSigned(Pred)) {
4448 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4449 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4450 } else {
4451 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4452 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4453 }
4454 }
4455
Dan Gohman0f4b2852009-07-21 23:03:19 +00004456 // Canonicalize the query to match the way instcombine will have
4457 // canonicalized the comparison.
4458 // First, put a constant operand on the right.
4459 if (isa<SCEVConstant>(LHS)) {
4460 std::swap(LHS, RHS);
4461 Pred = ICmpInst::getSwappedPredicate(Pred);
4462 }
4463 // Then, canonicalize comparisons with boundary cases.
4464 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4465 const APInt &RA = RC->getValue()->getValue();
4466 switch (Pred) {
4467 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4468 case ICmpInst::ICMP_EQ:
4469 case ICmpInst::ICMP_NE:
4470 break;
4471 case ICmpInst::ICMP_UGE:
4472 if ((RA - 1).isMinValue()) {
4473 Pred = ICmpInst::ICMP_NE;
4474 RHS = getConstant(RA - 1);
4475 break;
4476 }
4477 if (RA.isMaxValue()) {
4478 Pred = ICmpInst::ICMP_EQ;
4479 break;
4480 }
4481 if (RA.isMinValue()) return true;
4482 break;
4483 case ICmpInst::ICMP_ULE:
4484 if ((RA + 1).isMaxValue()) {
4485 Pred = ICmpInst::ICMP_NE;
4486 RHS = getConstant(RA + 1);
4487 break;
4488 }
4489 if (RA.isMinValue()) {
4490 Pred = ICmpInst::ICMP_EQ;
4491 break;
4492 }
4493 if (RA.isMaxValue()) return true;
4494 break;
4495 case ICmpInst::ICMP_SGE:
4496 if ((RA - 1).isMinSignedValue()) {
4497 Pred = ICmpInst::ICMP_NE;
4498 RHS = getConstant(RA - 1);
4499 break;
4500 }
4501 if (RA.isMaxSignedValue()) {
4502 Pred = ICmpInst::ICMP_EQ;
4503 break;
4504 }
4505 if (RA.isMinSignedValue()) return true;
4506 break;
4507 case ICmpInst::ICMP_SLE:
4508 if ((RA + 1).isMaxSignedValue()) {
4509 Pred = ICmpInst::ICMP_NE;
4510 RHS = getConstant(RA + 1);
4511 break;
4512 }
4513 if (RA.isMinSignedValue()) {
4514 Pred = ICmpInst::ICMP_EQ;
4515 break;
4516 }
4517 if (RA.isMaxSignedValue()) return true;
4518 break;
4519 case ICmpInst::ICMP_UGT:
4520 if (RA.isMinValue()) {
4521 Pred = ICmpInst::ICMP_NE;
4522 break;
4523 }
4524 if ((RA + 1).isMaxValue()) {
4525 Pred = ICmpInst::ICMP_EQ;
4526 RHS = getConstant(RA + 1);
4527 break;
4528 }
4529 if (RA.isMaxValue()) return false;
4530 break;
4531 case ICmpInst::ICMP_ULT:
4532 if (RA.isMaxValue()) {
4533 Pred = ICmpInst::ICMP_NE;
4534 break;
4535 }
4536 if ((RA - 1).isMinValue()) {
4537 Pred = ICmpInst::ICMP_EQ;
4538 RHS = getConstant(RA - 1);
4539 break;
4540 }
4541 if (RA.isMinValue()) return false;
4542 break;
4543 case ICmpInst::ICMP_SGT:
4544 if (RA.isMinSignedValue()) {
4545 Pred = ICmpInst::ICMP_NE;
4546 break;
4547 }
4548 if ((RA + 1).isMaxSignedValue()) {
4549 Pred = ICmpInst::ICMP_EQ;
4550 RHS = getConstant(RA + 1);
4551 break;
4552 }
4553 if (RA.isMaxSignedValue()) return false;
4554 break;
4555 case ICmpInst::ICMP_SLT:
4556 if (RA.isMaxSignedValue()) {
4557 Pred = ICmpInst::ICMP_NE;
4558 break;
4559 }
4560 if ((RA - 1).isMinSignedValue()) {
4561 Pred = ICmpInst::ICMP_EQ;
4562 RHS = getConstant(RA - 1);
4563 break;
4564 }
4565 if (RA.isMinSignedValue()) return false;
4566 break;
4567 }
4568 }
4569
4570 // Check to see if we can make the LHS or RHS match.
4571 if (LHS == FoundRHS || RHS == FoundLHS) {
4572 if (isa<SCEVConstant>(RHS)) {
4573 std::swap(FoundLHS, FoundRHS);
4574 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4575 } else {
4576 std::swap(LHS, RHS);
4577 Pred = ICmpInst::getSwappedPredicate(Pred);
4578 }
4579 }
4580
4581 // Check whether the found predicate is the same as the desired predicate.
4582 if (FoundPred == Pred)
4583 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4584
4585 // Check whether swapping the found predicate makes it the same as the
4586 // desired predicate.
4587 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4588 if (isa<SCEVConstant>(RHS))
4589 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4590 else
4591 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4592 RHS, LHS, FoundLHS, FoundRHS);
4593 }
4594
4595 // Check whether the actual condition is beyond sufficient.
4596 if (FoundPred == ICmpInst::ICMP_EQ)
4597 if (ICmpInst::isTrueWhenEqual(Pred))
4598 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4599 return true;
4600 if (Pred == ICmpInst::ICMP_NE)
4601 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4602 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4603 return true;
4604
4605 // Otherwise assume the worst.
4606 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004607}
4608
Dan Gohman0f4b2852009-07-21 23:03:19 +00004609/// isImpliedCondOperands - Test whether the condition described by Pred,
4610/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4611/// and FoundRHS is true.
4612bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4613 const SCEV *LHS, const SCEV *RHS,
4614 const SCEV *FoundLHS,
4615 const SCEV *FoundRHS) {
4616 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4617 FoundLHS, FoundRHS) ||
4618 // ~x < ~y --> x > y
4619 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4620 getNotSCEV(FoundRHS),
4621 getNotSCEV(FoundLHS));
4622}
4623
4624/// isImpliedCondOperandsHelper - Test whether the condition described by
4625/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4626/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004627bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004628ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4629 const SCEV *LHS, const SCEV *RHS,
4630 const SCEV *FoundLHS,
4631 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004632 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004633 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4634 case ICmpInst::ICMP_EQ:
4635 case ICmpInst::ICMP_NE:
4636 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4637 return true;
4638 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004639 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004640 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004641 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4642 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4643 return true;
4644 break;
4645 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004646 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004647 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4648 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4649 return true;
4650 break;
4651 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004652 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004653 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4654 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4655 return true;
4656 break;
4657 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004658 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004659 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4660 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4661 return true;
4662 break;
4663 }
4664
4665 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004666}
4667
Dan Gohman51f53b72009-06-21 23:46:38 +00004668/// getBECount - Subtract the end and start values and divide by the step,
4669/// rounding up, to get the number of times the backedge is executed. Return
4670/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004671const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004672 const SCEV *End,
4673 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004674 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004675 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4676 const SCEV *Diff = getMinusSCEV(End, Start);
4677 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004678
4679 // Add an adjustment to the difference between End and Start so that
4680 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004681 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004682
4683 // Check Add for unsigned overflow.
4684 // TODO: More sophisticated things could be done here.
Owen Andersone922c022009-07-22 00:24:57 +00004685 const Type *WideTy = getContext().getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004686 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4687 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4688 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004689 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004690 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004691
4692 return getUDivExpr(Add, Step);
4693}
4694
Chris Lattnerdb25de42005-08-15 23:33:51 +00004695/// HowManyLessThans - Return the number of times a backedge containing the
4696/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004697/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004698ScalarEvolution::BackedgeTakenInfo
4699ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4700 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004701 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004702 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004703
Dan Gohman35738ac2009-05-04 22:30:44 +00004704 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004705 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004706 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004707
4708 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004709 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004710 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004711 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004712
4713 // TODO: handle non-constant strides.
4714 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4715 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004716 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004717 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004718 // With unit stride, the iteration never steps past the limit value.
4719 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4720 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4721 // Test whether a positive iteration iteration can step past the limit
4722 // value and past the maximum value for its type in a single step.
4723 if (isSigned) {
4724 APInt Max = APInt::getSignedMaxValue(BitWidth);
4725 if ((Max - CStep->getValue()->getValue())
4726 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004727 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004728 } else {
4729 APInt Max = APInt::getMaxValue(BitWidth);
4730 if ((Max - CStep->getValue()->getValue())
4731 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004732 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004733 }
4734 } else
4735 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004736 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004737 } else
4738 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004739 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004740
Dan Gohmana1af7572009-04-30 20:47:05 +00004741 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4742 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4743 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004744 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004745
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004746 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004747 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004748
Dan Gohmana1af7572009-04-30 20:47:05 +00004749 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004750 const SCEV *MinStart = getConstant(isSigned ?
4751 getSignedRange(Start).getSignedMin() :
4752 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004753
Dan Gohmana1af7572009-04-30 20:47:05 +00004754 // If we know that the condition is true in order to enter the loop,
4755 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004756 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4757 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004758 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004759 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004760 isSigned ? ICmpInst::ICMP_SLT :
4761 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004762 getMinusSCEV(Start, Step), RHS))
4763 End = isSigned ? getSMaxExpr(RHS, Start)
4764 : getUMaxExpr(RHS, Start);
4765
4766 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004767 const SCEV *MaxEnd = getConstant(isSigned ?
4768 getSignedRange(End).getSignedMax() :
4769 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004770
4771 // Finally, we subtract these two values and divide, rounding up, to get
4772 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004773 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004774
4775 // The maximum backedge count is similar, except using the minimum start
4776 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004777 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004778
4779 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004780 }
4781
Dan Gohman1c343752009-06-27 21:21:31 +00004782 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004783}
4784
Chris Lattner53e677a2004-04-02 20:23:17 +00004785/// getNumIterationsInRange - Return the number of iterations of this loop that
4786/// produce values in the specified constant range. Another way of looking at
4787/// this is that it returns the first iteration number where the value is not in
4788/// the condition, thus computing the exit count. If the iteration count can't
4789/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004790const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004791 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004792 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004793 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004794
4795 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004796 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004797 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004798 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004799 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004800 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004801 if (const SCEVAddRecExpr *ShiftedAddRec =
4802 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004803 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004804 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004805 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004806 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004807 }
4808
4809 // The only time we can solve this is when we have all constant indices.
4810 // Otherwise, we cannot determine the overflow conditions.
4811 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4812 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004813 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004814
4815
4816 // Okay at this point we know that all elements of the chrec are constants and
4817 // that the start element is zero.
4818
4819 // First check to see if the range contains zero. If not, the first
4820 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004821 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004822 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004823 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004824
Chris Lattner53e677a2004-04-02 20:23:17 +00004825 if (isAffine()) {
4826 // If this is an affine expression then we have this situation:
4827 // Solve {0,+,A} in Range === Ax in Range
4828
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004829 // We know that zero is in the range. If A is positive then we know that
4830 // the upper value of the range must be the first possible exit value.
4831 // If A is negative then the lower of the range is the last possible loop
4832 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004833 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004834 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4835 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004836
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004837 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004838 APInt ExitVal = (End + A).udiv(A);
Owen Andersone922c022009-07-22 00:24:57 +00004839 ConstantInt *ExitValue = SE.getContext().getConstantInt(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004840
4841 // Evaluate at the exit value. If we really did fall out of the valid
4842 // range, then we computed our trip count, otherwise wrap around or other
4843 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004844 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004845 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004846 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004847
4848 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004849 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004850 EvaluateConstantChrecAtConstant(this,
Owen Andersone922c022009-07-22 00:24:57 +00004851 SE.getContext().getConstantInt(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004852 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004853 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004854 } else if (isQuadratic()) {
4855 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4856 // quadratic equation to solve it. To do this, we must frame our problem in
4857 // terms of figuring out when zero is crossed, instead of when
4858 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004859 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004860 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004861 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004862
4863 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004864 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004865 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004866 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4867 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004868 if (R1) {
4869 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004870 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004871 dyn_cast<ConstantInt>(
Owen Andersone922c022009-07-22 00:24:57 +00004872 SE.getContext().getConstantExprICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00004873 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004874 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004875 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004876
Chris Lattner53e677a2004-04-02 20:23:17 +00004877 // Make sure the root is not off by one. The returned iteration should
4878 // not be in the range, but the previous one should be. When solving
4879 // for "X*X < 5", for example, we should not return a root of 2.
4880 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004881 R1->getValue(),
4882 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004883 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004884 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004885 ConstantInt *NextVal =
Owen Andersone922c022009-07-22 00:24:57 +00004886 SE.getContext().getConstantInt(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004887
Dan Gohman246b2562007-10-22 18:31:58 +00004888 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004889 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004890 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004891 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004892 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004893
Chris Lattner53e677a2004-04-02 20:23:17 +00004894 // If R1 was not in the range, then it is a good return value. Make
4895 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00004896 ConstantInt *NextVal =
Owen Andersone922c022009-07-22 00:24:57 +00004897 SE.getContext().getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004898 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004899 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004900 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004901 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004902 }
4903 }
4904 }
4905
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004906 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004907}
4908
4909
4910
4911//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004912// SCEVCallbackVH Class Implementation
4913//===----------------------------------------------------------------------===//
4914
Dan Gohman1959b752009-05-19 19:22:47 +00004915void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00004916 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004917 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4918 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004919 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4920 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004921 SE->Scalars.erase(getValPtr());
4922 // this now dangles!
4923}
4924
Dan Gohman1959b752009-05-19 19:22:47 +00004925void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00004926 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004927
4928 // Forget all the expressions associated with users of the old value,
4929 // so that future queries will recompute the expressions using the new
4930 // value.
4931 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00004932 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00004933 Value *Old = getValPtr();
4934 bool DeleteOld = false;
4935 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4936 UI != UE; ++UI)
4937 Worklist.push_back(*UI);
4938 while (!Worklist.empty()) {
4939 User *U = Worklist.pop_back_val();
4940 // Deleting the Old value will cause this to dangle. Postpone
4941 // that until everything else is done.
4942 if (U == Old) {
4943 DeleteOld = true;
4944 continue;
4945 }
Dan Gohman69fcae92009-07-14 14:34:04 +00004946 if (!Visited.insert(U))
4947 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00004948 if (PHINode *PN = dyn_cast<PHINode>(U))
4949 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004950 if (Instruction *I = dyn_cast<Instruction>(U))
4951 SE->ValuesAtScopes.erase(I);
Dan Gohman69fcae92009-07-14 14:34:04 +00004952 SE->Scalars.erase(U);
4953 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4954 UI != UE; ++UI)
4955 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00004956 }
Dan Gohman69fcae92009-07-14 14:34:04 +00004957 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00004958 if (DeleteOld) {
4959 if (PHINode *PN = dyn_cast<PHINode>(Old))
4960 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004961 if (Instruction *I = dyn_cast<Instruction>(Old))
4962 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004963 SE->Scalars.erase(Old);
4964 // this now dangles!
4965 }
4966 // this may dangle!
4967}
4968
Dan Gohman1959b752009-05-19 19:22:47 +00004969ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004970 : CallbackVH(V), SE(se) {}
4971
4972//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004973// ScalarEvolution Class Implementation
4974//===----------------------------------------------------------------------===//
4975
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004976ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00004977 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004978}
4979
Chris Lattner53e677a2004-04-02 20:23:17 +00004980bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004981 this->F = &F;
4982 LI = &getAnalysis<LoopInfo>();
4983 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004984 return false;
4985}
4986
4987void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004988 Scalars.clear();
4989 BackedgeTakenCounts.clear();
4990 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004991 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00004992 UniqueSCEVs.clear();
4993 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00004994}
4995
4996void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4997 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004998 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004999}
5000
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005001bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005002 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005003}
5004
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005005static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005006 const Loop *L) {
5007 // Print all inner loops first
5008 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5009 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005010
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005011 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005012
Devang Patelb7211a22007-08-21 00:31:24 +00005013 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005014 L->getExitBlocks(ExitBlocks);
5015 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005016 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005017
Dan Gohman46bdfb02009-02-24 18:55:53 +00005018 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5019 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005020 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005021 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005022 }
5023
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005024 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005025 OS << "Loop " << L->getHeader()->getName() << ": ";
5026
5027 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5028 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5029 } else {
5030 OS << "Unpredictable max backedge-taken count. ";
5031 }
5032
5033 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005034}
5035
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005036void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005037 // ScalarEvolution's implementaiton of the print method is to print
5038 // out SCEV values of all instructions that are interesting. Doing
5039 // this potentially causes it to create new SCEV objects though,
5040 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005041 // observable from outside the class though, so casting away the
5042 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005043 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005044
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005045 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005046 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005047 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005048 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005049 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005050 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005051 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005052
Dan Gohman0c689c52009-06-19 17:49:54 +00005053 const Loop *L = LI->getLoopFor((*I).getParent());
5054
Dan Gohman0bba49c2009-07-07 17:06:11 +00005055 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005056 if (AtUse != SV) {
5057 OS << " --> ";
5058 AtUse->print(OS);
5059 }
5060
5061 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005062 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005063 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005064 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005065 OS << "<<Unknown>>";
5066 } else {
5067 OS << *ExitValue;
5068 }
5069 }
5070
Chris Lattner53e677a2004-04-02 20:23:17 +00005071 OS << "\n";
5072 }
5073
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005074 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5075 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5076 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005077}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005078
5079void ScalarEvolution::print(std::ostream &o, const Module *M) const {
5080 raw_os_ostream OS(o);
5081 print(OS, M);
5082}