blob: 577315879bfffeff521c99109e13e7a1bb60931f [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
Owen Anderson372b46c2009-06-22 21:39:50 +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"
John Criswella1156432005-10-27 15:54:34 +000069#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000070#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000071#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000074#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000075#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000079#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000080#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000081#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000082#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000083#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000084#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000085using namespace llvm;
86
Chris Lattner3b27d682006-12-19 22:30:33 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman844731a2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +000099 "symbolically execute a constant "
100 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000101 cl::init(100));
102
Dan Gohman844731a2008-05-13 00:00:25 +0000103static RegisterPass<ScalarEvolution>
104R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000105char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000106
107//===----------------------------------------------------------------------===//
108// SCEV class definitions
109//===----------------------------------------------------------------------===//
110
111//===----------------------------------------------------------------------===//
112// Implementation of the SCEV class.
113//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000114
Chris Lattner53e677a2004-04-02 20:23:17 +0000115SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000116
Chris Lattner53e677a2004-04-02 20:23:17 +0000117void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000125}
126
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Dan Gohman70a1fe72009-05-18 15:22:39 +0000133bool SCEV::isOne() const {
134 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
135 return SC->getValue()->isOne();
136 return false;
137}
Chris Lattner53e677a2004-04-02 20:23:17 +0000138
Dan Gohman4d289bf2009-06-24 00:30:26 +0000139bool SCEV::isAllOnesValue() const {
140 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
141 return SC->getValue()->isAllOnesValue();
142 return false;
143}
144
Owen Anderson753ad612009-06-22 21:57:23 +0000145SCEVCouldNotCompute::SCEVCouldNotCompute() :
146 SCEV(scCouldNotCompute) {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000147
Dan Gohman1c343752009-06-27 21:21:31 +0000148void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150}
151
Chris Lattner53e677a2004-04-02 20:23:17 +0000152bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
153 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000154 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000155}
156
157const Type *SCEVCouldNotCompute::getType() const {
158 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000159 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000160}
161
162bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
163 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
164 return false;
165}
166
Dan Gohman64a845e2009-06-24 04:48:43 +0000167const SCEV *
168SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
169 const SCEV *Sym,
170 const SCEV *Conc,
171 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000172 return this;
173}
174
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000175void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000176 OS << "***COULDNOTCOMPUTE***";
177}
178
179bool SCEVCouldNotCompute::classof(const SCEV *S) {
180 return S->getSCEVType() == scCouldNotCompute;
181}
182
Owen Anderson372b46c2009-06-22 21:39:50 +0000183const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000184 FoldingSetNodeID ID;
185 ID.AddInteger(scConstant);
186 ID.AddPointer(V);
187 void *IP = 0;
188 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
189 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
190 new (S) SCEVConstant(V);
191 UniqueSCEVs.InsertNode(S, IP);
192 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193}
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Owen Anderson372b46c2009-06-22 21:39:50 +0000195const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman246b2562007-10-22 18:31:58 +0000196 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000197}
198
Owen Anderson372b46c2009-06-22 21:39:50 +0000199const SCEV*
Dan Gohman6de29f82009-06-15 22:12:54 +0000200ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
201 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
202}
203
Dan Gohman1c343752009-06-27 21:21:31 +0000204void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
205 ID.AddInteger(scConstant);
206 ID.AddPointer(V);
207}
208
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000209const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000211void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212 WriteAsOperand(OS, V, false);
213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Dan Gohman84923602009-04-21 01:25:57 +0000215SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Anderson753ad612009-06-22 21:57:23 +0000216 const SCEV* op, const Type *ty)
217 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman84923602009-04-21 01:25:57 +0000218
Dan Gohman1c343752009-06-27 21:21:31 +0000219void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
220 ID.AddInteger(getSCEVType());
221 ID.AddPointer(Op);
222 ID.AddPointer(Ty);
223}
224
Dan Gohman84923602009-04-21 01:25:57 +0000225bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
226 return Op->dominates(BB, DT);
227}
228
Owen Anderson753ad612009-06-22 21:57:23 +0000229SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
230 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234}
Chris Lattner53e677a2004-04-02 20:23:17 +0000235
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000236void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000237 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
Owen Anderson753ad612009-06-22 21:57:23 +0000240SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
241 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000242 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
243 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000244 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000245}
246
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000247void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000248 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000249}
250
Owen Anderson753ad612009-06-22 21:57:23 +0000251SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
252 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000253 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
254 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000255 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000256}
257
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000258void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000259 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000260}
261
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000262void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000263 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
264 const char *OpStr = getOperationStr();
265 OS << "(" << *Operands[0];
266 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
267 OS << OpStr << *Operands[i];
268 OS << ")";
269}
270
Dan Gohman64a845e2009-06-24 04:48:43 +0000271const SCEV *
272SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
273 const SCEV *Sym,
274 const SCEV *Conc,
275 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000276 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000277 const SCEV* H =
Dan Gohman246b2562007-10-22 18:31:58 +0000278 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000279 if (H != getOperand(i)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000280 SmallVector<const SCEV*, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000281 NewOps.reserve(getNumOperands());
282 for (unsigned j = 0; j != i; ++j)
283 NewOps.push_back(getOperand(j));
284 NewOps.push_back(H);
285 for (++i; i != e; ++i)
286 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000287 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288
289 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000290 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000291 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000292 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000293 else if (isa<SCEVSMaxExpr>(this))
294 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000295 else if (isa<SCEVUMaxExpr>(this))
296 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000297 else
298 assert(0 && "Unknown commutative expr!");
299 }
300 }
301 return this;
302}
303
Dan Gohman1c343752009-06-27 21:21:31 +0000304void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
305 ID.AddInteger(getSCEVType());
306 ID.AddInteger(Operands.size());
307 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
308 ID.AddPointer(Operands[i]);
309}
310
Dan Gohmanecb403a2009-05-07 14:00:19 +0000311bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
313 if (!getOperand(i)->dominates(BB, DT))
314 return false;
315 }
316 return true;
317}
318
Dan Gohman1c343752009-06-27 21:21:31 +0000319void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
320 ID.AddInteger(scUDivExpr);
321 ID.AddPointer(LHS);
322 ID.AddPointer(RHS);
323}
324
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000325bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
326 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
327}
328
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000329void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000330 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331}
332
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000333const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000334 // In most cases the types of LHS and RHS will be the same, but in some
335 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
336 // depend on the type for correctness, but handling types carefully can
337 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
338 // a pointer type than the RHS, so use the RHS' type here.
339 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000340}
341
Dan Gohman1c343752009-06-27 21:21:31 +0000342void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
343 ID.AddInteger(scAddRecExpr);
344 ID.AddInteger(Operands.size());
345 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
346 ID.AddPointer(Operands[i]);
347 ID.AddPointer(L);
348}
349
Dan Gohman64a845e2009-06-24 04:48:43 +0000350const SCEV *
351SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
352 const SCEV *Conc,
353 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000354 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000355 const SCEV* H =
Dan Gohman246b2562007-10-22 18:31:58 +0000356 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000357 if (H != getOperand(i)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000358 SmallVector<const SCEV*, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000359 NewOps.reserve(getNumOperands());
360 for (unsigned j = 0; j != i; ++j)
361 NewOps.push_back(getOperand(j));
362 NewOps.push_back(H);
363 for (++i; i != e; ++i)
364 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000365 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000366
Dan Gohman246b2562007-10-22 18:31:58 +0000367 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000368 }
369 }
370 return this;
371}
372
373
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000374bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000375 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000376 if (!QueryLoop)
377 return false;
378
379 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
380 if (QueryLoop->contains(L->getHeader()))
381 return false;
382
383 // This recurrence is variant w.r.t. QueryLoop if any of its operands
384 // are variant.
385 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
386 if (!getOperand(i)->isLoopInvariant(QueryLoop))
387 return false;
388
389 // Otherwise it's loop-invariant.
390 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000391}
392
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000393void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
398}
Chris Lattner53e677a2004-04-02 20:23:17 +0000399
Dan Gohman1c343752009-06-27 21:21:31 +0000400void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
401 ID.AddInteger(scUnknown);
402 ID.AddPointer(V);
403}
404
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000408 // Instructions are never considered invariant in the function body
409 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000410 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000411 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000412 return true;
413}
Chris Lattner53e677a2004-04-02 20:23:17 +0000414
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000415bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
416 if (Instruction *I = dyn_cast<Instruction>(getValue()))
417 return DT->dominates(I->getParent(), BB);
418 return true;
419}
420
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000421const Type *SCEVUnknown::getType() const {
422 return V->getType();
423}
Chris Lattner53e677a2004-04-02 20:23:17 +0000424
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000425void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000426 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000427}
428
Chris Lattner8d741b82004-06-20 06:23:15 +0000429//===----------------------------------------------------------------------===//
430// SCEV Utilities
431//===----------------------------------------------------------------------===//
432
433namespace {
434 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
435 /// than the complexity of the RHS. This comparator is used to canonicalize
436 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000437 class VISIBILITY_HIDDEN SCEVComplexityCompare {
438 LoopInfo *LI;
439 public:
440 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
441
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000442 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000443 // Primarily, sort the SCEVs by their getSCEVType().
444 if (LHS->getSCEVType() != RHS->getSCEVType())
445 return LHS->getSCEVType() < RHS->getSCEVType();
446
447 // Aside from the getSCEVType() ordering, the particular ordering
448 // isn't very important except that it's beneficial to be consistent,
449 // so that (a + b) and (b + a) don't end up as different expressions.
450
451 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
452 // not as complete as it could be.
453 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
454 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
455
Dan Gohman5be18e82009-05-19 02:15:55 +0000456 // Order pointer values after integer values. This helps SCEVExpander
457 // form GEPs.
458 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
459 return false;
460 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
461 return true;
462
Dan Gohman72861302009-05-07 14:39:04 +0000463 // Compare getValueID values.
464 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
465 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
466
467 // Sort arguments by their position.
468 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
469 const Argument *RA = cast<Argument>(RU->getValue());
470 return LA->getArgNo() < RA->getArgNo();
471 }
472
473 // For instructions, compare their loop depth, and their opcode.
474 // This is pretty loose.
475 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
476 Instruction *RV = cast<Instruction>(RU->getValue());
477
478 // Compare loop depths.
479 if (LI->getLoopDepth(LV->getParent()) !=
480 LI->getLoopDepth(RV->getParent()))
481 return LI->getLoopDepth(LV->getParent()) <
482 LI->getLoopDepth(RV->getParent());
483
484 // Compare opcodes.
485 if (LV->getOpcode() != RV->getOpcode())
486 return LV->getOpcode() < RV->getOpcode();
487
488 // Compare the number of operands.
489 if (LV->getNumOperands() != RV->getNumOperands())
490 return LV->getNumOperands() < RV->getNumOperands();
491 }
492
493 return false;
494 }
495
Dan Gohman4dfad292009-06-14 22:51:25 +0000496 // Compare constant values.
497 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
498 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000499 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
500 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000501 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
502 }
503
504 // Compare addrec loop depths.
505 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
506 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
507 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
508 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
509 }
Dan Gohman72861302009-05-07 14:39:04 +0000510
511 // Lexicographically compare n-ary expressions.
512 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
513 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
514 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
515 if (i >= RC->getNumOperands())
516 return false;
517 if (operator()(LC->getOperand(i), RC->getOperand(i)))
518 return true;
519 if (operator()(RC->getOperand(i), LC->getOperand(i)))
520 return false;
521 }
522 return LC->getNumOperands() < RC->getNumOperands();
523 }
524
Dan Gohmana6b35e22009-05-07 19:23:21 +0000525 // Lexicographically compare udiv expressions.
526 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
527 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
528 if (operator()(LC->getLHS(), RC->getLHS()))
529 return true;
530 if (operator()(RC->getLHS(), LC->getLHS()))
531 return false;
532 if (operator()(LC->getRHS(), RC->getRHS()))
533 return true;
534 if (operator()(RC->getRHS(), LC->getRHS()))
535 return false;
536 return false;
537 }
538
Dan Gohman72861302009-05-07 14:39:04 +0000539 // Compare cast expressions by operand.
540 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
541 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
542 return operator()(LC->getOperand(), RC->getOperand());
543 }
544
545 assert(0 && "Unknown SCEV kind!");
546 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000547 }
548 };
549}
550
551/// GroupByComplexity - Given a list of SCEV objects, order them by their
552/// complexity, and group objects of the same complexity together by value.
553/// When this routine is finished, we know that any duplicates in the vector are
554/// consecutive and that complexity is monotonically increasing.
555///
556/// Note that we go take special precautions to ensure that we get determinstic
557/// results from this routine. In other words, we don't want the results of
558/// this to depend on where the addresses of various SCEV objects happened to
559/// land in memory.
560///
Owen Anderson372b46c2009-06-22 21:39:50 +0000561static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000562 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000563 if (Ops.size() < 2) return; // Noop
564 if (Ops.size() == 2) {
565 // This is the common case, which also happens to be trivially simple.
566 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000567 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000568 std::swap(Ops[0], Ops[1]);
569 return;
570 }
571
572 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000573 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000574
575 // Now that we are sorted by complexity, group elements of the same
576 // complexity. Note that this is, at worst, N^2, but the vector is likely to
577 // be extremely short in practice. Note that we take this approach because we
578 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000579 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000580 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000581 unsigned Complexity = S->getSCEVType();
582
583 // If there are any objects of the same complexity and same value as this
584 // one, group them.
585 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
586 if (Ops[j] == S) { // Found a duplicate.
587 // Move it to immediately after i'th element.
588 std::swap(Ops[i+1], Ops[j]);
589 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000590 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000591 }
592 }
593 }
594}
595
Chris Lattner53e677a2004-04-02 20:23:17 +0000596
Chris Lattner53e677a2004-04-02 20:23:17 +0000597
598//===----------------------------------------------------------------------===//
599// Simple SCEV method implementations
600//===----------------------------------------------------------------------===//
601
Eli Friedmanb42a6262008-08-04 23:49:06 +0000602/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000603/// Assume, K > 0.
Owen Anderson372b46c2009-06-22 21:39:50 +0000604static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000605 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000606 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000607 // Handle the simplest case efficiently.
608 if (K == 1)
609 return SE.getTruncateOrZeroExtend(It, ResultTy);
610
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000611 // We are using the following formula for BC(It, K):
612 //
613 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
614 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000615 // Suppose, W is the bitwidth of the return value. We must be prepared for
616 // overflow. Hence, we must assure that the result of our computation is
617 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
618 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000619 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000620 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000621 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000622 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
623 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000625 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000626 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000627 // This formula is trivially equivalent to the previous formula. However,
628 // this formula can be implemented much more efficiently. The trick is that
629 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
630 // arithmetic. To do exact division in modular arithmetic, all we have
631 // to do is multiply by the inverse. Therefore, this step can be done at
632 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000633 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000634 // The next issue is how to safely do the division by 2^T. The way this
635 // is done is by doing the multiplication step at a width of at least W + T
636 // bits. This way, the bottom W+T bits of the product are accurate. Then,
637 // when we perform the division by 2^T (which is equivalent to a right shift
638 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
639 // truncated out after the division by 2^T.
640 //
641 // In comparison to just directly using the first formula, this technique
642 // is much more efficient; using the first formula requires W * K bits,
643 // but this formula less than W + K bits. Also, the first formula requires
644 // a division step, whereas this formula only requires multiplies and shifts.
645 //
646 // It doesn't matter whether the subtraction step is done in the calculation
647 // width or the input iteration count's width; if the subtraction overflows,
648 // the result must be zero anyway. We prefer here to do it in the width of
649 // the induction variable because it helps a lot for certain cases; CodeGen
650 // isn't smart enough to ignore the overflow, which leads to much less
651 // efficient code if the width of the subtraction is wider than the native
652 // register width.
653 //
654 // (It's possible to not widen at all by pulling out factors of 2 before
655 // the multiplication; for example, K=2 can be calculated as
656 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
657 // extra arithmetic, so it's not an obvious win, and it gets
658 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000659
Eli Friedmanb42a6262008-08-04 23:49:06 +0000660 // Protection from insane SCEVs; this bound is conservative,
661 // but it probably doesn't matter.
662 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000663 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000664
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000665 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000666
Eli Friedmanb42a6262008-08-04 23:49:06 +0000667 // Calculate K! / 2^T and T; we divide out the factors of two before
668 // multiplying for calculating K! / 2^T to avoid overflow.
669 // Other overflow doesn't matter because we only care about the bottom
670 // W bits of the result.
671 APInt OddFactorial(W, 1);
672 unsigned T = 1;
673 for (unsigned i = 3; i <= K; ++i) {
674 APInt Mult(W, i);
675 unsigned TwoFactors = Mult.countTrailingZeros();
676 T += TwoFactors;
677 Mult = Mult.lshr(TwoFactors);
678 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000679 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000680
Eli Friedmanb42a6262008-08-04 23:49:06 +0000681 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000682 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000683
684 // Calcuate 2^T, at width T+W.
685 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
686
687 // Calculate the multiplicative inverse of K! / 2^T;
688 // this multiplication factor will perform the exact division by
689 // K! / 2^T.
690 APInt Mod = APInt::getSignedMinValue(W+1);
691 APInt MultiplyFactor = OddFactorial.zext(W+1);
692 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
693 MultiplyFactor = MultiplyFactor.trunc(W);
694
695 // Calculate the product, at width T+W
696 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Anderson372b46c2009-06-22 21:39:50 +0000697 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000698 for (unsigned i = 1; i != K; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000699 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000700 Dividend = SE.getMulExpr(Dividend,
701 SE.getTruncateOrZeroExtend(S, CalculationTy));
702 }
703
704 // Divide by 2^T
Owen Anderson372b46c2009-06-22 21:39:50 +0000705 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000706
707 // Truncate the result, and divide by K! / 2^T.
708
709 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
710 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000711}
712
Chris Lattner53e677a2004-04-02 20:23:17 +0000713/// evaluateAtIteration - Return the value of this chain of recurrences at
714/// the specified iteration number. We can evaluate this recurrence by
715/// multiplying each element in the chain by the binomial coefficient
716/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
717///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000718/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000719///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000720/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000721///
Owen Anderson372b46c2009-06-22 21:39:50 +0000722const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman246b2562007-10-22 18:31:58 +0000723 ScalarEvolution &SE) const {
Owen Anderson372b46c2009-06-22 21:39:50 +0000724 const SCEV* Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000725 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000726 // The computation is correct in the face of overflow provided that the
727 // multiplication is performed _after_ the evaluation of the binomial
728 // coefficient.
Owen Anderson372b46c2009-06-22 21:39:50 +0000729 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000730 if (isa<SCEVCouldNotCompute>(Coeff))
731 return Coeff;
732
733 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000734 }
735 return Result;
736}
737
Chris Lattner53e677a2004-04-02 20:23:17 +0000738//===----------------------------------------------------------------------===//
739// SCEV Expression folder implementations
740//===----------------------------------------------------------------------===//
741
Owen Anderson372b46c2009-06-22 21:39:50 +0000742const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman99243b32009-05-01 16:44:56 +0000743 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000744 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000745 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000746 assert(isSCEVable(Ty) &&
747 "This is not a conversion to a SCEVable type!");
748 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000749
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000750 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000751 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000752 return getConstant(
753 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000754
Dan Gohman20900ca2009-04-22 16:20:48 +0000755 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000756 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000757 return getTruncateExpr(ST->getOperand(), Ty);
758
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000759 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000761 return getTruncateOrSignExtend(SS->getOperand(), Ty);
762
763 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000764 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000765 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
766
Dan Gohman6864db62009-06-18 16:24:47 +0000767 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000768 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000769 SmallVector<const SCEV*, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000770 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000771 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
772 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000773 }
774
Dan Gohman1c343752009-06-27 21:21:31 +0000775 FoldingSetNodeID ID;
776 ID.AddInteger(scTruncate);
777 ID.AddPointer(Op);
778 ID.AddPointer(Ty);
779 void *IP = 0;
780 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
781 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
782 new (S) SCEVTruncateExpr(Op, Ty);
783 UniqueSCEVs.InsertNode(S, IP);
784 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000785}
786
Owen Anderson372b46c2009-06-22 21:39:50 +0000787const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman8170a682009-04-16 19:25:55 +0000788 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000789 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000790 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000791 assert(isSCEVable(Ty) &&
792 "This is not a conversion to a SCEVable type!");
793 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000794
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000795 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000796 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000797 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000798 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
799 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000800 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000801 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000802
Dan Gohman20900ca2009-04-22 16:20:48 +0000803 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000804 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000805 return getZeroExtendExpr(SZ->getOperand(), Ty);
806
Dan Gohman01ecca22009-04-27 20:16:15 +0000807 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000808 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000809 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000811 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000812 if (AR->isAffine()) {
813 // Check whether the backedge-taken count is SCEVCouldNotCompute.
814 // Note that this serves two purposes: It filters out loops that are
815 // simply not analyzable, and it covers the case where this code is
816 // being called from within backedge-taken count analysis, such that
817 // attempting to ask for the backedge-taken count would likely result
818 // in infinite recursion. In the later case, the analysis code will
819 // cope with a conservative value, and it will take care to purge
820 // that value once it has finished.
Owen Anderson372b46c2009-06-22 21:39:50 +0000821 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000822 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000823 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000824 // overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000825 const SCEV* Start = AR->getStart();
826 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000827
828 // Check whether the backedge-taken count can be losslessly casted to
829 // the addrec's type. The count is always unsigned.
Owen Anderson372b46c2009-06-22 21:39:50 +0000830 const SCEV* CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000831 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +0000832 const SCEV* RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000833 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
834 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000835 const Type *WideTy =
836 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000837 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000838 const SCEV* ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000839 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000840 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Anderson372b46c2009-06-22 21:39:50 +0000841 const SCEV* Add = getAddExpr(Start, ZMul);
842 const SCEV* OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000843 getAddExpr(getZeroExtendExpr(Start, WideTy),
844 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
845 getZeroExtendExpr(Step, WideTy)));
846 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000847 // Return the expression with the addrec on the outside.
848 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
849 getZeroExtendExpr(Step, Ty),
850 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000851
852 // Similar to above, only this time treat the step value as signed.
853 // This covers loops that count down.
Owen Anderson372b46c2009-06-22 21:39:50 +0000854 const SCEV* SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000855 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000856 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000857 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000858 OperandExtendedAdd =
859 getAddExpr(getZeroExtendExpr(Start, WideTy),
860 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
861 getSignExtendExpr(Step, WideTy)));
862 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000863 // Return the expression with the addrec on the outside.
864 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
865 getSignExtendExpr(Step, Ty),
866 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000867 }
868 }
869 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000870
Dan Gohman1c343752009-06-27 21:21:31 +0000871 FoldingSetNodeID ID;
872 ID.AddInteger(scZeroExtend);
873 ID.AddPointer(Op);
874 ID.AddPointer(Ty);
875 void *IP = 0;
876 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
877 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
878 new (S) SCEVZeroExtendExpr(Op, Ty);
879 UniqueSCEVs.InsertNode(S, IP);
880 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000881}
882
Owen Anderson372b46c2009-06-22 21:39:50 +0000883const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohman01ecca22009-04-27 20:16:15 +0000884 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000885 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000886 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000887 assert(isSCEVable(Ty) &&
888 "This is not a conversion to a SCEVable type!");
889 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000890
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000891 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000892 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000893 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000894 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
895 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000896 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000897 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000898
Dan Gohman20900ca2009-04-22 16:20:48 +0000899 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000900 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000901 return getSignExtendExpr(SS->getOperand(), Ty);
902
Dan Gohman01ecca22009-04-27 20:16:15 +0000903 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000904 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000905 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000906 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000907 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000908 if (AR->isAffine()) {
909 // Check whether the backedge-taken count is SCEVCouldNotCompute.
910 // Note that this serves two purposes: It filters out loops that are
911 // simply not analyzable, and it covers the case where this code is
912 // being called from within backedge-taken count analysis, such that
913 // attempting to ask for the backedge-taken count would likely result
914 // in infinite recursion. In the later case, the analysis code will
915 // cope with a conservative value, and it will take care to purge
916 // that value once it has finished.
Owen Anderson372b46c2009-06-22 21:39:50 +0000917 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000918 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000919 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000920 // overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000921 const SCEV* Start = AR->getStart();
922 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000923
924 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000925 // the addrec's type. The count is always unsigned.
Owen Anderson372b46c2009-06-22 21:39:50 +0000926 const SCEV* CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000927 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +0000928 const SCEV* RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000929 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
930 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000931 const Type *WideTy =
932 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000933 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000934 const SCEV* SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000935 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000936 getTruncateOrSignExtend(Step, Start->getType()));
Owen Anderson372b46c2009-06-22 21:39:50 +0000937 const SCEV* Add = getAddExpr(Start, SMul);
938 const SCEV* OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000939 getAddExpr(getSignExtendExpr(Start, WideTy),
940 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
941 getSignExtendExpr(Step, WideTy)));
942 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000943 // Return the expression with the addrec on the outside.
944 return getAddRecExpr(getSignExtendExpr(Start, Ty),
945 getSignExtendExpr(Step, Ty),
946 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000947 }
948 }
949 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000950
Dan Gohman1c343752009-06-27 21:21:31 +0000951 FoldingSetNodeID ID;
952 ID.AddInteger(scSignExtend);
953 ID.AddPointer(Op);
954 ID.AddPointer(Ty);
955 void *IP = 0;
956 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
957 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
958 new (S) SCEVSignExtendExpr(Op, Ty);
959 UniqueSCEVs.InsertNode(S, IP);
960 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +0000961}
962
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000963/// getAnyExtendExpr - Return a SCEV for the given operand extended with
964/// unspecified bits out to the given type.
965///
Owen Anderson372b46c2009-06-22 21:39:50 +0000966const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000967 const Type *Ty) {
968 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
969 "This is not an extending conversion!");
970 assert(isSCEVable(Ty) &&
971 "This is not a conversion to a SCEVable type!");
972 Ty = getEffectiveSCEVType(Ty);
973
974 // Sign-extend negative constants.
975 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
976 if (SC->getValue()->getValue().isNegative())
977 return getSignExtendExpr(Op, Ty);
978
979 // Peel off a truncate cast.
980 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000981 const SCEV* NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000982 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
983 return getAnyExtendExpr(NewOp, Ty);
984 return getTruncateOrNoop(NewOp, Ty);
985 }
986
987 // Next try a zext cast. If the cast is folded, use it.
Owen Anderson372b46c2009-06-22 21:39:50 +0000988 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000989 if (!isa<SCEVZeroExtendExpr>(ZExt))
990 return ZExt;
991
992 // Next try a sext cast. If the cast is folded, use it.
Owen Anderson372b46c2009-06-22 21:39:50 +0000993 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000994 if (!isa<SCEVSignExtendExpr>(SExt))
995 return SExt;
996
997 // If the expression is obviously signed, use the sext cast value.
998 if (isa<SCEVSMaxExpr>(Op))
999 return SExt;
1000
1001 // Absent any other information, use the zext cast value.
1002 return ZExt;
1003}
1004
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001005/// CollectAddOperandsWithScales - Process the given Ops list, which is
1006/// a list of operands to be added under the given scale, update the given
1007/// map. This is a helper function for getAddRecExpr. As an example of
1008/// what it does, given a sequence of operands that would form an add
1009/// expression like this:
1010///
1011/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1012///
1013/// where A and B are constants, update the map with these values:
1014///
1015/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1016///
1017/// and add 13 + A*B*29 to AccumulatedConstant.
1018/// This will allow getAddRecExpr to produce this:
1019///
1020/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1021///
1022/// This form often exposes folding opportunities that are hidden in
1023/// the original operand list.
1024///
1025/// Return true iff it appears that any interesting folding opportunities
1026/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1027/// the common case where no interesting opportunities are present, and
1028/// is also used as a check to avoid infinite recursion.
1029///
1030static bool
Owen Anderson372b46c2009-06-22 21:39:50 +00001031CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
1032 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001033 APInt &AccumulatedConstant,
Owen Anderson372b46c2009-06-22 21:39:50 +00001034 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001035 const APInt &Scale,
1036 ScalarEvolution &SE) {
1037 bool Interesting = false;
1038
1039 // Iterate over the add operands.
1040 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1041 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1042 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1043 APInt NewScale =
1044 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1045 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1046 // A multiplication of a constant with another add; recurse.
1047 Interesting |=
1048 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1049 cast<SCEVAddExpr>(Mul->getOperand(1))
1050 ->getOperands(),
1051 NewScale, SE);
1052 } else {
1053 // A multiplication of a constant with some other value. Update
1054 // the map.
Owen Anderson372b46c2009-06-22 21:39:50 +00001055 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1056 const SCEV* Key = SE.getMulExpr(MulOps);
1057 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001058 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001059 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001060 NewOps.push_back(Pair.first->first);
1061 } else {
1062 Pair.first->second += NewScale;
1063 // The map already had an entry for this value, which may indicate
1064 // a folding opportunity.
1065 Interesting = true;
1066 }
1067 }
1068 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1069 // Pull a buried constant out to the outside.
1070 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1071 Interesting = true;
1072 AccumulatedConstant += Scale * C->getValue()->getValue();
1073 } else {
1074 // An ordinary operand. Update the map.
Owen Anderson372b46c2009-06-22 21:39:50 +00001075 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001076 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001077 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001078 NewOps.push_back(Pair.first->first);
1079 } else {
1080 Pair.first->second += Scale;
1081 // The map already had an entry for this value, which may indicate
1082 // a folding opportunity.
1083 Interesting = true;
1084 }
1085 }
1086 }
1087
1088 return Interesting;
1089}
1090
1091namespace {
1092 struct APIntCompare {
1093 bool operator()(const APInt &LHS, const APInt &RHS) const {
1094 return LHS.ult(RHS);
1095 }
1096 };
1097}
1098
Dan Gohman6c0866c2009-05-24 23:45:28 +00001099/// getAddExpr - Get a canonical add expression, or something simpler if
1100/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001101const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001102 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001103 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001104#ifndef NDEBUG
1105 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1106 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1107 getEffectiveSCEVType(Ops[0]->getType()) &&
1108 "SCEVAddExpr operand types don't match!");
1109#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001110
1111 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001112 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001113
1114 // If there are any constants, fold them together.
1115 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001116 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001117 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001118 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001119 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001120 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001121 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1122 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001123 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001124 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001125 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001126 }
1127
1128 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001129 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001130 Ops.erase(Ops.begin());
1131 --Idx;
1132 }
1133 }
1134
Chris Lattner627018b2004-04-07 16:16:11 +00001135 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001136
Chris Lattner53e677a2004-04-02 20:23:17 +00001137 // Okay, check to see if the same value occurs in the operand list twice. If
1138 // so, merge them together into an multiply expression. Since we sorted the
1139 // list, these values are required to be adjacent.
1140 const Type *Ty = Ops[0]->getType();
1141 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1142 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1143 // Found a match, merge the two values into a multiply, and add any
1144 // remaining values to the result.
Owen Anderson372b46c2009-06-22 21:39:50 +00001145 const SCEV* Two = getIntegerSCEV(2, Ty);
1146 const SCEV* Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001147 if (Ops.size() == 2)
1148 return Mul;
1149 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1150 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001151 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001152 }
1153
Dan Gohman728c7f32009-05-08 21:03:19 +00001154 // Check for truncates. If all the operands are truncated from the same
1155 // type, see if factoring out the truncate would permit the result to be
1156 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1157 // if the contents of the resulting outer trunc fold to something simple.
1158 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1159 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1160 const Type *DstType = Trunc->getType();
1161 const Type *SrcType = Trunc->getOperand()->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00001162 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001163 bool Ok = true;
1164 // Check all the operands to see if they can be represented in the
1165 // source type of the truncate.
1166 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1167 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1168 if (T->getOperand()->getType() != SrcType) {
1169 Ok = false;
1170 break;
1171 }
1172 LargeOps.push_back(T->getOperand());
1173 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1174 // This could be either sign or zero extension, but sign extension
1175 // is much more likely to be foldable here.
1176 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1177 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001178 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001179 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1180 if (const SCEVTruncateExpr *T =
1181 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1182 if (T->getOperand()->getType() != SrcType) {
1183 Ok = false;
1184 break;
1185 }
1186 LargeMulOps.push_back(T->getOperand());
1187 } else if (const SCEVConstant *C =
1188 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1189 // This could be either sign or zero extension, but sign extension
1190 // is much more likely to be foldable here.
1191 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1192 } else {
1193 Ok = false;
1194 break;
1195 }
1196 }
1197 if (Ok)
1198 LargeOps.push_back(getMulExpr(LargeMulOps));
1199 } else {
1200 Ok = false;
1201 break;
1202 }
1203 }
1204 if (Ok) {
1205 // Evaluate the expression in the larger type.
Owen Anderson372b46c2009-06-22 21:39:50 +00001206 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001207 // If it folds to something simple, use it. Otherwise, don't.
1208 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1209 return getTruncateExpr(Fold, DstType);
1210 }
1211 }
1212
1213 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001214 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1215 ++Idx;
1216
1217 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001218 if (Idx < Ops.size()) {
1219 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001220 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001221 // If we have an add, expand the add operands onto the end of the operands
1222 // list.
1223 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1224 Ops.erase(Ops.begin()+Idx);
1225 DeletedAdd = true;
1226 }
1227
1228 // If we deleted at least one add, we added operands to the end of the list,
1229 // and they are not necessarily sorted. Recurse to resort and resimplify
1230 // any operands we just aquired.
1231 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001232 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001233 }
1234
1235 // Skip over the add expression until we get to a multiply.
1236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1237 ++Idx;
1238
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001239 // Check to see if there are any folding opportunities present with
1240 // operands multiplied by constant values.
1241 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1242 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +00001243 DenseMap<const SCEV*, APInt> M;
1244 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001245 APInt AccumulatedConstant(BitWidth, 0);
1246 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1247 Ops, APInt(BitWidth, 1), *this)) {
1248 // Some interesting folding opportunity is present, so its worthwhile to
1249 // re-generate the operands list. Group the operands by constant scale,
1250 // to avoid multiplying by the same constant scale multiple times.
Owen Anderson372b46c2009-06-22 21:39:50 +00001251 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1252 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001253 E = NewOps.end(); I != E; ++I)
1254 MulOpLists[M.find(*I)->second].push_back(*I);
1255 // Re-generate the operands list.
1256 Ops.clear();
1257 if (AccumulatedConstant != 0)
1258 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001259 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1260 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001261 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001262 Ops.push_back(getMulExpr(getConstant(I->first),
1263 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001264 if (Ops.empty())
1265 return getIntegerSCEV(0, Ty);
1266 if (Ops.size() == 1)
1267 return Ops[0];
1268 return getAddExpr(Ops);
1269 }
1270 }
1271
Chris Lattner53e677a2004-04-02 20:23:17 +00001272 // If we are adding something to a multiply expression, make sure the
1273 // something is not already an operand of the multiply. If so, merge it into
1274 // the multiply.
1275 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001276 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001277 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001278 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001279 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001280 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001281 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Anderson372b46c2009-06-22 21:39:50 +00001282 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001283 if (Mul->getNumOperands() != 2) {
1284 // If the multiply has more than two operands, we must get the
1285 // Y*Z term.
Owen Anderson372b46c2009-06-22 21:39:50 +00001286 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001287 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001288 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001289 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001290 const SCEV* One = getIntegerSCEV(1, Ty);
1291 const SCEV* AddOne = getAddExpr(InnerMul, One);
1292 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001293 if (Ops.size() == 2) return OuterMul;
1294 if (AddOp < Idx) {
1295 Ops.erase(Ops.begin()+AddOp);
1296 Ops.erase(Ops.begin()+Idx-1);
1297 } else {
1298 Ops.erase(Ops.begin()+Idx);
1299 Ops.erase(Ops.begin()+AddOp-1);
1300 }
1301 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001302 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001304
Chris Lattner53e677a2004-04-02 20:23:17 +00001305 // Check this multiply against other multiplies being added together.
1306 for (unsigned OtherMulIdx = Idx+1;
1307 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1308 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001309 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001310 // If MulOp occurs in OtherMul, we can fold the two multiplies
1311 // together.
1312 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1313 OMulOp != e; ++OMulOp)
1314 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1315 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Anderson372b46c2009-06-22 21:39:50 +00001316 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001317 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001318 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1319 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001321 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001322 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001323 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001324 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001325 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1326 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001327 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001328 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001330 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1331 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001332 if (Ops.size() == 2) return OuterMul;
1333 Ops.erase(Ops.begin()+Idx);
1334 Ops.erase(Ops.begin()+OtherMulIdx-1);
1335 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001336 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001337 }
1338 }
1339 }
1340 }
1341
1342 // If there are any add recurrences in the operands list, see if any other
1343 // added values are loop invariant. If so, we can fold them into the
1344 // recurrence.
1345 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1346 ++Idx;
1347
1348 // Scan over all recurrences, trying to fold loop invariants into them.
1349 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1350 // Scan all of the other operands to this add and add them to the vector if
1351 // they are loop invariant w.r.t. the recurrence.
Owen Anderson372b46c2009-06-22 21:39:50 +00001352 SmallVector<const SCEV*, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001353 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001354 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1355 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1356 LIOps.push_back(Ops[i]);
1357 Ops.erase(Ops.begin()+i);
1358 --i; --e;
1359 }
1360
1361 // If we found some loop invariants, fold them into the recurrence.
1362 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001363 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 LIOps.push_back(AddRec->getStart());
1365
Owen Anderson372b46c2009-06-22 21:39:50 +00001366 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001367 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001368 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001369
Owen Anderson372b46c2009-06-22 21:39:50 +00001370 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001371 // If all of the other operands were loop invariant, we are done.
1372 if (Ops.size() == 1) return NewRec;
1373
1374 // Otherwise, add the folded AddRec by the non-liv parts.
1375 for (unsigned i = 0;; ++i)
1376 if (Ops[i] == AddRec) {
1377 Ops[i] = NewRec;
1378 break;
1379 }
Dan Gohman246b2562007-10-22 18:31:58 +00001380 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001381 }
1382
1383 // Okay, if there weren't any loop invariants to be folded, check to see if
1384 // there are multiple AddRec's with the same loop induction variable being
1385 // added together. If so, we can fold them.
1386 for (unsigned OtherIdx = Idx+1;
1387 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1388 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001389 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001390 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1391 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001392 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1393 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001394 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1395 if (i >= NewOps.size()) {
1396 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1397 OtherAddRec->op_end());
1398 break;
1399 }
Dan Gohman246b2562007-10-22 18:31:58 +00001400 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001402 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001403
1404 if (Ops.size() == 2) return NewAddRec;
1405
1406 Ops.erase(Ops.begin()+Idx);
1407 Ops.erase(Ops.begin()+OtherIdx-1);
1408 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001409 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 }
1411 }
1412
1413 // Otherwise couldn't fold anything into this recurrence. Move onto the
1414 // next one.
1415 }
1416
1417 // Okay, it looks like we really DO need an add expr. Check to see if we
1418 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001419 FoldingSetNodeID ID;
1420 ID.AddInteger(scAddExpr);
1421 ID.AddInteger(Ops.size());
1422 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1423 ID.AddPointer(Ops[i]);
1424 void *IP = 0;
1425 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1426 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1427 new (S) SCEVAddExpr(Ops);
1428 UniqueSCEVs.InsertNode(S, IP);
1429 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001430}
1431
1432
Dan Gohman6c0866c2009-05-24 23:45:28 +00001433/// getMulExpr - Get a canonical multiply expression, or something simpler if
1434/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001435const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001436 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001437#ifndef NDEBUG
1438 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1439 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1440 getEffectiveSCEVType(Ops[0]->getType()) &&
1441 "SCEVMulExpr operand types don't match!");
1442#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001443
1444 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001445 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001446
1447 // If there are any constants, fold them together.
1448 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001449 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001450
1451 // C1*(C2+V) -> C1*C2 + C1*V
1452 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001453 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001454 if (Add->getNumOperands() == 2 &&
1455 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001456 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1457 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001458
1459
1460 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001461 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 // We found two constants, fold them together!
Dan Gohman64a845e2009-06-24 04:48:43 +00001463 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001464 RHSC->getValue()->getValue());
1465 Ops[0] = getConstant(Fold);
1466 Ops.erase(Ops.begin()+1); // Erase the folded element
1467 if (Ops.size() == 1) return Ops[0];
1468 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 }
1470
1471 // If we are left with a constant one being multiplied, strip it off.
1472 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1473 Ops.erase(Ops.begin());
1474 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001475 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 // If we have a multiply of zero, it will always be zero.
1477 return Ops[0];
1478 }
1479 }
1480
1481 // Skip over the add expression until we get to a multiply.
1482 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1483 ++Idx;
1484
1485 if (Ops.size() == 1)
1486 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001487
Chris Lattner53e677a2004-04-02 20:23:17 +00001488 // If there are mul operands inline them all into this expression.
1489 if (Idx < Ops.size()) {
1490 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001491 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001492 // If we have an mul, expand the mul operands onto the end of the operands
1493 // list.
1494 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1495 Ops.erase(Ops.begin()+Idx);
1496 DeletedMul = true;
1497 }
1498
1499 // If we deleted at least one mul, we added operands to the end of the list,
1500 // and they are not necessarily sorted. Recurse to resort and resimplify
1501 // any operands we just aquired.
1502 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001503 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 }
1505
1506 // If there are any add recurrences in the operands list, see if any other
1507 // added values are loop invariant. If so, we can fold them into the
1508 // recurrence.
1509 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1510 ++Idx;
1511
1512 // Scan over all recurrences, trying to fold loop invariants into them.
1513 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1514 // Scan all of the other operands to this mul and add them to the vector if
1515 // they are loop invariant w.r.t. the recurrence.
Owen Anderson372b46c2009-06-22 21:39:50 +00001516 SmallVector<const SCEV*, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001517 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1519 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1520 LIOps.push_back(Ops[i]);
1521 Ops.erase(Ops.begin()+i);
1522 --i; --e;
1523 }
1524
1525 // If we found some loop invariants, fold them into the recurrence.
1526 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001527 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Anderson372b46c2009-06-22 21:39:50 +00001528 SmallVector<const SCEV*, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001529 NewOps.reserve(AddRec->getNumOperands());
1530 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001531 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001532 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001533 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001534 } else {
1535 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001536 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001538 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 }
1540 }
1541
Owen Anderson372b46c2009-06-22 21:39:50 +00001542 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001543
1544 // If all of the other operands were loop invariant, we are done.
1545 if (Ops.size() == 1) return NewRec;
1546
1547 // Otherwise, multiply the folded AddRec by the non-liv parts.
1548 for (unsigned i = 0;; ++i)
1549 if (Ops[i] == AddRec) {
1550 Ops[i] = NewRec;
1551 break;
1552 }
Dan Gohman246b2562007-10-22 18:31:58 +00001553 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 }
1555
1556 // Okay, if there weren't any loop invariants to be folded, check to see if
1557 // there are multiple AddRec's with the same loop induction variable being
1558 // multiplied together. If so, we can fold them.
1559 for (unsigned OtherIdx = Idx+1;
1560 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1561 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001562 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001563 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1564 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001565 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Anderson372b46c2009-06-22 21:39:50 +00001566 const SCEV* NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 G->getStart());
Owen Anderson372b46c2009-06-22 21:39:50 +00001568 const SCEV* B = F->getStepRecurrence(*this);
1569 const SCEV* D = G->getStepRecurrence(*this);
1570 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001571 getMulExpr(G, B),
1572 getMulExpr(B, D));
Owen Anderson372b46c2009-06-22 21:39:50 +00001573 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001574 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 if (Ops.size() == 2) return NewAddRec;
1576
1577 Ops.erase(Ops.begin()+Idx);
1578 Ops.erase(Ops.begin()+OtherIdx-1);
1579 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001580 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001581 }
1582 }
1583
1584 // Otherwise couldn't fold anything into this recurrence. Move onto the
1585 // next one.
1586 }
1587
1588 // Okay, it looks like we really DO need an mul expr. Check to see if we
1589 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001590 FoldingSetNodeID ID;
1591 ID.AddInteger(scMulExpr);
1592 ID.AddInteger(Ops.size());
1593 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1594 ID.AddPointer(Ops[i]);
1595 void *IP = 0;
1596 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1597 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1598 new (S) SCEVMulExpr(Ops);
1599 UniqueSCEVs.InsertNode(S, IP);
1600 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001601}
1602
Dan Gohman6c0866c2009-05-24 23:45:28 +00001603/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1604/// possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001605const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1606 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001607 assert(getEffectiveSCEVType(LHS->getType()) ==
1608 getEffectiveSCEVType(RHS->getType()) &&
1609 "SCEVUDivExpr operand types don't match!");
1610
Dan Gohman622ed672009-05-04 22:02:23 +00001611 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001612 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001613 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001614 if (RHSC->isZero())
1615 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001616
Dan Gohman185cf032009-05-08 20:18:49 +00001617 // Determine if the division can be folded into the operands of
1618 // its operands.
1619 // TODO: Generalize this to non-constants by using known-bits information.
1620 const Type *Ty = LHS->getType();
1621 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1622 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1623 // For non-power-of-two values, effectively round the value up to the
1624 // nearest power of two.
1625 if (!RHSC->getValue()->getValue().isPowerOf2())
1626 ++MaxShiftAmt;
1627 const IntegerType *ExtTy =
1628 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1629 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1630 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1631 if (const SCEVConstant *Step =
1632 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1633 if (!Step->getValue()->getValue()
1634 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001635 getZeroExtendExpr(AR, ExtTy) ==
1636 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1637 getZeroExtendExpr(Step, ExtTy),
1638 AR->getLoop())) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001639 SmallVector<const SCEV*, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001640 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1641 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1642 return getAddRecExpr(Operands, AR->getLoop());
1643 }
1644 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001645 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001646 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001647 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1648 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1649 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001650 // Find an operand that's safely divisible.
1651 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001652 const SCEV* Op = M->getOperand(i);
1653 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001654 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001655 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1656 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001657 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001658 Operands[i] = Div;
1659 return getMulExpr(Operands);
1660 }
1661 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001662 }
Dan Gohman185cf032009-05-08 20:18:49 +00001663 // (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 +00001664 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001665 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001666 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1667 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1668 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1669 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001670 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001671 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001672 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1673 break;
1674 Operands.push_back(Op);
1675 }
1676 if (Operands.size() == A->getNumOperands())
1677 return getAddExpr(Operands);
1678 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001679 }
Dan Gohman185cf032009-05-08 20:18:49 +00001680
1681 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001682 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001683 Constant *LHSCV = LHSC->getValue();
1684 Constant *RHSCV = RHSC->getValue();
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001685 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1686 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 }
1688 }
1689
Dan Gohman1c343752009-06-27 21:21:31 +00001690 FoldingSetNodeID ID;
1691 ID.AddInteger(scUDivExpr);
1692 ID.AddPointer(LHS);
1693 ID.AddPointer(RHS);
1694 void *IP = 0;
1695 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1696 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1697 new (S) SCEVUDivExpr(LHS, RHS);
1698 UniqueSCEVs.InsertNode(S, IP);
1699 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001700}
1701
1702
Dan Gohman6c0866c2009-05-24 23:45:28 +00001703/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1704/// Simplify the expression as much as possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001705const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1706 const SCEV* Step, const Loop *L) {
1707 SmallVector<const SCEV*, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001708 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001709 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001710 if (StepChrec->getLoop() == L) {
1711 Operands.insert(Operands.end(), StepChrec->op_begin(),
1712 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001713 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001714 }
1715
1716 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001717 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001718}
1719
Dan Gohman6c0866c2009-05-24 23:45:28 +00001720/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1721/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001722const SCEV *
1723ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
1724 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001725 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001726#ifndef NDEBUG
1727 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1728 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1729 getEffectiveSCEVType(Operands[0]->getType()) &&
1730 "SCEVAddRecExpr operand types don't match!");
1731#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001732
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001733 if (Operands.back()->isZero()) {
1734 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001735 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001736 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001737
Dan Gohmand9cc7492008-08-08 18:33:12 +00001738 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001739 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001740 const Loop* NestedLoop = NestedAR->getLoop();
1741 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001742 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001743 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001744 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001745 // AddRecs require their operands be loop-invariant with respect to their
1746 // loops. Don't perform this transformation if it would break this
1747 // requirement.
1748 bool AllInvariant = true;
1749 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1750 if (!Operands[i]->isLoopInvariant(L)) {
1751 AllInvariant = false;
1752 break;
1753 }
1754 if (AllInvariant) {
1755 NestedOperands[0] = getAddRecExpr(Operands, L);
1756 AllInvariant = true;
1757 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1758 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1759 AllInvariant = false;
1760 break;
1761 }
1762 if (AllInvariant)
1763 // Ok, both add recurrences are valid after the transformation.
1764 return getAddRecExpr(NestedOperands, NestedLoop);
1765 }
1766 // Reset Operands to its original state.
1767 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001768 }
1769 }
1770
Dan Gohman1c343752009-06-27 21:21:31 +00001771 FoldingSetNodeID ID;
1772 ID.AddInteger(scAddRecExpr);
1773 ID.AddInteger(Operands.size());
1774 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1775 ID.AddPointer(Operands[i]);
1776 ID.AddPointer(L);
1777 void *IP = 0;
1778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1779 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1780 new (S) SCEVAddRecExpr(Operands, L);
1781 UniqueSCEVs.InsertNode(S, IP);
1782 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001783}
1784
Dan Gohman9311ef62009-06-24 14:49:00 +00001785const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1786 const SCEV *RHS) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001787 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001788 Ops.push_back(LHS);
1789 Ops.push_back(RHS);
1790 return getSMaxExpr(Ops);
1791}
1792
Owen Anderson372b46c2009-06-22 21:39:50 +00001793const SCEV*
1794ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001795 assert(!Ops.empty() && "Cannot get empty smax!");
1796 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001797#ifndef NDEBUG
1798 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1799 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1800 getEffectiveSCEVType(Ops[0]->getType()) &&
1801 "SCEVSMaxExpr operand types don't match!");
1802#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001803
1804 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001805 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001806
1807 // If there are any constants, fold them together.
1808 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001809 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001810 ++Idx;
1811 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001812 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001813 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001814 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001815 APIntOps::smax(LHSC->getValue()->getValue(),
1816 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001817 Ops[0] = getConstant(Fold);
1818 Ops.erase(Ops.begin()+1); // Erase the folded element
1819 if (Ops.size() == 1) return Ops[0];
1820 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001821 }
1822
Dan Gohmane5aceed2009-06-24 14:46:22 +00001823 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001824 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1825 Ops.erase(Ops.begin());
1826 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001827 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1828 // If we have an smax with a constant maximum-int, it will always be
1829 // maximum-int.
1830 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001831 }
1832 }
1833
1834 if (Ops.size() == 1) return Ops[0];
1835
1836 // Find the first SMax
1837 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1838 ++Idx;
1839
1840 // Check to see if one of the operands is an SMax. If so, expand its operands
1841 // onto our operand list, and recurse to simplify.
1842 if (Idx < Ops.size()) {
1843 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001844 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001845 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1846 Ops.erase(Ops.begin()+Idx);
1847 DeletedSMax = true;
1848 }
1849
1850 if (DeletedSMax)
1851 return getSMaxExpr(Ops);
1852 }
1853
1854 // Okay, check to see if the same value occurs in the operand list twice. If
1855 // so, delete one. Since we sorted the list, these values are required to
1856 // be adjacent.
1857 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1858 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1859 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1860 --i; --e;
1861 }
1862
1863 if (Ops.size() == 1) return Ops[0];
1864
1865 assert(!Ops.empty() && "Reduced smax down to nothing!");
1866
Nick Lewycky3e630762008-02-20 06:48:22 +00001867 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001868 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001869 FoldingSetNodeID ID;
1870 ID.AddInteger(scSMaxExpr);
1871 ID.AddInteger(Ops.size());
1872 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1873 ID.AddPointer(Ops[i]);
1874 void *IP = 0;
1875 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1876 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1877 new (S) SCEVSMaxExpr(Ops);
1878 UniqueSCEVs.InsertNode(S, IP);
1879 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001880}
1881
Dan Gohman9311ef62009-06-24 14:49:00 +00001882const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1883 const SCEV *RHS) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001884 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001885 Ops.push_back(LHS);
1886 Ops.push_back(RHS);
1887 return getUMaxExpr(Ops);
1888}
1889
Owen Anderson372b46c2009-06-22 21:39:50 +00001890const SCEV*
1891ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001892 assert(!Ops.empty() && "Cannot get empty umax!");
1893 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001894#ifndef NDEBUG
1895 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1896 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1897 getEffectiveSCEVType(Ops[0]->getType()) &&
1898 "SCEVUMaxExpr operand types don't match!");
1899#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001900
1901 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001902 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001903
1904 // If there are any constants, fold them together.
1905 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001906 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001907 ++Idx;
1908 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001909 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001910 // We found two constants, fold them together!
1911 ConstantInt *Fold = ConstantInt::get(
1912 APIntOps::umax(LHSC->getValue()->getValue(),
1913 RHSC->getValue()->getValue()));
1914 Ops[0] = getConstant(Fold);
1915 Ops.erase(Ops.begin()+1); // Erase the folded element
1916 if (Ops.size() == 1) return Ops[0];
1917 LHSC = cast<SCEVConstant>(Ops[0]);
1918 }
1919
Dan Gohmane5aceed2009-06-24 14:46:22 +00001920 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001921 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1922 Ops.erase(Ops.begin());
1923 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001924 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1925 // If we have an umax with a constant maximum-int, it will always be
1926 // maximum-int.
1927 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001928 }
1929 }
1930
1931 if (Ops.size() == 1) return Ops[0];
1932
1933 // Find the first UMax
1934 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1935 ++Idx;
1936
1937 // Check to see if one of the operands is a UMax. If so, expand its operands
1938 // onto our operand list, and recurse to simplify.
1939 if (Idx < Ops.size()) {
1940 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001941 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001942 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1943 Ops.erase(Ops.begin()+Idx);
1944 DeletedUMax = true;
1945 }
1946
1947 if (DeletedUMax)
1948 return getUMaxExpr(Ops);
1949 }
1950
1951 // Okay, check to see if the same value occurs in the operand list twice. If
1952 // so, delete one. Since we sorted the list, these values are required to
1953 // be adjacent.
1954 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1955 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1956 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1957 --i; --e;
1958 }
1959
1960 if (Ops.size() == 1) return Ops[0];
1961
1962 assert(!Ops.empty() && "Reduced umax down to nothing!");
1963
1964 // Okay, it looks like we really DO need a umax expr. Check to see if we
1965 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001966 FoldingSetNodeID ID;
1967 ID.AddInteger(scUMaxExpr);
1968 ID.AddInteger(Ops.size());
1969 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1970 ID.AddPointer(Ops[i]);
1971 void *IP = 0;
1972 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1973 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1974 new (S) SCEVUMaxExpr(Ops);
1975 UniqueSCEVs.InsertNode(S, IP);
1976 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00001977}
1978
Dan Gohman9311ef62009-06-24 14:49:00 +00001979const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1980 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001981 // ~smax(~x, ~y) == smin(x, y).
1982 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1983}
1984
Dan Gohman9311ef62009-06-24 14:49:00 +00001985const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1986 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001987 // ~umax(~x, ~y) == umin(x, y)
1988 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1989}
1990
Owen Anderson372b46c2009-06-22 21:39:50 +00001991const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00001992 // Don't attempt to do anything other than create a SCEVUnknown object
1993 // here. createSCEV only calls getUnknown after checking for all other
1994 // interesting possibilities, and any other code that calls getUnknown
1995 // is doing so in order to hide a value from SCEV canonicalization.
1996
Dan Gohman1c343752009-06-27 21:21:31 +00001997 FoldingSetNodeID ID;
1998 ID.AddInteger(scUnknown);
1999 ID.AddPointer(V);
2000 void *IP = 0;
2001 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2002 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2003 new (S) SCEVUnknown(V);
2004 UniqueSCEVs.InsertNode(S, IP);
2005 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002006}
2007
Chris Lattner53e677a2004-04-02 20:23:17 +00002008//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002009// Basic SCEV Analysis and PHI Idiom Recognition Code
2010//
2011
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002012/// isSCEVable - Test if values of the given type are analyzable within
2013/// the SCEV framework. This primarily includes integer types, and it
2014/// can optionally include pointer types if the ScalarEvolution class
2015/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002016bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002017 // Integers are always SCEVable.
2018 if (Ty->isInteger())
2019 return true;
2020
2021 // Pointers are SCEVable if TargetData information is available
2022 // to provide pointer size information.
2023 if (isa<PointerType>(Ty))
2024 return TD != NULL;
2025
2026 // Otherwise it's not SCEVable.
2027 return false;
2028}
2029
2030/// getTypeSizeInBits - Return the size in bits of the specified type,
2031/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002032uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002033 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2034
2035 // If we have a TargetData, use it!
2036 if (TD)
2037 return TD->getTypeSizeInBits(Ty);
2038
2039 // Otherwise, we support only integer types.
2040 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2041 return Ty->getPrimitiveSizeInBits();
2042}
2043
2044/// getEffectiveSCEVType - Return a type with the same bitwidth as
2045/// the given type and which represents how SCEV will treat the given
2046/// type, for which isSCEVable must return true. For pointer types,
2047/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002048const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002049 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2050
2051 if (Ty->isInteger())
2052 return Ty;
2053
2054 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2055 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002056}
Chris Lattner53e677a2004-04-02 20:23:17 +00002057
Owen Anderson372b46c2009-06-22 21:39:50 +00002058const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002059 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002060}
2061
Dan Gohman92fa56e2009-05-04 22:20:30 +00002062/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00002063/// computed.
2064bool ScalarEvolution::hasSCEV(Value *V) const {
2065 return Scalars.count(V);
2066}
2067
Chris Lattner53e677a2004-04-02 20:23:17 +00002068/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2069/// expression and create a new one.
Owen Anderson372b46c2009-06-22 21:39:50 +00002070const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002071 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002072
Owen Anderson372b46c2009-06-22 21:39:50 +00002073 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002074 if (I != Scalars.end()) return I->second;
Owen Anderson372b46c2009-06-22 21:39:50 +00002075 const SCEV* S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002076 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002077 return S;
2078}
2079
Dan Gohman6bbcba12009-06-24 00:54:57 +00002080/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002081/// specified signed integer value and return a SCEV for the constant.
Owen Anderson372b46c2009-06-22 21:39:50 +00002082const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002083 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2084 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002085}
2086
2087/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2088///
Owen Anderson372b46c2009-06-22 21:39:50 +00002089const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002090 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanb8be8b72009-06-24 00:38:39 +00002091 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002092
2093 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002094 Ty = getEffectiveSCEVType(Ty);
2095 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002096}
2097
2098/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Anderson372b46c2009-06-22 21:39:50 +00002099const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002100 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanb8be8b72009-06-24 00:38:39 +00002101 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002102
2103 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002104 Ty = getEffectiveSCEVType(Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +00002105 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00002106 return getMinusSCEV(AllOnes, V);
2107}
2108
2109/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2110///
Dan Gohman9311ef62009-06-24 14:49:00 +00002111const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2112 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002113 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002114 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002115}
2116
2117/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2118/// input value to the specified type. If the type must be extended, it is zero
2119/// extended.
Owen Anderson372b46c2009-06-22 21:39:50 +00002120const SCEV*
2121ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002122 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002123 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002124 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2125 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002126 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002127 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002128 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002129 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002130 return getTruncateExpr(V, Ty);
2131 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002132}
2133
2134/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2135/// input value to the specified type. If the type must be extended, it is sign
2136/// extended.
Owen Anderson372b46c2009-06-22 21:39:50 +00002137const SCEV*
2138ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002139 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002140 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002141 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2142 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002143 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002144 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002145 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002146 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002147 return getTruncateExpr(V, Ty);
2148 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002149}
2150
Dan Gohman467c4302009-05-13 03:46:30 +00002151/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2152/// input value to the specified type. If the type must be extended, it is zero
2153/// extended. The conversion must not be narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002154const SCEV*
2155ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002156 const Type *SrcTy = V->getType();
2157 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2158 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2159 "Cannot noop or zero extend with non-integer arguments!");
2160 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2161 "getNoopOrZeroExtend cannot truncate!");
2162 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2163 return V; // No conversion
2164 return getZeroExtendExpr(V, Ty);
2165}
2166
2167/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2168/// input value to the specified type. If the type must be extended, it is sign
2169/// extended. The conversion must not be narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002170const SCEV*
2171ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002172 const Type *SrcTy = V->getType();
2173 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2174 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2175 "Cannot noop or sign extend with non-integer arguments!");
2176 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2177 "getNoopOrSignExtend cannot truncate!");
2178 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2179 return V; // No conversion
2180 return getSignExtendExpr(V, Ty);
2181}
2182
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002183/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2184/// the input value to the specified type. If the type must be extended,
2185/// it is extended with unspecified bits. The conversion must not be
2186/// narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002187const SCEV*
2188ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002189 const Type *SrcTy = V->getType();
2190 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2191 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2192 "Cannot noop or any extend with non-integer arguments!");
2193 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2194 "getNoopOrAnyExtend cannot truncate!");
2195 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2196 return V; // No conversion
2197 return getAnyExtendExpr(V, Ty);
2198}
2199
Dan Gohman467c4302009-05-13 03:46:30 +00002200/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2201/// input value to the specified type. The conversion must not be widening.
Owen Anderson372b46c2009-06-22 21:39:50 +00002202const SCEV*
2203ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002204 const Type *SrcTy = V->getType();
2205 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2206 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2207 "Cannot truncate or noop with non-integer arguments!");
2208 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2209 "getTruncateOrNoop cannot extend!");
2210 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2211 return V; // No conversion
2212 return getTruncateExpr(V, Ty);
2213}
2214
Dan Gohmana334aa72009-06-22 00:31:57 +00002215/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2216/// the types using zero-extension, and then perform a umax operation
2217/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002218const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2219 const SCEV *RHS) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002220 const SCEV* PromotedLHS = LHS;
2221 const SCEV* PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002222
2223 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2224 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2225 else
2226 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2227
2228 return getUMaxExpr(PromotedLHS, PromotedRHS);
2229}
2230
Dan Gohmanc9759e82009-06-22 15:03:27 +00002231/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2232/// the types using zero-extension, and then perform a umin operation
2233/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002234const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2235 const SCEV *RHS) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002236 const SCEV* PromotedLHS = LHS;
2237 const SCEV* PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002238
2239 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2240 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2241 else
2242 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2243
2244 return getUMinExpr(PromotedLHS, PromotedRHS);
2245}
2246
Chris Lattner4dc534c2005-02-13 04:37:18 +00002247/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2248/// the specified instruction and replaces any references to the symbolic value
2249/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002250void
2251ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2252 const SCEV *SymName,
2253 const SCEV *NewVal) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002254 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002255 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002256 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002257
Owen Anderson372b46c2009-06-22 21:39:50 +00002258 const SCEV* NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002259 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002260 if (NV == SI->second) return; // No change.
2261
2262 SI->second = NV; // Update the scalars map!
2263
2264 // Any instruction values that use this instruction might also need to be
2265 // updated!
2266 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2267 UI != E; ++UI)
2268 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2269}
Chris Lattner53e677a2004-04-02 20:23:17 +00002270
2271/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2272/// a loop header, making it a potential recurrence, or it doesn't.
2273///
Owen Anderson372b46c2009-06-22 21:39:50 +00002274const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002275 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002276 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002277 if (L->getHeader() == PN->getParent()) {
2278 // If it lives in the loop header, it has two incoming values, one
2279 // from outside the loop, and one from inside.
2280 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2281 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002282
Chris Lattner53e677a2004-04-02 20:23:17 +00002283 // While we are analyzing this PHI node, handle its value symbolically.
Owen Anderson372b46c2009-06-22 21:39:50 +00002284 const SCEV* SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002285 assert(Scalars.find(PN) == Scalars.end() &&
2286 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002287 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002288
2289 // Using this symbolic name for the PHI, analyze the value coming around
2290 // the back-edge.
Owen Anderson372b46c2009-06-22 21:39:50 +00002291 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002292
2293 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2294 // has a special value for the first iteration of the loop.
2295
2296 // If the value coming around the backedge is an add with the symbolic
2297 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002298 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002299 // If there is a single occurrence of the symbolic value, replace it
2300 // with a recurrence.
2301 unsigned FoundIndex = Add->getNumOperands();
2302 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2303 if (Add->getOperand(i) == SymbolicName)
2304 if (FoundIndex == e) {
2305 FoundIndex = i;
2306 break;
2307 }
2308
2309 if (FoundIndex != Add->getNumOperands()) {
2310 // Create an add with everything but the specified operand.
Owen Anderson372b46c2009-06-22 21:39:50 +00002311 SmallVector<const SCEV*, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002312 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2313 if (i != FoundIndex)
2314 Ops.push_back(Add->getOperand(i));
Owen Anderson372b46c2009-06-22 21:39:50 +00002315 const SCEV* Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002316
2317 // This is not a valid addrec if the step amount is varying each
2318 // loop iteration, but is not itself an addrec in this loop.
2319 if (Accum->isLoopInvariant(L) ||
2320 (isa<SCEVAddRecExpr>(Accum) &&
2321 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002322 const SCEV *StartVal =
2323 getSCEV(PN->getIncomingValue(IncomingEdge));
2324 const SCEV *PHISCEV =
2325 getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002326
2327 // Okay, for the entire analysis of this edge we assumed the PHI
2328 // to be symbolic. We now need to go back and update all of the
2329 // entries for the scalars that use the PHI (except for the PHI
2330 // itself) to use the new analyzed value instead of the "symbolic"
2331 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002332 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002333 return PHISCEV;
2334 }
2335 }
Dan Gohman622ed672009-05-04 22:02:23 +00002336 } else if (const SCEVAddRecExpr *AddRec =
2337 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002338 // Otherwise, this could be a loop like this:
2339 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2340 // In this case, j = {1,+,1} and BEValue is j.
2341 // Because the other in-value of i (0) fits the evolution of BEValue
2342 // i really is an addrec evolution.
2343 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002344 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002345
2346 // If StartVal = j.start - j.stride, we can use StartVal as the
2347 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002348 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002349 AddRec->getOperand(1))) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002350 const SCEV* PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002351 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002352
2353 // Okay, for the entire analysis of this edge we assumed the PHI
2354 // to be symbolic. We now need to go back and update all of the
2355 // entries for the scalars that use the PHI (except for the PHI
2356 // itself) to use the new analyzed value instead of the "symbolic"
2357 // value.
2358 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2359 return PHISCEV;
2360 }
2361 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002362 }
2363
2364 return SymbolicName;
2365 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002366
Chris Lattner53e677a2004-04-02 20:23:17 +00002367 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002368 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002369}
2370
Dan Gohman26466c02009-05-08 20:26:55 +00002371/// createNodeForGEP - Expand GEP instructions into add and multiply
2372/// operations. This allows them to be analyzed by regular SCEV code.
2373///
Owen Anderson372b46c2009-06-22 21:39:50 +00002374const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002375
2376 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002377 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002378 // Don't attempt to analyze GEPs over unsized objects.
2379 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2380 return getUnknown(GEP);
Owen Anderson372b46c2009-06-22 21:39:50 +00002381 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002382 gep_type_iterator GTI = gep_type_begin(GEP);
2383 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2384 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002385 I != E; ++I) {
2386 Value *Index = *I;
2387 // Compute the (potentially symbolic) offset in bytes for this index.
2388 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2389 // For a struct, add the member offset.
2390 const StructLayout &SL = *TD->getStructLayout(STy);
2391 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2392 uint64_t Offset = SL.getElementOffset(FieldNo);
2393 TotalOffset = getAddExpr(TotalOffset,
2394 getIntegerSCEV(Offset, IntPtrTy));
2395 } else {
2396 // For an array, add the element offset, explicitly scaled.
Owen Anderson372b46c2009-06-22 21:39:50 +00002397 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002398 if (!isa<PointerType>(LocalOffset->getType()))
2399 // Getelementptr indicies are signed.
2400 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2401 IntPtrTy);
2402 LocalOffset =
2403 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002404 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002405 IntPtrTy));
2406 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2407 }
2408 }
2409 return getAddExpr(getSCEV(Base), TotalOffset);
2410}
2411
Nick Lewycky83bb0052007-11-22 07:59:40 +00002412/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2413/// guaranteed to end in (at every loop iteration). It is, at the same time,
2414/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2415/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002416uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002417ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002418 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002419 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002420
Dan Gohman622ed672009-05-04 22:02:23 +00002421 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002422 return std::min(GetMinTrailingZeros(T->getOperand()),
2423 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002424
Dan Gohman622ed672009-05-04 22:02:23 +00002425 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002426 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2427 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2428 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002429 }
2430
Dan Gohman622ed672009-05-04 22:02:23 +00002431 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002432 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2433 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2434 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002435 }
2436
Dan Gohman622ed672009-05-04 22:02:23 +00002437 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002438 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002439 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002440 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002441 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002442 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002443 }
2444
Dan Gohman622ed672009-05-04 22:02:23 +00002445 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002446 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002447 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2448 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002449 for (unsigned i = 1, e = M->getNumOperands();
2450 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002451 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002452 BitWidth);
2453 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002454 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002455
Dan Gohman622ed672009-05-04 22:02:23 +00002456 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002457 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002458 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002459 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002460 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002461 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002462 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002463
Dan Gohman622ed672009-05-04 22:02:23 +00002464 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002465 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002466 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002467 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002468 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002469 return MinOpRes;
2470 }
2471
Dan Gohman622ed672009-05-04 22:02:23 +00002472 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002473 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002474 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002475 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002476 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002477 return MinOpRes;
2478 }
2479
Dan Gohman2c364ad2009-06-19 23:29:04 +00002480 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2481 // For a SCEVUnknown, ask ValueTracking.
2482 unsigned BitWidth = getTypeSizeInBits(U->getType());
2483 APInt Mask = APInt::getAllOnesValue(BitWidth);
2484 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2485 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2486 return Zeros.countTrailingOnes();
2487 }
2488
2489 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002490 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002491}
Chris Lattner53e677a2004-04-02 20:23:17 +00002492
Dan Gohman2c364ad2009-06-19 23:29:04 +00002493uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002494ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002495 // TODO: Handle other SCEV expression types here.
2496
2497 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2498 return C->getValue()->getValue().countLeadingZeros();
2499
2500 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2501 // A zero-extension cast adds zero bits.
2502 return GetMinLeadingZeros(C->getOperand()) +
2503 (getTypeSizeInBits(C->getType()) -
2504 getTypeSizeInBits(C->getOperand()->getType()));
2505 }
2506
2507 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2508 // For a SCEVUnknown, ask ValueTracking.
2509 unsigned BitWidth = getTypeSizeInBits(U->getType());
2510 APInt Mask = APInt::getAllOnesValue(BitWidth);
2511 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2512 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2513 return Zeros.countLeadingOnes();
2514 }
2515
2516 return 1;
2517}
2518
2519uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002520ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002521 // TODO: Handle other SCEV expression types here.
2522
2523 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2524 const APInt &A = C->getValue()->getValue();
2525 return A.isNegative() ? A.countLeadingOnes() :
2526 A.countLeadingZeros();
2527 }
2528
2529 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2530 // A sign-extension cast adds sign bits.
2531 return GetMinSignBits(C->getOperand()) +
2532 (getTypeSizeInBits(C->getType()) -
2533 getTypeSizeInBits(C->getOperand()->getType()));
2534 }
2535
Dan Gohman62849c02009-06-24 01:05:09 +00002536 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2537 unsigned BitWidth = getTypeSizeInBits(A->getType());
2538
2539 // Special case decrementing a value (ADD X, -1):
2540 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2541 if (CRHS->isAllOnesValue()) {
2542 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2543 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2544 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2545
2546 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2547 // sign bits set.
2548 if (LZ == BitWidth - 1)
2549 return BitWidth;
2550
2551 // If we are subtracting one from a positive number, there is no carry
2552 // out of the result.
2553 if (LZ > 0)
2554 return GetMinSignBits(OtherOpsAdd);
2555 }
2556
2557 // Add can have at most one carry bit. Thus we know that the output
2558 // is, at worst, one more bit than the inputs.
2559 unsigned Min = BitWidth;
2560 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2561 unsigned N = GetMinSignBits(A->getOperand(i));
2562 Min = std::min(Min, N) - 1;
2563 if (Min == 0) return 1;
2564 }
2565 return 1;
2566 }
2567
Dan Gohman2c364ad2009-06-19 23:29:04 +00002568 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2569 // For a SCEVUnknown, ask ValueTracking.
2570 return ComputeNumSignBits(U->getValue(), TD);
2571 }
2572
2573 return 1;
2574}
2575
Chris Lattner53e677a2004-04-02 20:23:17 +00002576/// createSCEV - We know that there is no SCEV for the specified value.
2577/// Analyze the expression.
2578///
Owen Anderson372b46c2009-06-22 21:39:50 +00002579const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002580 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002581 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002582
Dan Gohman6c459a22008-06-22 19:56:46 +00002583 unsigned Opcode = Instruction::UserOp1;
2584 if (Instruction *I = dyn_cast<Instruction>(V))
2585 Opcode = I->getOpcode();
2586 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2587 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002588 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2589 return getConstant(CI);
2590 else if (isa<ConstantPointerNull>(V))
2591 return getIntegerSCEV(0, V->getType());
2592 else if (isa<UndefValue>(V))
2593 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002594 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002595 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002596
Dan Gohman6c459a22008-06-22 19:56:46 +00002597 User *U = cast<User>(V);
2598 switch (Opcode) {
2599 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002600 return getAddExpr(getSCEV(U->getOperand(0)),
2601 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002602 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002603 return getMulExpr(getSCEV(U->getOperand(0)),
2604 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002605 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002606 return getUDivExpr(getSCEV(U->getOperand(0)),
2607 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002608 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002609 return getMinusSCEV(getSCEV(U->getOperand(0)),
2610 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002611 case Instruction::And:
2612 // For an expression like x&255 that merely masks off the high bits,
2613 // use zext(trunc(x)) as the SCEV expression.
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002615 if (CI->isNullValue())
2616 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002617 if (CI->isAllOnesValue())
2618 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002619 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002620
2621 // Instcombine's ShrinkDemandedConstant may strip bits out of
2622 // constants, obscuring what would otherwise be a low-bits mask.
2623 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2624 // knew about to reconstruct a low-bits mask value.
2625 unsigned LZ = A.countLeadingZeros();
2626 unsigned BitWidth = A.getBitWidth();
2627 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2628 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2629 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2630
2631 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2632
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002633 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002634 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002635 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002636 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002637 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002638 }
2639 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002640
Dan Gohman6c459a22008-06-22 19:56:46 +00002641 case Instruction::Or:
2642 // If the RHS of the Or is a constant, we may have something like:
2643 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2644 // optimizations will transparently handle this case.
2645 //
2646 // In order for this transformation to be safe, the LHS must be of the
2647 // form X*(2^n) and the Or constant must be less than 2^n.
2648 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002649 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002650 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002651 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002652 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002653 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002654 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002655 break;
2656 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002657 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002658 // If the RHS of the xor is a signbit, then this is just an add.
2659 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002660 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002661 return getAddExpr(getSCEV(U->getOperand(0)),
2662 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002663
2664 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002665 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002666 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002667
2668 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2669 // This is a variant of the check for xor with -1, and it handles
2670 // the case where instcombine has trimmed non-demanded bits out
2671 // of an xor with -1.
2672 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2673 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2674 if (BO->getOpcode() == Instruction::And &&
2675 LCI->getValue() == CI->getValue())
2676 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002677 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002678 const Type *UTy = U->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00002679 const SCEV* Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002680 const Type *Z0Ty = Z0->getType();
2681 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2682
2683 // If C is a low-bits mask, the zero extend is zerving to
2684 // mask off the high bits. Complement the operand and
2685 // re-apply the zext.
2686 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2687 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2688
2689 // If C is a single bit, it may be in the sign-bit position
2690 // before the zero-extend. In this case, represent the xor
2691 // using an add, which is equivalent, and re-apply the zext.
2692 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2693 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2694 Trunc.isSignBit())
2695 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2696 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002697 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002698 }
2699 break;
2700
2701 case Instruction::Shl:
2702 // Turn shift left of a constant amount into a multiply.
2703 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2704 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2705 Constant *X = ConstantInt::get(
2706 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002707 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002708 }
2709 break;
2710
Nick Lewycky01eaf802008-07-07 06:15:49 +00002711 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002712 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002713 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2714 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2715 Constant *X = ConstantInt::get(
2716 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002717 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002718 }
2719 break;
2720
Dan Gohman4ee29af2009-04-21 02:26:00 +00002721 case Instruction::AShr:
2722 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2723 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2724 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2725 if (L->getOpcode() == Instruction::Shl &&
2726 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002727 unsigned BitWidth = getTypeSizeInBits(U->getType());
2728 uint64_t Amt = BitWidth - CI->getZExtValue();
2729 if (Amt == BitWidth)
2730 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2731 if (Amt > BitWidth)
2732 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002733 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002734 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002735 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002736 U->getType());
2737 }
2738 break;
2739
Dan Gohman6c459a22008-06-22 19:56:46 +00002740 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002741 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002742
2743 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002744 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002745
2746 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002747 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002748
2749 case Instruction::BitCast:
2750 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002751 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002752 return getSCEV(U->getOperand(0));
2753 break;
2754
Dan Gohman2d1be872009-04-16 03:18:22 +00002755 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002756 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002757 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002758 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002759
2760 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002761 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002762 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2763 U->getType());
2764
Dan Gohman26466c02009-05-08 20:26:55 +00002765 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002766 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002767 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002768
Dan Gohman6c459a22008-06-22 19:56:46 +00002769 case Instruction::PHI:
2770 return createNodeForPHI(cast<PHINode>(U));
2771
2772 case Instruction::Select:
2773 // This could be a smax or umax that was lowered earlier.
2774 // Try to recover it.
2775 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2776 Value *LHS = ICI->getOperand(0);
2777 Value *RHS = ICI->getOperand(1);
2778 switch (ICI->getPredicate()) {
2779 case ICmpInst::ICMP_SLT:
2780 case ICmpInst::ICMP_SLE:
2781 std::swap(LHS, RHS);
2782 // fall through
2783 case ICmpInst::ICMP_SGT:
2784 case ICmpInst::ICMP_SGE:
2785 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002786 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002787 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002788 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002789 break;
2790 case ICmpInst::ICMP_ULT:
2791 case ICmpInst::ICMP_ULE:
2792 std::swap(LHS, RHS);
2793 // fall through
2794 case ICmpInst::ICMP_UGT:
2795 case ICmpInst::ICMP_UGE:
2796 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002797 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002798 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002799 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002800 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002801 case ICmpInst::ICMP_NE:
2802 // n != 0 ? n : 1 -> umax(n, 1)
2803 if (LHS == U->getOperand(1) &&
2804 isa<ConstantInt>(U->getOperand(2)) &&
2805 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2806 isa<ConstantInt>(RHS) &&
2807 cast<ConstantInt>(RHS)->isZero())
2808 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2809 break;
2810 case ICmpInst::ICMP_EQ:
2811 // n == 0 ? 1 : n -> umax(n, 1)
2812 if (LHS == U->getOperand(2) &&
2813 isa<ConstantInt>(U->getOperand(1)) &&
2814 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2815 isa<ConstantInt>(RHS) &&
2816 cast<ConstantInt>(RHS)->isZero())
2817 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2818 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002819 default:
2820 break;
2821 }
2822 }
2823
2824 default: // We cannot analyze this expression.
2825 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002826 }
2827
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002828 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002829}
2830
2831
2832
2833//===----------------------------------------------------------------------===//
2834// Iteration Count Computation Code
2835//
2836
Dan Gohman46bdfb02009-02-24 18:55:53 +00002837/// getBackedgeTakenCount - If the specified loop has a predictable
2838/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2839/// object. The backedge-taken count is the number of times the loop header
2840/// will be branched to from within the loop. This is one less than the
2841/// trip count of the loop, since it doesn't count the first iteration,
2842/// when the header is branched to from outside the loop.
2843///
2844/// Note that it is not valid to call this method on a loop without a
2845/// loop-invariant backedge-taken count (see
2846/// hasLoopInvariantBackedgeTakenCount).
2847///
Owen Anderson372b46c2009-06-22 21:39:50 +00002848const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002849 return getBackedgeTakenInfo(L).Exact;
2850}
2851
2852/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2853/// return the least SCEV value that is known never to be less than the
2854/// actual backedge taken count.
Owen Anderson372b46c2009-06-22 21:39:50 +00002855const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002856 return getBackedgeTakenInfo(L).Max;
2857}
2858
2859const ScalarEvolution::BackedgeTakenInfo &
2860ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002861 // Initially insert a CouldNotCompute for this loop. If the insertion
2862 // succeeds, procede to actually compute a backedge-taken count and
2863 // update the value. The temporary CouldNotCompute value tells SCEV
2864 // code elsewhere that it shouldn't attempt to request a new
2865 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002866 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002867 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2868 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002869 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00002870 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002871 assert(ItCount.Exact->isLoopInvariant(L) &&
2872 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002873 "Computed trip count isn't loop invariant for loop!");
2874 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002875
Dan Gohman01ecca22009-04-27 20:16:15 +00002876 // Update the value in the map.
2877 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00002878 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00002879 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00002880 // Update the value in the map.
2881 Pair.first->second = ItCount;
2882 if (isa<PHINode>(L->getHeader()->begin()))
2883 // Only count loops that have phi nodes as not being computable.
2884 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00002885 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002886
2887 // Now that we know more about the trip count for this loop, forget any
2888 // existing SCEV values for PHI nodes in this loop since they are only
2889 // conservative estimates made without the benefit
2890 // of trip count information.
2891 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002892 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002893 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002894 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002895}
2896
Dan Gohman46bdfb02009-02-24 18:55:53 +00002897/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002898/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002899/// ScalarEvolution's ability to compute a trip count, or if the loop
2900/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002901void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002902 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002903 forgetLoopPHIs(L);
2904}
2905
2906/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2907/// PHI nodes in the given loop. This is used when the trip count of
2908/// the loop may have changed.
2909void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002910 BasicBlock *Header = L->getHeader();
2911
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002912 // Push all Loop-header PHIs onto the Worklist stack, except those
2913 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2914 // a PHI either means that it has an unrecognized structure, or it's
2915 // a PHI that's in the progress of being computed by createNodeForPHI.
2916 // In the former case, additional loop trip count information isn't
2917 // going to change anything. In the later case, createNodeForPHI will
2918 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002919 SmallVector<Instruction *, 16> Worklist;
2920 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002921 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002922 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2923 Scalars.find((Value*)I);
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002924 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2925 Worklist.push_back(PN);
2926 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002927
2928 while (!Worklist.empty()) {
2929 Instruction *I = Worklist.pop_back_val();
2930 if (Scalars.erase(I))
2931 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2932 UI != UE; ++UI)
2933 Worklist.push_back(cast<Instruction>(UI));
2934 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002935}
2936
Dan Gohman46bdfb02009-02-24 18:55:53 +00002937/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2938/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002939ScalarEvolution::BackedgeTakenInfo
2940ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002941 SmallVector<BasicBlock*, 8> ExitingBlocks;
2942 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00002943
Dan Gohmana334aa72009-06-22 00:31:57 +00002944 // Examine all exits and pick the most conservative values.
Dan Gohman1c343752009-06-27 21:21:31 +00002945 const SCEV* BECount = getCouldNotCompute();
2946 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00002947 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00002948 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2949 BackedgeTakenInfo NewBTI =
2950 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00002951
Dan Gohman1c343752009-06-27 21:21:31 +00002952 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002953 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002954 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002955 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00002956 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00002957 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00002958 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00002959 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00002960 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00002961 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002962 }
Dan Gohman1c343752009-06-27 21:21:31 +00002963 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00002964 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00002965 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00002966 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002967 }
2968
2969 return BackedgeTakenInfo(BECount, MaxBECount);
2970}
2971
2972/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2973/// of the specified loop will execute if it exits via the specified block.
2974ScalarEvolution::BackedgeTakenInfo
2975ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2976 BasicBlock *ExitingBlock) {
2977
2978 // Okay, we've chosen an exiting block. See what condition causes us to
2979 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00002980 //
2981 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002982 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00002983 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00002984 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00002985
Chris Lattner8b0e3602007-01-07 02:24:26 +00002986 // At this point, we know we have a conditional branch that determines whether
2987 // the loop is exited. However, we don't know if the branch is executed each
2988 // time through the loop. If not, then the execution count of the branch will
2989 // not be equal to the trip count of the loop.
2990 //
2991 // Currently we check for this by checking to see if the Exit branch goes to
2992 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002993 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00002994 // loop header. This is common for un-rotated loops.
2995 //
2996 // If both of those tests fail, walk up the unique predecessor chain to the
2997 // header, stopping if there is an edge that doesn't exit the loop. If the
2998 // header is reached, the execution count of the branch will be equal to the
2999 // trip count of the loop.
3000 //
3001 // More extensive analysis could be done to handle more cases here.
3002 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003003 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003004 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003005 ExitBr->getParent() != L->getHeader()) {
3006 // The simple checks failed, try climbing the unique predecessor chain
3007 // up to the header.
3008 bool Ok = false;
3009 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3010 BasicBlock *Pred = BB->getUniquePredecessor();
3011 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003012 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003013 TerminatorInst *PredTerm = Pred->getTerminator();
3014 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3015 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3016 if (PredSucc == BB)
3017 continue;
3018 // If the predecessor has a successor that isn't BB and isn't
3019 // outside the loop, assume the worst.
3020 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003021 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003022 }
3023 if (Pred == L->getHeader()) {
3024 Ok = true;
3025 break;
3026 }
3027 BB = Pred;
3028 }
3029 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003030 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003031 }
3032
3033 // Procede to the next level to examine the exit condition expression.
3034 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3035 ExitBr->getSuccessor(0),
3036 ExitBr->getSuccessor(1));
3037}
3038
3039/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3040/// backedge of the specified loop will execute if its exit condition
3041/// were a conditional branch of ExitCond, TBB, and FBB.
3042ScalarEvolution::BackedgeTakenInfo
3043ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3044 Value *ExitCond,
3045 BasicBlock *TBB,
3046 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003047 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3049 if (BO->getOpcode() == Instruction::And) {
3050 // Recurse on the operands of the and.
3051 BackedgeTakenInfo BTI0 =
3052 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3053 BackedgeTakenInfo BTI1 =
3054 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman1c343752009-06-27 21:21:31 +00003055 const SCEV* BECount = getCouldNotCompute();
3056 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003057 if (L->contains(TBB)) {
3058 // Both conditions must be true for the loop to continue executing.
3059 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003060 if (BTI0.Exact == getCouldNotCompute() ||
3061 BTI1.Exact == getCouldNotCompute())
3062 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003063 else
3064 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003065 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003066 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003067 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003068 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003069 else
3070 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003071 } else {
3072 // Both conditions must be true for the loop to exit.
3073 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003074 if (BTI0.Exact != getCouldNotCompute() &&
3075 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003076 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003077 if (BTI0.Max != getCouldNotCompute() &&
3078 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003079 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3080 }
3081
3082 return BackedgeTakenInfo(BECount, MaxBECount);
3083 }
3084 if (BO->getOpcode() == Instruction::Or) {
3085 // Recurse on the operands of the or.
3086 BackedgeTakenInfo BTI0 =
3087 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3088 BackedgeTakenInfo BTI1 =
3089 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman1c343752009-06-27 21:21:31 +00003090 const SCEV* BECount = getCouldNotCompute();
3091 const SCEV* MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003092 if (L->contains(FBB)) {
3093 // Both conditions must be false for the loop to continue executing.
3094 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003095 if (BTI0.Exact == getCouldNotCompute() ||
3096 BTI1.Exact == getCouldNotCompute())
3097 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003098 else
3099 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003100 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003101 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003102 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003103 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003104 else
3105 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003106 } else {
3107 // Both conditions must be false for the loop to exit.
3108 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003109 if (BTI0.Exact != getCouldNotCompute() &&
3110 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003111 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003112 if (BTI0.Max != getCouldNotCompute() &&
3113 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003114 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3115 }
3116
3117 return BackedgeTakenInfo(BECount, MaxBECount);
3118 }
3119 }
3120
3121 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3122 // Procede to the next level to examine the icmp.
3123 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3124 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003125
Eli Friedman361e54d2009-05-09 12:32:42 +00003126 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003127 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3128}
3129
3130/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3131/// backedge of the specified loop will execute if its exit condition
3132/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3133ScalarEvolution::BackedgeTakenInfo
3134ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3135 ICmpInst *ExitCond,
3136 BasicBlock *TBB,
3137 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003138
Reid Spencere4d87aa2006-12-23 06:05:41 +00003139 // If the condition was exit on true, convert the condition to exit on false
3140 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003141 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003142 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003143 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003144 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003145
3146 // Handle common loops like: for (X = "string"; *X; ++X)
3147 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3148 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003149 const SCEV* ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003150 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003151 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3152 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3153 return BackedgeTakenInfo(ItCnt,
3154 isa<SCEVConstant>(ItCnt) ? ItCnt :
3155 getConstant(APInt::getMaxValue(BitWidth)-1));
3156 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003157 }
3158
Owen Anderson372b46c2009-06-22 21:39:50 +00003159 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3160 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003161
3162 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003163 LHS = getSCEVAtScope(LHS, L);
3164 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003165
Dan Gohman64a845e2009-06-24 04:48:43 +00003166 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003167 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003168 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3169 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003170 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003171 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003172 }
3173
Chris Lattner53e677a2004-04-02 20:23:17 +00003174 // If we have a comparison of a chrec against a constant, try to use value
3175 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003176 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3177 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003178 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003179 // Form the constant range.
3180 ConstantRange CompRange(
3181 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003182
Owen Anderson372b46c2009-06-22 21:39:50 +00003183 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003184 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003185 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003186
Chris Lattner53e677a2004-04-02 20:23:17 +00003187 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003188 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003189 // Convert to: while (X-Y != 0)
Owen Anderson372b46c2009-06-22 21:39:50 +00003190 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003191 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003192 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003193 }
3194 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003195 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Anderson372b46c2009-06-22 21:39:50 +00003196 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003197 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003198 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003199 }
3200 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003201 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3202 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003203 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003204 }
3205 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003206 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3207 getNotSCEV(RHS), L, true);
3208 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003209 break;
3210 }
3211 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003212 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3213 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003214 break;
3215 }
3216 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003217 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3218 getNotSCEV(RHS), L, false);
3219 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003220 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003221 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003222 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003223#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003224 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003225 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003226 errs() << "[unsigned] ";
3227 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003228 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003229 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003230#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003231 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003232 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003233 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003234 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003235}
3236
Chris Lattner673e02b2004-10-12 01:49:27 +00003237static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003238EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3239 ScalarEvolution &SE) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003240 const SCEV* InVal = SE.getConstant(C);
3241 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003242 assert(isa<SCEVConstant>(Val) &&
3243 "Evaluation of SCEV at constant didn't fold correctly?");
3244 return cast<SCEVConstant>(Val)->getValue();
3245}
3246
3247/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3248/// and a GEP expression (missing the pointer index) indexing into it, return
3249/// the addressed element of the initializer or null if the index expression is
3250/// invalid.
3251static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003252GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003253 const std::vector<ConstantInt*> &Indices) {
3254 Constant *Init = GV->getInitializer();
3255 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003256 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003257 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3258 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3259 Init = cast<Constant>(CS->getOperand(Idx));
3260 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3261 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3262 Init = cast<Constant>(CA->getOperand(Idx));
3263 } else if (isa<ConstantAggregateZero>(Init)) {
3264 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3265 assert(Idx < STy->getNumElements() && "Bad struct index!");
3266 Init = Constant::getNullValue(STy->getElementType(Idx));
3267 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3268 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3269 Init = Constant::getNullValue(ATy->getElementType());
3270 } else {
3271 assert(0 && "Unknown constant aggregate type!");
3272 }
3273 return 0;
3274 } else {
3275 return 0; // Unknown initializer type
3276 }
3277 }
3278 return Init;
3279}
3280
Dan Gohman46bdfb02009-02-24 18:55:53 +00003281/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3282/// 'icmp op load X, cst', try to see if we can compute the backedge
3283/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003284const SCEV *
3285ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3286 LoadInst *LI,
3287 Constant *RHS,
3288 const Loop *L,
3289 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003290 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003291
3292 // Check to see if the loaded pointer is a getelementptr of a global.
3293 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003294 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003295
3296 // Make sure that it is really a constant global we are gepping, with an
3297 // initializer, and make sure the first IDX is really 0.
3298 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3299 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3300 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3301 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003302 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003303
3304 // Okay, we allow one non-constant index into the GEP instruction.
3305 Value *VarIdx = 0;
3306 std::vector<ConstantInt*> Indexes;
3307 unsigned VarIdxNum = 0;
3308 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3309 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3310 Indexes.push_back(CI);
3311 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003312 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003313 VarIdx = GEP->getOperand(i);
3314 VarIdxNum = i-2;
3315 Indexes.push_back(0);
3316 }
3317
3318 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3319 // Check to see if X is a loop variant variable value now.
Owen Anderson372b46c2009-06-22 21:39:50 +00003320 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003321 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003322
3323 // We can only recognize very limited forms of loop index expressions, in
3324 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003325 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003326 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3327 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3328 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003329 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003330
3331 unsigned MaxSteps = MaxBruteForceIterations;
3332 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003333 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003334 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003335 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003336
3337 // Form the GEP offset.
3338 Indexes[VarIdxNum] = Val;
3339
3340 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3341 if (Result == 0) break; // Cannot compute!
3342
3343 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003344 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003345 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003346 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003347#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003348 errs() << "\n***\n*** Computed loop count " << *ItCst
3349 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3350 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003351#endif
3352 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003353 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003354 }
3355 }
Dan Gohman1c343752009-06-27 21:21:31 +00003356 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003357}
3358
3359
Chris Lattner3221ad02004-04-17 22:58:41 +00003360/// CanConstantFold - Return true if we can constant fold an instruction of the
3361/// specified type, assuming that all operands were constants.
3362static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003363 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003364 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3365 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003366
Chris Lattner3221ad02004-04-17 22:58:41 +00003367 if (const CallInst *CI = dyn_cast<CallInst>(I))
3368 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003369 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003370 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003371}
3372
Chris Lattner3221ad02004-04-17 22:58:41 +00003373/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3374/// in the loop that V is derived from. We allow arbitrary operations along the
3375/// way, but the operands of an operation must either be constants or a value
3376/// derived from a constant PHI. If this expression does not fit with these
3377/// constraints, return null.
3378static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3379 // If this is not an instruction, or if this is an instruction outside of the
3380 // loop, it can't be derived from a loop PHI.
3381 Instruction *I = dyn_cast<Instruction>(V);
3382 if (I == 0 || !L->contains(I->getParent())) return 0;
3383
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003384 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003385 if (L->getHeader() == I->getParent())
3386 return PN;
3387 else
3388 // We don't currently keep track of the control flow needed to evaluate
3389 // PHIs, so we cannot handle PHIs inside of loops.
3390 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003391 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003392
3393 // If we won't be able to constant fold this expression even if the operands
3394 // are constants, return early.
3395 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003396
Chris Lattner3221ad02004-04-17 22:58:41 +00003397 // Otherwise, we can evaluate this instruction if all of its operands are
3398 // constant or derived from a PHI node themselves.
3399 PHINode *PHI = 0;
3400 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3401 if (!(isa<Constant>(I->getOperand(Op)) ||
3402 isa<GlobalValue>(I->getOperand(Op)))) {
3403 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3404 if (P == 0) return 0; // Not evolving from PHI
3405 if (PHI == 0)
3406 PHI = P;
3407 else if (PHI != P)
3408 return 0; // Evolving from multiple different PHIs.
3409 }
3410
3411 // This is a expression evolving from a constant PHI!
3412 return PHI;
3413}
3414
3415/// EvaluateExpression - Given an expression that passes the
3416/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3417/// in the loop has the value PHIVal. If we can't fold this expression for some
3418/// reason, return null.
3419static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3420 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003421 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003422 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003423 Instruction *I = cast<Instruction>(V);
Owen Anderson07cf79e2009-07-06 23:00:19 +00003424 LLVMContext *Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003425
3426 std::vector<Constant*> Operands;
3427 Operands.resize(I->getNumOperands());
3428
3429 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3430 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3431 if (Operands[i] == 0) return 0;
3432 }
3433
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003434 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3435 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003436 &Operands[0], Operands.size(),
3437 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003438 else
3439 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003440 &Operands[0], Operands.size(),
3441 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003442}
3443
3444/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3445/// in the header of its containing loop, we know the loop executes a
3446/// constant number of times, and the PHI node is just a recurrence
3447/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003448Constant *
3449ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3450 const APInt& BEs,
3451 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003452 std::map<PHINode*, Constant*>::iterator I =
3453 ConstantEvolutionLoopExitValue.find(PN);
3454 if (I != ConstantEvolutionLoopExitValue.end())
3455 return I->second;
3456
Dan Gohman46bdfb02009-02-24 18:55:53 +00003457 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003458 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3459
3460 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3461
3462 // Since the loop is canonicalized, the PHI node must have two entries. One
3463 // entry must be a constant (coming in from outside of the loop), and the
3464 // second must be derived from the same PHI.
3465 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3466 Constant *StartCST =
3467 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3468 if (StartCST == 0)
3469 return RetVal = 0; // Must be a constant.
3470
3471 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3472 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3473 if (PN2 != PN)
3474 return RetVal = 0; // Not derived from same PHI.
3475
3476 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003477 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003478 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003479
Dan Gohman46bdfb02009-02-24 18:55:53 +00003480 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003481 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003482 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3483 if (IterationNum == NumIterations)
3484 return RetVal = PHIVal; // Got exit value!
3485
3486 // Compute the value of the PHI node for the next iteration.
3487 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3488 if (NextPHI == PHIVal)
3489 return RetVal = NextPHI; // Stopped evolving!
3490 if (NextPHI == 0)
3491 return 0; // Couldn't evaluate!
3492 PHIVal = NextPHI;
3493 }
3494}
3495
Dan Gohman46bdfb02009-02-24 18:55:53 +00003496/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003497/// constant number of times (the condition evolves only from constants),
3498/// try to evaluate a few iterations of the loop until we get the exit
3499/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003500/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003501const SCEV *
3502ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3503 Value *Cond,
3504 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003505 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003506 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003507
3508 // Since the loop is canonicalized, the PHI node must have two entries. One
3509 // entry must be a constant (coming in from outside of the loop), and the
3510 // second must be derived from the same PHI.
3511 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3512 Constant *StartCST =
3513 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003514 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003515
3516 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3517 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003518 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003519
3520 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3521 // the loop symbolically to determine when the condition gets a value of
3522 // "ExitWhen".
3523 unsigned IterationNum = 0;
3524 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3525 for (Constant *PHIVal = StartCST;
3526 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003527 ConstantInt *CondVal =
3528 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003529
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003530 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003531 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003532
Reid Spencere8019bb2007-03-01 07:25:48 +00003533 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003534 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003535 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003536 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003537
Chris Lattner3221ad02004-04-17 22:58:41 +00003538 // Compute the value of the PHI node for the next iteration.
3539 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3540 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003541 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003542 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003543 }
3544
3545 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003546 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003547}
3548
Dan Gohman66a7e852009-05-08 20:38:54 +00003549/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3550/// at the specified scope in the program. The L value specifies a loop
3551/// nest to evaluate the expression at, where null is the top-level or a
3552/// specified loop is immediately inside of the loop.
3553///
3554/// This method can be used to compute the exit value for a variable defined
3555/// in a loop by querying what the value will hold in the parent loop.
3556///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003557/// In the case that a relevant loop exit value cannot be computed, the
3558/// original value V is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00003559const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003560 // FIXME: this should be turned into a virtual method on SCEV!
3561
Chris Lattner3221ad02004-04-17 22:58:41 +00003562 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003563
Nick Lewycky3e630762008-02-20 06:48:22 +00003564 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003565 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003566 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003567 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003568 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003569 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3570 if (PHINode *PN = dyn_cast<PHINode>(I))
3571 if (PN->getParent() == LI->getHeader()) {
3572 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003573 // to see if the loop that contains it has a known backedge-taken
3574 // count. If so, we may be able to force computation of the exit
3575 // value.
Owen Anderson372b46c2009-06-22 21:39:50 +00003576 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003577 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003578 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003579 // Okay, we know how many times the containing loop executes. If
3580 // this is a constant evolving PHI node, get the final value at
3581 // the specified iteration number.
3582 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003583 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003584 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003585 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003586 }
3587 }
3588
Reid Spencer09906f32006-12-04 21:33:23 +00003589 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003590 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003591 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003592 // result. This is particularly useful for computing loop exit values.
3593 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003594 // Check to see if we've folded this instruction at this loop before.
3595 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3596 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3597 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3598 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003599 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003600
Chris Lattner3221ad02004-04-17 22:58:41 +00003601 std::vector<Constant*> Operands;
3602 Operands.reserve(I->getNumOperands());
3603 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3604 Value *Op = I->getOperand(i);
3605 if (Constant *C = dyn_cast<Constant>(Op)) {
3606 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003607 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003608 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003609 // non-integer and non-pointer, don't even try to analyze them
3610 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003611 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003612 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003613
Owen Anderson372b46c2009-06-22 21:39:50 +00003614 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00003615 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003616 Constant *C = SC->getValue();
3617 if (C->getType() != Op->getType())
3618 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3619 Op->getType(),
3620 false),
3621 C, Op->getType());
3622 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003623 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003624 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3625 if (C->getType() != Op->getType())
3626 C =
3627 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3628 Op->getType(),
3629 false),
3630 C, Op->getType());
3631 Operands.push_back(C);
3632 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003633 return V;
3634 } else {
3635 return V;
3636 }
3637 }
3638 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003639
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003640 Constant *C;
3641 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3642 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003643 &Operands[0], Operands.size(),
3644 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003645 else
3646 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003647 &Operands[0], Operands.size(), Context);
Dan Gohman6bce6432009-05-08 20:47:27 +00003648 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003649 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003650 }
3651 }
3652
3653 // This is some other type of SCEVUnknown, just return it.
3654 return V;
3655 }
3656
Dan Gohman622ed672009-05-04 22:02:23 +00003657 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003658 // Avoid performing the look-up in the common case where the specified
3659 // expression has no loop-variant portions.
3660 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003661 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003662 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003663 // Okay, at least one of these operands is loop variant but might be
3664 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00003665 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3666 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003667 NewOps.push_back(OpAtScope);
3668
3669 for (++i; i != e; ++i) {
3670 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003671 NewOps.push_back(OpAtScope);
3672 }
3673 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003674 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003675 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003676 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003677 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003678 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003679 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003680 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003681 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003682 }
3683 }
3684 // If we got here, all operands are loop invariant.
3685 return Comm;
3686 }
3687
Dan Gohman622ed672009-05-04 22:02:23 +00003688 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003689 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3690 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003691 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3692 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003693 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003694 }
3695
3696 // If this is a loop recurrence for a loop that does not contain L, then we
3697 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003698 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003699 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3700 // To evaluate this recurrence, we need to know how many times the AddRec
3701 // loop iterates. Compute this now.
Owen Anderson372b46c2009-06-22 21:39:50 +00003702 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00003703 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003704
Eli Friedmanb42a6262008-08-04 23:49:06 +00003705 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003706 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003707 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003708 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003709 }
3710
Dan Gohman622ed672009-05-04 22:02:23 +00003711 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003712 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003713 if (Op == Cast->getOperand())
3714 return Cast; // must be loop invariant
3715 return getZeroExtendExpr(Op, Cast->getType());
3716 }
3717
Dan Gohman622ed672009-05-04 22:02:23 +00003718 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003719 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003720 if (Op == Cast->getOperand())
3721 return Cast; // must be loop invariant
3722 return getSignExtendExpr(Op, Cast->getType());
3723 }
3724
Dan Gohman622ed672009-05-04 22:02:23 +00003725 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003726 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003727 if (Op == Cast->getOperand())
3728 return Cast; // must be loop invariant
3729 return getTruncateExpr(Op, Cast->getType());
3730 }
3731
3732 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003733 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003734}
3735
Dan Gohman66a7e852009-05-08 20:38:54 +00003736/// getSCEVAtScope - This is a convenience function which does
3737/// getSCEVAtScope(getSCEV(V), L).
Owen Anderson372b46c2009-06-22 21:39:50 +00003738const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003739 return getSCEVAtScope(getSCEV(V), L);
3740}
3741
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003742/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3743/// following equation:
3744///
3745/// A * X = B (mod N)
3746///
3747/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3748/// A and B isn't important.
3749///
3750/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00003751static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003752 ScalarEvolution &SE) {
3753 uint32_t BW = A.getBitWidth();
3754 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3755 assert(A != 0 && "A must be non-zero.");
3756
3757 // 1. D = gcd(A, N)
3758 //
3759 // The gcd of A and N may have only one prime factor: 2. The number of
3760 // trailing zeros in A is its multiplicity
3761 uint32_t Mult2 = A.countTrailingZeros();
3762 // D = 2^Mult2
3763
3764 // 2. Check if B is divisible by D.
3765 //
3766 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3767 // is not less than multiplicity of this prime factor for D.
3768 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003769 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003770
3771 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3772 // modulo (N / D).
3773 //
3774 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3775 // bit width during computations.
3776 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3777 APInt Mod(BW + 1, 0);
3778 Mod.set(BW - Mult2); // Mod = N / D
3779 APInt I = AD.multiplicativeInverse(Mod);
3780
3781 // 4. Compute the minimum unsigned root of the equation:
3782 // I * (B / D) mod (N / D)
3783 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3784
3785 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3786 // bits.
3787 return SE.getConstant(Result.trunc(BW));
3788}
Chris Lattner53e677a2004-04-02 20:23:17 +00003789
3790/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3791/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3792/// might be the same) or two SCEVCouldNotCompute objects.
3793///
Owen Anderson372b46c2009-06-22 21:39:50 +00003794static std::pair<const SCEV*,const SCEV*>
Dan Gohman246b2562007-10-22 18:31:58 +00003795SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003796 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003797 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3798 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3799 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003800
Chris Lattner53e677a2004-04-02 20:23:17 +00003801 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003802 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003803 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003804 return std::make_pair(CNC, CNC);
3805 }
3806
Reid Spencere8019bb2007-03-01 07:25:48 +00003807 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003808 const APInt &L = LC->getValue()->getValue();
3809 const APInt &M = MC->getValue()->getValue();
3810 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003811 APInt Two(BitWidth, 2);
3812 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003813
Dan Gohman64a845e2009-06-24 04:48:43 +00003814 {
Reid Spencere8019bb2007-03-01 07:25:48 +00003815 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003816 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003817 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3818 // The B coefficient is M-N/2
3819 APInt B(M);
3820 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003821
Reid Spencere8019bb2007-03-01 07:25:48 +00003822 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003823 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003824
Reid Spencere8019bb2007-03-01 07:25:48 +00003825 // Compute the B^2-4ac term.
3826 APInt SqrtTerm(B);
3827 SqrtTerm *= B;
3828 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003829
Reid Spencere8019bb2007-03-01 07:25:48 +00003830 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3831 // integer value or else APInt::sqrt() will assert.
3832 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003833
Dan Gohman64a845e2009-06-24 04:48:43 +00003834 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00003835 // The divisions must be performed as signed divisions.
3836 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003837 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003838 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003839 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003840 return std::make_pair(CNC, CNC);
3841 }
3842
Owen Anderson76f600b2009-07-06 22:37:39 +00003843 LLVMContext *Context = SE.getContext();
3844
3845 ConstantInt *Solution1 =
3846 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
3847 ConstantInt *Solution2 =
3848 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003849
Dan Gohman64a845e2009-06-24 04:48:43 +00003850 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00003851 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003852 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003853}
3854
3855/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003856/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Anderson372b46c2009-06-22 21:39:50 +00003857const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003858 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003859 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003860 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003861 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00003862 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003863 }
3864
Dan Gohman35738ac2009-05-04 22:30:44 +00003865 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003866 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00003867 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003868
3869 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003870 // If this is an affine expression, the execution count of this branch is
3871 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003872 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003873 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003874 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003875 // equivalent to:
3876 //
3877 // Step*N = -Start (mod 2^BW)
3878 //
3879 // where BW is the common bit width of Start and Step.
3880
Chris Lattner53e677a2004-04-02 20:23:17 +00003881 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00003882 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3883 L->getParentLoop());
3884 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3885 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003886
Dan Gohman622ed672009-05-04 22:02:23 +00003887 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003888 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003889
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003890 // First, handle unitary steps.
3891 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003892 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003893 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3894 return Start; // N = Start (as unsigned)
3895
3896 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003897 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003898 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003899 -StartC->getValue()->getValue(),
3900 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003901 }
Chris Lattner42a75512007-01-15 02:27:26 +00003902 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003903 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3904 // the quadratic equation to solve it.
Owen Anderson372b46c2009-06-22 21:39:50 +00003905 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003906 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003907 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3908 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003909 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003910#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003911 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3912 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003913#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003914 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003915 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00003916 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003917 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003918 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003919 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003920
Chris Lattner53e677a2004-04-02 20:23:17 +00003921 // We can only use this value if the chrec ends up with an exact zero
3922 // value at this index. When solving for "X*X != 5", for example, we
3923 // should not accept a root of 2.
Owen Anderson372b46c2009-06-22 21:39:50 +00003924 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003925 if (Val->isZero())
3926 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003927 }
3928 }
3929 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003930
Dan Gohman1c343752009-06-27 21:21:31 +00003931 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003932}
3933
3934/// HowFarToNonZero - Return the number of times a backedge checking the
3935/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003936/// CouldNotCompute
Owen Anderson372b46c2009-06-22 21:39:50 +00003937const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003938 // Loops that look like: while (X == 0) are very strange indeed. We don't
3939 // handle them yet except for the trivial case. This could be expanded in the
3940 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003941
Chris Lattner53e677a2004-04-02 20:23:17 +00003942 // If the value is a constant, check to see if it is known to be non-zero
3943 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003945 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003946 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00003947 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003948 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003949
Chris Lattner53e677a2004-04-02 20:23:17 +00003950 // We could implement others, but I really doubt anyone writes loops like
3951 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00003952 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003953}
3954
Dan Gohman859b4822009-05-18 15:36:09 +00003955/// getLoopPredecessor - If the given loop's header has exactly one unique
3956/// predecessor outside the loop, return it. Otherwise return null.
3957///
3958BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3959 BasicBlock *Header = L->getHeader();
3960 BasicBlock *Pred = 0;
3961 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3962 PI != E; ++PI)
3963 if (!L->contains(*PI)) {
3964 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3965 Pred = *PI;
3966 }
3967 return Pred;
3968}
3969
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003970/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3971/// (which may not be an immediate predecessor) which has exactly one
3972/// successor from which BB is reachable, or null if no such block is
3973/// found.
3974///
3975BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003976ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003977 // If the block has a unique predecessor, then there is no path from the
3978 // predecessor to the block that does not go through the direct edge
3979 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003980 if (BasicBlock *Pred = BB->getSinglePredecessor())
3981 return Pred;
3982
3983 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00003984 // If the header has a unique predecessor outside the loop, it must be
3985 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003986 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00003987 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003988
3989 return 0;
3990}
3991
Dan Gohman763bad12009-06-20 00:35:32 +00003992/// HasSameValue - SCEV structural equivalence is usually sufficient for
3993/// testing whether two expressions are equal, however for the purposes of
3994/// looking for a condition guarding a loop, it can be useful to be a little
3995/// more general, since a front-end may have replicated the controlling
3996/// expression.
3997///
Owen Anderson372b46c2009-06-22 21:39:50 +00003998static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohman763bad12009-06-20 00:35:32 +00003999 // Quick check to see if they are the same SCEV.
4000 if (A == B) return true;
4001
4002 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4003 // two different instructions with the same value. Check for this case.
4004 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4005 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4006 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4007 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4008 if (AI->isIdenticalTo(BI))
4009 return true;
4010
4011 // Otherwise assume they may have a different value.
4012 return false;
4013}
4014
Dan Gohmanc2390b12009-02-12 22:19:27 +00004015/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00004016/// a conditional between LHS and RHS. This is used to help avoid max
4017/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004018bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00004019 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00004020 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004021 // Interpret a null as meaning no loop, where there is obviously no guard
4022 // (interprocedural conditions notwithstanding).
4023 if (!L) return false;
4024
Dan Gohman859b4822009-05-18 15:36:09 +00004025 BasicBlock *Predecessor = getLoopPredecessor(L);
4026 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004027
Dan Gohman859b4822009-05-18 15:36:09 +00004028 // Starting at the loop predecessor, climb up the predecessor chain, as long
4029 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004030 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004031 for (; Predecessor;
4032 PredecessorDest = Predecessor,
4033 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004034
4035 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004036 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004037 if (!LoopEntryPredicate ||
4038 LoopEntryPredicate->isUnconditional())
4039 continue;
4040
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004041 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4042 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004043 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004044 }
4045
Dan Gohman38372182008-08-12 20:17:31 +00004046 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004047}
4048
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004049/// isNecessaryCond - Test whether the given CondValue value is a condition
4050/// which is at least as strict as the one described by Pred, LHS, and RHS.
4051bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4052 ICmpInst::Predicate Pred,
4053 const SCEV *LHS, const SCEV *RHS,
4054 bool Inverse) {
4055 // Recursivly handle And and Or conditions.
4056 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4057 if (BO->getOpcode() == Instruction::And) {
4058 if (!Inverse)
4059 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4060 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4061 } else if (BO->getOpcode() == Instruction::Or) {
4062 if (Inverse)
4063 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4064 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4065 }
4066 }
4067
4068 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4069 if (!ICI) return false;
4070
4071 // Now that we found a conditional branch that dominates the loop, check to
4072 // see if it is the comparison we are looking for.
4073 Value *PreCondLHS = ICI->getOperand(0);
4074 Value *PreCondRHS = ICI->getOperand(1);
4075 ICmpInst::Predicate Cond;
4076 if (Inverse)
4077 Cond = ICI->getInversePredicate();
4078 else
4079 Cond = ICI->getPredicate();
4080
4081 if (Cond == Pred)
4082 ; // An exact match.
4083 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4084 ; // The actual condition is beyond sufficient.
4085 else
4086 // Check a few special cases.
4087 switch (Cond) {
4088 case ICmpInst::ICMP_UGT:
4089 if (Pred == ICmpInst::ICMP_ULT) {
4090 std::swap(PreCondLHS, PreCondRHS);
4091 Cond = ICmpInst::ICMP_ULT;
4092 break;
4093 }
4094 return false;
4095 case ICmpInst::ICMP_SGT:
4096 if (Pred == ICmpInst::ICMP_SLT) {
4097 std::swap(PreCondLHS, PreCondRHS);
4098 Cond = ICmpInst::ICMP_SLT;
4099 break;
4100 }
4101 return false;
4102 case ICmpInst::ICMP_NE:
4103 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4104 // so check for this case by checking if the NE is comparing against
4105 // a minimum or maximum constant.
4106 if (!ICmpInst::isTrueWhenEqual(Pred))
4107 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4108 const APInt &A = CI->getValue();
4109 switch (Pred) {
4110 case ICmpInst::ICMP_SLT:
4111 if (A.isMaxSignedValue()) break;
4112 return false;
4113 case ICmpInst::ICMP_SGT:
4114 if (A.isMinSignedValue()) break;
4115 return false;
4116 case ICmpInst::ICMP_ULT:
4117 if (A.isMaxValue()) break;
4118 return false;
4119 case ICmpInst::ICMP_UGT:
4120 if (A.isMinValue()) break;
4121 return false;
4122 default:
4123 return false;
4124 }
4125 Cond = ICmpInst::ICMP_NE;
4126 // NE is symmetric but the original comparison may not be. Swap
4127 // the operands if necessary so that they match below.
4128 if (isa<SCEVConstant>(LHS))
4129 std::swap(PreCondLHS, PreCondRHS);
4130 break;
4131 }
4132 return false;
4133 default:
4134 // We weren't able to reconcile the condition.
4135 return false;
4136 }
4137
4138 if (!PreCondLHS->getType()->isInteger()) return false;
4139
4140 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4141 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4142 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4143 HasSameValue(RHS, PreCondRHSSCEV)) ||
4144 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4145 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4146}
4147
Dan Gohman51f53b72009-06-21 23:46:38 +00004148/// getBECount - Subtract the end and start values and divide by the step,
4149/// rounding up, to get the number of times the backedge is executed. Return
4150/// CouldNotCompute if an intermediate computation overflows.
Owen Anderson372b46c2009-06-22 21:39:50 +00004151const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
4152 const SCEV* End,
4153 const SCEV* Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004154 const Type *Ty = Start->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00004155 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
4156 const SCEV* Diff = getMinusSCEV(End, Start);
4157 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004158
4159 // Add an adjustment to the difference between End and Start so that
4160 // the division will effectively round up.
Owen Anderson372b46c2009-06-22 21:39:50 +00004161 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004162
4163 // Check Add for unsigned overflow.
4164 // TODO: More sophisticated things could be done here.
Owen Anderson76f600b2009-07-06 22:37:39 +00004165 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Owen Anderson372b46c2009-06-22 21:39:50 +00004166 const SCEV* OperandExtendedAdd =
Dan Gohman51f53b72009-06-21 23:46:38 +00004167 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4168 getZeroExtendExpr(RoundUp, WideTy));
4169 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004170 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004171
4172 return getUDivExpr(Add, Step);
4173}
4174
Chris Lattnerdb25de42005-08-15 23:33:51 +00004175/// HowManyLessThans - Return the number of times a backedge containing the
4176/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004177/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004178ScalarEvolution::BackedgeTakenInfo
4179ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4180 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004181 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004182 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004183
Dan Gohman35738ac2009-05-04 22:30:44 +00004184 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004185 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004186 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004187
4188 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004189 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004190 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +00004191 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004192
4193 // TODO: handle non-constant strides.
4194 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4195 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004196 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004197 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004198 // With unit stride, the iteration never steps past the limit value.
4199 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4200 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4201 // Test whether a positive iteration iteration can step past the limit
4202 // value and past the maximum value for its type in a single step.
4203 if (isSigned) {
4204 APInt Max = APInt::getSignedMaxValue(BitWidth);
4205 if ((Max - CStep->getValue()->getValue())
4206 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004207 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004208 } else {
4209 APInt Max = APInt::getMaxValue(BitWidth);
4210 if ((Max - CStep->getValue()->getValue())
4211 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004212 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004213 }
4214 } else
4215 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004216 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004217 } else
4218 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004219 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004220
Dan Gohmana1af7572009-04-30 20:47:05 +00004221 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4222 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4223 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004224 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004225
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004226 // First, we get the value of the LHS in the first iteration: n
Owen Anderson372b46c2009-06-22 21:39:50 +00004227 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004228
Dan Gohmana1af7572009-04-30 20:47:05 +00004229 // Determine the minimum constant start value.
Dan Gohman64a845e2009-06-24 04:48:43 +00004230 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmana1af7572009-04-30 20:47:05 +00004231 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4232 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004233
Dan Gohmana1af7572009-04-30 20:47:05 +00004234 // If we know that the condition is true in order to enter the loop,
4235 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004236 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4237 // the division must round up.
Owen Anderson372b46c2009-06-22 21:39:50 +00004238 const SCEV* End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004239 if (!isLoopGuardedByCond(L,
4240 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4241 getMinusSCEV(Start, Step), RHS))
4242 End = isSigned ? getSMaxExpr(RHS, Start)
4243 : getUMaxExpr(RHS, Start);
4244
4245 // Determine the maximum constant end value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004246 const SCEV* MaxEnd =
Dan Gohman3964acc2009-06-20 00:32:22 +00004247 isa<SCEVConstant>(End) ? End :
4248 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4249 .ashr(GetMinSignBits(End) - 1) :
4250 APInt::getMaxValue(BitWidth)
4251 .lshr(GetMinLeadingZeros(End)));
Dan Gohmana1af7572009-04-30 20:47:05 +00004252
4253 // Finally, we subtract these two values and divide, rounding up, to get
4254 // the number of times the backedge is executed.
Owen Anderson372b46c2009-06-22 21:39:50 +00004255 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004256
4257 // The maximum backedge count is similar, except using the minimum start
4258 // value and the maximum end value.
Dan Gohmanc39f44b2009-06-30 20:13:32 +00004259 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004260
4261 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004262 }
4263
Dan Gohman1c343752009-06-27 21:21:31 +00004264 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004265}
4266
Chris Lattner53e677a2004-04-02 20:23:17 +00004267/// getNumIterationsInRange - Return the number of iterations of this loop that
4268/// produce values in the specified constant range. Another way of looking at
4269/// this is that it returns the first iteration number where the value is not in
4270/// the condition, thus computing the exit count. If the iteration count can't
4271/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00004272const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004273 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004274 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004275 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004276
4277 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004279 if (!SC->getValue()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00004280 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004281 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +00004282 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004283 if (const SCEVAddRecExpr *ShiftedAddRec =
4284 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004285 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004286 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004287 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004288 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004289 }
4290
4291 // The only time we can solve this is when we have all constant indices.
4292 // Otherwise, we cannot determine the overflow conditions.
4293 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4294 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004295 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004296
4297
4298 // Okay at this point we know that all elements of the chrec are constants and
4299 // that the start element is zero.
4300
4301 // First check to see if the range contains zero. If not, the first
4302 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004303 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004304 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004305 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004306
Chris Lattner53e677a2004-04-02 20:23:17 +00004307 if (isAffine()) {
4308 // If this is an affine expression then we have this situation:
4309 // Solve {0,+,A} in Range === Ax in Range
4310
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004311 // We know that zero is in the range. If A is positive then we know that
4312 // the upper value of the range must be the first possible exit value.
4313 // If A is negative then the lower of the range is the last possible loop
4314 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004315 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004316 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4317 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004318
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004319 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004320 APInt ExitVal = (End + A).udiv(A);
Owen Anderson76f600b2009-07-06 22:37:39 +00004321 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004322
4323 // Evaluate at the exit value. If we really did fall out of the valid
4324 // range, then we computed our trip count, otherwise wrap around or other
4325 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004326 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004327 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004328 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004329
4330 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004331 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004332 EvaluateConstantChrecAtConstant(this,
Owen Anderson76f600b2009-07-06 22:37:39 +00004333 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004334 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004335 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004336 } else if (isQuadratic()) {
4337 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4338 // quadratic equation to solve it. To do this, we must frame our problem in
4339 // terms of figuring out when zero is crossed, instead of when
4340 // Range.getUpper() is crossed.
Owen Anderson372b46c2009-06-22 21:39:50 +00004341 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004342 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Anderson372b46c2009-06-22 21:39:50 +00004343 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004344
4345 // Next, solve the constructed addrec
Owen Anderson372b46c2009-06-22 21:39:50 +00004346 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004347 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004348 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4349 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004350 if (R1) {
4351 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004352 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004353 dyn_cast<ConstantInt>(
4354 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4355 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004356 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004357 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004358
Chris Lattner53e677a2004-04-02 20:23:17 +00004359 // Make sure the root is not off by one. The returned iteration should
4360 // not be in the range, but the previous one should be. When solving
4361 // for "X*X < 5", for example, we should not return a root of 2.
4362 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004363 R1->getValue(),
4364 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004365 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004366 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004367 ConstantInt *NextVal =
4368 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004369
Dan Gohman246b2562007-10-22 18:31:58 +00004370 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004371 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004372 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004373 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004374 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004375
Chris Lattner53e677a2004-04-02 20:23:17 +00004376 // If R1 was not in the range, then it is a good return value. Make
4377 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00004378 ConstantInt *NextVal =
4379 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004380 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004381 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004382 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004383 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004384 }
4385 }
4386 }
4387
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004388 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004389}
4390
4391
4392
4393//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004394// SCEVCallbackVH Class Implementation
4395//===----------------------------------------------------------------------===//
4396
Dan Gohman1959b752009-05-19 19:22:47 +00004397void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00004398 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4399 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4400 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004401 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4402 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004403 SE->Scalars.erase(getValPtr());
4404 // this now dangles!
4405}
4406
Dan Gohman1959b752009-05-19 19:22:47 +00004407void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004408 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4409
4410 // Forget all the expressions associated with users of the old value,
4411 // so that future queries will recompute the expressions using the new
4412 // value.
4413 SmallVector<User *, 16> Worklist;
4414 Value *Old = getValPtr();
4415 bool DeleteOld = false;
4416 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4417 UI != UE; ++UI)
4418 Worklist.push_back(*UI);
4419 while (!Worklist.empty()) {
4420 User *U = Worklist.pop_back_val();
4421 // Deleting the Old value will cause this to dangle. Postpone
4422 // that until everything else is done.
4423 if (U == Old) {
4424 DeleteOld = true;
4425 continue;
4426 }
4427 if (PHINode *PN = dyn_cast<PHINode>(U))
4428 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004429 if (Instruction *I = dyn_cast<Instruction>(U))
4430 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004431 if (SE->Scalars.erase(U))
4432 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4433 UI != UE; ++UI)
4434 Worklist.push_back(*UI);
4435 }
4436 if (DeleteOld) {
4437 if (PHINode *PN = dyn_cast<PHINode>(Old))
4438 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004439 if (Instruction *I = dyn_cast<Instruction>(Old))
4440 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004441 SE->Scalars.erase(Old);
4442 // this now dangles!
4443 }
4444 // this may dangle!
4445}
4446
Dan Gohman1959b752009-05-19 19:22:47 +00004447ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004448 : CallbackVH(V), SE(se) {}
4449
4450//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004451// ScalarEvolution Class Implementation
4452//===----------------------------------------------------------------------===//
4453
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004454ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00004455 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004456}
4457
Chris Lattner53e677a2004-04-02 20:23:17 +00004458bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004459 this->F = &F;
4460 LI = &getAnalysis<LoopInfo>();
4461 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004462 return false;
4463}
4464
4465void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004466 Scalars.clear();
4467 BackedgeTakenCounts.clear();
4468 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004469 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00004470 UniqueSCEVs.clear();
4471 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00004472}
4473
4474void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4475 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004476 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004477}
4478
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004479bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004480 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004481}
4482
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004483static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004484 const Loop *L) {
4485 // Print all inner loops first
4486 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4487 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004488
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004489 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004490
Devang Patelb7211a22007-08-21 00:31:24 +00004491 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004492 L->getExitBlocks(ExitBlocks);
4493 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004494 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004495
Dan Gohman46bdfb02009-02-24 18:55:53 +00004496 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4497 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004498 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004499 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004500 }
4501
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004502 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00004503 OS << "Loop " << L->getHeader()->getName() << ": ";
4504
4505 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4506 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4507 } else {
4508 OS << "Unpredictable max backedge-taken count. ";
4509 }
4510
4511 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004512}
4513
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004514void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004515 // ScalarEvolution's implementaiton of the print method is to print
4516 // out SCEV values of all instructions that are interesting. Doing
4517 // this potentially causes it to create new SCEV objects though,
4518 // which technically conflicts with the const qualifier. This isn't
4519 // observable from outside the class though (the hasSCEV function
4520 // notwithstanding), so casting away the const isn't dangerous.
4521 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004522
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004523 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004524 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004525 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004526 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004527 OS << " --> ";
Owen Anderson372b46c2009-06-22 21:39:50 +00004528 const SCEV* SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004529 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004530
Dan Gohman0c689c52009-06-19 17:49:54 +00004531 const Loop *L = LI->getLoopFor((*I).getParent());
4532
Owen Anderson372b46c2009-06-22 21:39:50 +00004533 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004534 if (AtUse != SV) {
4535 OS << " --> ";
4536 AtUse->print(OS);
4537 }
4538
4539 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004540 OS << "\t\t" "Exits: ";
Owen Anderson372b46c2009-06-22 21:39:50 +00004541 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004542 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004543 OS << "<<Unknown>>";
4544 } else {
4545 OS << *ExitValue;
4546 }
4547 }
4548
Chris Lattner53e677a2004-04-02 20:23:17 +00004549 OS << "\n";
4550 }
4551
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004552 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4553 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4554 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004555}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004556
4557void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4558 raw_os_ostream OS(o);
4559 print(OS, M);
4560}