blob: a9528cf19cba3498c90542f077b03a544aa6d29a [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohman0bba49c2009-07-07 17:06:11 +000017// can handle. These classes are reference counted, managed by the const SCEV *
Chris Lattner53e677a2004-04-02 20:23:17 +000018// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
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"
Dan Gohman59ae6b92009-07-08 19:23:34 +000084#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000085#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000086using namespace llvm;
87
Chris Lattner3b27d682006-12-19 22:30:33 +000088STATISTIC(NumArrayLenItCounts,
89 "Number of trip counts computed with array length");
90STATISTIC(NumTripCountsComputed,
91 "Number of loops with predictable loop counts");
92STATISTIC(NumTripCountsNotComputed,
93 "Number of loops without predictable loop counts");
94STATISTIC(NumBruteForceTripCountsComputed,
95 "Number of loops with trip counts computed by force");
96
Dan Gohman844731a2008-05-13 00:00:25 +000097static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000098MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
99 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000100 "symbolically execute a constant "
101 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000102 cl::init(100));
103
Dan Gohman844731a2008-05-13 00:00:25 +0000104static RegisterPass<ScalarEvolution>
105R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000106char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000107
108//===----------------------------------------------------------------------===//
109// SCEV class definitions
110//===----------------------------------------------------------------------===//
111
112//===----------------------------------------------------------------------===//
113// Implementation of the SCEV class.
114//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000115
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000119 print(errs());
120 errs() << '\n';
121}
122
123void SCEV::print(std::ostream &o) const {
124 raw_os_ostream OS(o);
125 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000126}
127
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000128bool SCEV::isZero() const {
129 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
130 return SC->getValue()->isZero();
131 return false;
132}
133
Dan Gohman70a1fe72009-05-18 15:22:39 +0000134bool SCEV::isOne() const {
135 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
136 return SC->getValue()->isOne();
137 return false;
138}
Chris Lattner53e677a2004-04-02 20:23:17 +0000139
Dan Gohman4d289bf2009-06-24 00:30:26 +0000140bool SCEV::isAllOnesValue() const {
141 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
142 return SC->getValue()->isAllOnesValue();
143 return false;
144}
145
Owen Anderson753ad612009-06-22 21:57:23 +0000146SCEVCouldNotCompute::SCEVCouldNotCompute() :
147 SCEV(scCouldNotCompute) {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000148
Dan Gohman1c343752009-06-27 21:21:31 +0000149void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151}
152
Chris Lattner53e677a2004-04-02 20:23:17 +0000153bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
154 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000155 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000156}
157
158const Type *SCEVCouldNotCompute::getType() const {
159 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000160 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000161}
162
163bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
164 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
165 return false;
166}
167
Dan Gohman64a845e2009-06-24 04:48:43 +0000168const SCEV *
169SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
170 const SCEV *Sym,
171 const SCEV *Conc,
172 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000173 return this;
174}
175
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000176void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000177 OS << "***COULDNOTCOMPUTE***";
178}
179
180bool SCEVCouldNotCompute::classof(const SCEV *S) {
181 return S->getSCEVType() == scCouldNotCompute;
182}
183
Dan Gohman0bba49c2009-07-07 17:06:11 +0000184const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000185 FoldingSetNodeID ID;
186 ID.AddInteger(scConstant);
187 ID.AddPointer(V);
188 void *IP = 0;
189 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
190 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
191 new (S) SCEVConstant(V);
192 UniqueSCEVs.InsertNode(S, IP);
193 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Dan Gohman0bba49c2009-07-07 17:06:11 +0000196const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman246b2562007-10-22 18:31:58 +0000197 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000198}
199
Dan Gohman0bba49c2009-07-07 17:06:11 +0000200const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000201ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
202 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
203}
204
Dan Gohman1c343752009-06-27 21:21:31 +0000205void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
206 ID.AddInteger(scConstant);
207 ID.AddPointer(V);
208}
209
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000211
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000212void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213 WriteAsOperand(OS, V, false);
214}
Chris Lattner53e677a2004-04-02 20:23:17 +0000215
Dan Gohman84923602009-04-21 01:25:57 +0000216SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Dan Gohman0bba49c2009-07-07 17:06:11 +0000217 const SCEV *op, const Type *ty)
Owen Anderson753ad612009-06-22 21:57:23 +0000218 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman84923602009-04-21 01:25:57 +0000219
Dan Gohman1c343752009-06-27 21:21:31 +0000220void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
221 ID.AddInteger(getSCEVType());
222 ID.AddPointer(Op);
223 ID.AddPointer(Ty);
224}
225
Dan Gohman84923602009-04-21 01:25:57 +0000226bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
227 return Op->dominates(BB, DT);
228}
229
Dan Gohman0bba49c2009-07-07 17:06:11 +0000230SCEVTruncateExpr::SCEVTruncateExpr(const SCEV *op, const Type *ty)
Owen Anderson753ad612009-06-22 21:57:23 +0000231 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000232 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
233 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
Chris Lattner53e677a2004-04-02 20:23:17 +0000236
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000237void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000238 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
Dan Gohman0bba49c2009-07-07 17:06:11 +0000241SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV *op, const Type *ty)
Owen Anderson753ad612009-06-22 21:57:23 +0000242 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000243 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
244 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000245 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246}
247
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000248void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000249 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250}
251
Dan Gohman0bba49c2009-07-07 17:06:11 +0000252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV *op, const Type *ty)
Owen Anderson753ad612009-06-22 21:57:23 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000257}
258
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000259void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000260 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000261}
262
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000263void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000264 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
265 const char *OpStr = getOperationStr();
266 OS << "(" << *Operands[0];
267 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
268 OS << OpStr << *Operands[i];
269 OS << ")";
270}
271
Dan Gohman64a845e2009-06-24 04:48:43 +0000272const SCEV *
273SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
274 const SCEV *Sym,
275 const SCEV *Conc,
276 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000277 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000278 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000279 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000280 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000281 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000282 NewOps.reserve(getNumOperands());
283 for (unsigned j = 0; j != i; ++j)
284 NewOps.push_back(getOperand(j));
285 NewOps.push_back(H);
286 for (++i; i != e; ++i)
287 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000288 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000289
290 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000291 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000293 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000294 else if (isa<SCEVSMaxExpr>(this))
295 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000296 else if (isa<SCEVUMaxExpr>(this))
297 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000298 else
299 assert(0 && "Unknown commutative expr!");
300 }
301 }
302 return this;
303}
304
Dan Gohman1c343752009-06-27 21:21:31 +0000305void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
306 ID.AddInteger(getSCEVType());
307 ID.AddInteger(Operands.size());
308 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
309 ID.AddPointer(Operands[i]);
310}
311
Dan Gohmanecb403a2009-05-07 14:00:19 +0000312bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000313 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
314 if (!getOperand(i)->dominates(BB, DT))
315 return false;
316 }
317 return true;
318}
319
Dan Gohman1c343752009-06-27 21:21:31 +0000320void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
321 ID.AddInteger(scUDivExpr);
322 ID.AddPointer(LHS);
323 ID.AddPointer(RHS);
324}
325
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000326bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
327 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
328}
329
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000330void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000331 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332}
333
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000334const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000335 // In most cases the types of LHS and RHS will be the same, but in some
336 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
337 // depend on the type for correctness, but handling types carefully can
338 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
339 // a pointer type than the RHS, so use the RHS' type here.
340 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341}
342
Dan Gohman1c343752009-06-27 21:21:31 +0000343void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
344 ID.AddInteger(scAddRecExpr);
345 ID.AddInteger(Operands.size());
346 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
347 ID.AddPointer(Operands[i]);
348 ID.AddPointer(L);
349}
350
Dan Gohman64a845e2009-06-24 04:48:43 +0000351const SCEV *
352SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
353 const SCEV *Conc,
354 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000355 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000356 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000357 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000358 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000359 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000360 NewOps.reserve(getNumOperands());
361 for (unsigned j = 0; j != i; ++j)
362 NewOps.push_back(getOperand(j));
363 NewOps.push_back(H);
364 for (++i; i != e; ++i)
365 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000366 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000367
Dan Gohman246b2562007-10-22 18:31:58 +0000368 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000369 }
370 }
371 return this;
372}
373
374
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000376 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000377 if (!QueryLoop)
378 return false;
379
380 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
381 if (QueryLoop->contains(L->getHeader()))
382 return false;
383
384 // This recurrence is variant w.r.t. QueryLoop if any of its operands
385 // are variant.
386 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
387 if (!getOperand(i)->isLoopInvariant(QueryLoop))
388 return false;
389
390 // Otherwise it's loop-invariant.
391 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000392}
393
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000394void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000395 OS << "{" << *Operands[0];
396 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
397 OS << ",+," << *Operands[i];
398 OS << "}<" << L->getHeader()->getName() + ">";
399}
Chris Lattner53e677a2004-04-02 20:23:17 +0000400
Dan Gohman1c343752009-06-27 21:21:31 +0000401void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
402 ID.AddInteger(scUnknown);
403 ID.AddPointer(V);
404}
405
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000406bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
407 // All non-instruction values are loop invariant. All instructions are loop
408 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000409 // Instructions are never considered invariant in the function body
410 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000411 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000412 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000413 return true;
414}
Chris Lattner53e677a2004-04-02 20:23:17 +0000415
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000416bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
417 if (Instruction *I = dyn_cast<Instruction>(getValue()))
418 return DT->dominates(I->getParent(), BB);
419 return true;
420}
421
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000422const Type *SCEVUnknown::getType() const {
423 return V->getType();
424}
Chris Lattner53e677a2004-04-02 20:23:17 +0000425
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000426void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000427 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000428}
429
Chris Lattner8d741b82004-06-20 06:23:15 +0000430//===----------------------------------------------------------------------===//
431// SCEV Utilities
432//===----------------------------------------------------------------------===//
433
434namespace {
435 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
436 /// than the complexity of the RHS. This comparator is used to canonicalize
437 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000438 class VISIBILITY_HIDDEN SCEVComplexityCompare {
439 LoopInfo *LI;
440 public:
441 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
442
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000443 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000444 // Primarily, sort the SCEVs by their getSCEVType().
445 if (LHS->getSCEVType() != RHS->getSCEVType())
446 return LHS->getSCEVType() < RHS->getSCEVType();
447
448 // Aside from the getSCEVType() ordering, the particular ordering
449 // isn't very important except that it's beneficial to be consistent,
450 // so that (a + b) and (b + a) don't end up as different expressions.
451
452 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
453 // not as complete as it could be.
454 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
455 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
456
Dan Gohman5be18e82009-05-19 02:15:55 +0000457 // Order pointer values after integer values. This helps SCEVExpander
458 // form GEPs.
459 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
460 return false;
461 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
462 return true;
463
Dan Gohman72861302009-05-07 14:39:04 +0000464 // Compare getValueID values.
465 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
466 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
467
468 // Sort arguments by their position.
469 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
470 const Argument *RA = cast<Argument>(RU->getValue());
471 return LA->getArgNo() < RA->getArgNo();
472 }
473
474 // For instructions, compare their loop depth, and their opcode.
475 // This is pretty loose.
476 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
477 Instruction *RV = cast<Instruction>(RU->getValue());
478
479 // Compare loop depths.
480 if (LI->getLoopDepth(LV->getParent()) !=
481 LI->getLoopDepth(RV->getParent()))
482 return LI->getLoopDepth(LV->getParent()) <
483 LI->getLoopDepth(RV->getParent());
484
485 // Compare opcodes.
486 if (LV->getOpcode() != RV->getOpcode())
487 return LV->getOpcode() < RV->getOpcode();
488
489 // Compare the number of operands.
490 if (LV->getNumOperands() != RV->getNumOperands())
491 return LV->getNumOperands() < RV->getNumOperands();
492 }
493
494 return false;
495 }
496
Dan Gohman4dfad292009-06-14 22:51:25 +0000497 // Compare constant values.
498 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
499 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000500 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
501 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000502 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
503 }
504
505 // Compare addrec loop depths.
506 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
507 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
508 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
509 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
510 }
Dan Gohman72861302009-05-07 14:39:04 +0000511
512 // Lexicographically compare n-ary expressions.
513 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
514 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
515 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
516 if (i >= RC->getNumOperands())
517 return false;
518 if (operator()(LC->getOperand(i), RC->getOperand(i)))
519 return true;
520 if (operator()(RC->getOperand(i), LC->getOperand(i)))
521 return false;
522 }
523 return LC->getNumOperands() < RC->getNumOperands();
524 }
525
Dan Gohmana6b35e22009-05-07 19:23:21 +0000526 // Lexicographically compare udiv expressions.
527 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
528 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
529 if (operator()(LC->getLHS(), RC->getLHS()))
530 return true;
531 if (operator()(RC->getLHS(), LC->getLHS()))
532 return false;
533 if (operator()(LC->getRHS(), RC->getRHS()))
534 return true;
535 if (operator()(RC->getRHS(), LC->getRHS()))
536 return false;
537 return false;
538 }
539
Dan Gohman72861302009-05-07 14:39:04 +0000540 // Compare cast expressions by operand.
541 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
542 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
543 return operator()(LC->getOperand(), RC->getOperand());
544 }
545
546 assert(0 && "Unknown SCEV kind!");
547 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000548 }
549 };
550}
551
552/// GroupByComplexity - Given a list of SCEV objects, order them by their
553/// complexity, and group objects of the same complexity together by value.
554/// When this routine is finished, we know that any duplicates in the vector are
555/// consecutive and that complexity is monotonically increasing.
556///
557/// Note that we go take special precautions to ensure that we get determinstic
558/// results from this routine. In other words, we don't want the results of
559/// this to depend on where the addresses of various SCEV objects happened to
560/// land in memory.
561///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000562static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000563 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000564 if (Ops.size() < 2) return; // Noop
565 if (Ops.size() == 2) {
566 // This is the common case, which also happens to be trivially simple.
567 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000568 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000569 std::swap(Ops[0], Ops[1]);
570 return;
571 }
572
573 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000574 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000575
576 // Now that we are sorted by complexity, group elements of the same
577 // complexity. Note that this is, at worst, N^2, but the vector is likely to
578 // be extremely short in practice. Note that we take this approach because we
579 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000580 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000581 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000582 unsigned Complexity = S->getSCEVType();
583
584 // If there are any objects of the same complexity and same value as this
585 // one, group them.
586 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
587 if (Ops[j] == S) { // Found a duplicate.
588 // Move it to immediately after i'th element.
589 std::swap(Ops[i+1], Ops[j]);
590 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000591 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000592 }
593 }
594 }
595}
596
Chris Lattner53e677a2004-04-02 20:23:17 +0000597
Chris Lattner53e677a2004-04-02 20:23:17 +0000598
599//===----------------------------------------------------------------------===//
600// Simple SCEV method implementations
601//===----------------------------------------------------------------------===//
602
Eli Friedmanb42a6262008-08-04 23:49:06 +0000603/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000604/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000605static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000606 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000607 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000608 // Handle the simplest case efficiently.
609 if (K == 1)
610 return SE.getTruncateOrZeroExtend(It, ResultTy);
611
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612 // We are using the following formula for BC(It, K):
613 //
614 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
615 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000616 // Suppose, W is the bitwidth of the return value. We must be prepared for
617 // overflow. Hence, we must assure that the result of our computation is
618 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
619 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000620 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000621 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000622 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000623 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
624 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000625 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000626 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000627 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000628 // This formula is trivially equivalent to the previous formula. However,
629 // this formula can be implemented much more efficiently. The trick is that
630 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
631 // arithmetic. To do exact division in modular arithmetic, all we have
632 // to do is multiply by the inverse. Therefore, this step can be done at
633 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000634 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000635 // The next issue is how to safely do the division by 2^T. The way this
636 // is done is by doing the multiplication step at a width of at least W + T
637 // bits. This way, the bottom W+T bits of the product are accurate. Then,
638 // when we perform the division by 2^T (which is equivalent to a right shift
639 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
640 // truncated out after the division by 2^T.
641 //
642 // In comparison to just directly using the first formula, this technique
643 // is much more efficient; using the first formula requires W * K bits,
644 // but this formula less than W + K bits. Also, the first formula requires
645 // a division step, whereas this formula only requires multiplies and shifts.
646 //
647 // It doesn't matter whether the subtraction step is done in the calculation
648 // width or the input iteration count's width; if the subtraction overflows,
649 // the result must be zero anyway. We prefer here to do it in the width of
650 // the induction variable because it helps a lot for certain cases; CodeGen
651 // isn't smart enough to ignore the overflow, which leads to much less
652 // efficient code if the width of the subtraction is wider than the native
653 // register width.
654 //
655 // (It's possible to not widen at all by pulling out factors of 2 before
656 // the multiplication; for example, K=2 can be calculated as
657 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
658 // extra arithmetic, so it's not an obvious win, and it gets
659 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000660
Eli Friedmanb42a6262008-08-04 23:49:06 +0000661 // Protection from insane SCEVs; this bound is conservative,
662 // but it probably doesn't matter.
663 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000664 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000665
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000666 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000667
Eli Friedmanb42a6262008-08-04 23:49:06 +0000668 // Calculate K! / 2^T and T; we divide out the factors of two before
669 // multiplying for calculating K! / 2^T to avoid overflow.
670 // Other overflow doesn't matter because we only care about the bottom
671 // W bits of the result.
672 APInt OddFactorial(W, 1);
673 unsigned T = 1;
674 for (unsigned i = 3; i <= K; ++i) {
675 APInt Mult(W, i);
676 unsigned TwoFactors = Mult.countTrailingZeros();
677 T += TwoFactors;
678 Mult = Mult.lshr(TwoFactors);
679 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000680 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000681
Eli Friedmanb42a6262008-08-04 23:49:06 +0000682 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000683 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000684
685 // Calcuate 2^T, at width T+W.
686 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
687
688 // Calculate the multiplicative inverse of K! / 2^T;
689 // this multiplication factor will perform the exact division by
690 // K! / 2^T.
691 APInt Mod = APInt::getSignedMinValue(W+1);
692 APInt MultiplyFactor = OddFactorial.zext(W+1);
693 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
694 MultiplyFactor = MultiplyFactor.trunc(W);
695
696 // Calculate the product, at width T+W
697 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000698 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000699 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000700 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000701 Dividend = SE.getMulExpr(Dividend,
702 SE.getTruncateOrZeroExtend(S, CalculationTy));
703 }
704
705 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000706 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000707
708 // Truncate the result, and divide by K! / 2^T.
709
710 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
711 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000712}
713
Chris Lattner53e677a2004-04-02 20:23:17 +0000714/// evaluateAtIteration - Return the value of this chain of recurrences at
715/// the specified iteration number. We can evaluate this recurrence by
716/// multiplying each element in the chain by the binomial coefficient
717/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
718///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000719/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000720///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000721/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000722///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000723const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman246b2562007-10-22 18:31:58 +0000724 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000725 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000726 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000727 // The computation is correct in the face of overflow provided that the
728 // multiplication is performed _after_ the evaluation of the binomial
729 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000730 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000731 if (isa<SCEVCouldNotCompute>(Coeff))
732 return Coeff;
733
734 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000735 }
736 return Result;
737}
738
Chris Lattner53e677a2004-04-02 20:23:17 +0000739//===----------------------------------------------------------------------===//
740// SCEV Expression folder implementations
741//===----------------------------------------------------------------------===//
742
Dan Gohman0bba49c2009-07-07 17:06:11 +0000743const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohman99243b32009-05-01 16:44:56 +0000744 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000745 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000746 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000747 assert(isSCEVable(Ty) &&
748 "This is not a conversion to a SCEVable type!");
749 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000750
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000751 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000752 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000753 return getConstant(
754 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000755
Dan Gohman20900ca2009-04-22 16:20:48 +0000756 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000757 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000758 return getTruncateExpr(ST->getOperand(), Ty);
759
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000760 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000761 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000762 return getTruncateOrSignExtend(SS->getOperand(), Ty);
763
764 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000765 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000766 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
767
Dan Gohman6864db62009-06-18 16:24:47 +0000768 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000769 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000770 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000771 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000772 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
773 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 }
775
Dan Gohman1c343752009-06-27 21:21:31 +0000776 FoldingSetNodeID ID;
777 ID.AddInteger(scTruncate);
778 ID.AddPointer(Op);
779 ID.AddPointer(Ty);
780 void *IP = 0;
781 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
782 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
783 new (S) SCEVTruncateExpr(Op, Ty);
784 UniqueSCEVs.InsertNode(S, IP);
785 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000786}
787
Dan Gohman0bba49c2009-07-07 17:06:11 +0000788const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohman8170a682009-04-16 19:25:55 +0000789 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000790 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000791 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000792 assert(isSCEVable(Ty) &&
793 "This is not a conversion to a SCEVable type!");
794 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000795
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000796 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000797 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000798 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000799 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
800 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000801 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000802 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000803
Dan Gohman20900ca2009-04-22 16:20:48 +0000804 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000805 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000806 return getZeroExtendExpr(SZ->getOperand(), Ty);
807
Dan Gohman01ecca22009-04-27 20:16:15 +0000808 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000809 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000810 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000811 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000812 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000813 if (AR->isAffine()) {
Dan Gohman1b342582009-07-10 16:42:52 +0000814 const SCEV *Start = AR->getStart();
815 const SCEV *Step = AR->getStepRecurrence(*this);
816 unsigned BitWidth = getTypeSizeInBits(AR->getType());
817 const Loop *L = AR->getLoop();
818
Dan Gohman01ecca22009-04-27 20:16:15 +0000819 // Check whether the backedge-taken count is SCEVCouldNotCompute.
820 // Note that this serves two purposes: It filters out loops that are
821 // simply not analyzable, and it covers the case where this code is
822 // being called from within backedge-taken count analysis, such that
823 // attempting to ask for the backedge-taken count would likely result
824 // in infinite recursion. In the later case, the analysis code will
825 // cope with a conservative value, and it will take care to purge
826 // that value once it has finished.
Dan Gohman1b342582009-07-10 16:42:52 +0000827 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000828 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000829 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000830 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000831
832 // Check whether the backedge-taken count can be losslessly casted to
833 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000834 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000835 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000836 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000837 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
838 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman1b342582009-07-10 16:42:52 +0000839 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000840 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000841 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000842 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000843 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000844 const SCEV *Add = getAddExpr(Start, ZMul);
845 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000846 getAddExpr(getZeroExtendExpr(Start, WideTy),
847 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
848 getZeroExtendExpr(Step, WideTy)));
849 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000850 // Return the expression with the addrec on the outside.
851 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
852 getZeroExtendExpr(Step, Ty),
Dan Gohman1b342582009-07-10 16:42:52 +0000853 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000854
855 // Similar to above, only this time treat the step value as signed.
856 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000857 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000858 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000859 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000860 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000861 OperandExtendedAdd =
862 getAddExpr(getZeroExtendExpr(Start, WideTy),
863 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
864 getSignExtendExpr(Step, WideTy)));
865 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000866 // Return the expression with the addrec on the outside.
867 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
868 getSignExtendExpr(Step, Ty),
Dan Gohman1b342582009-07-10 16:42:52 +0000869 L);
870 }
871
872 // If the backedge is guarded by a comparison with the pre-inc value
873 // the addrec is safe. Also, if the entry is guarded by a comparison
874 // with the start value and the backedge is guarded by a comparison
875 // with the post-inc value, the addrec is safe.
876 if (isKnownPositive(Step)) {
877 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
878 getUnsignedRange(Step).getUnsignedMax());
879 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
880 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
881 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
882 AR->getPostIncExpr(*this), N)))
883 // Return the expression with the addrec on the outside.
884 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
885 getZeroExtendExpr(Step, Ty),
886 L);
887 } else if (isKnownNegative(Step)) {
888 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
889 getSignedRange(Step).getSignedMin());
890 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
891 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
892 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
893 AR->getPostIncExpr(*this), N)))
894 // Return the expression with the addrec on the outside.
895 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
896 getSignExtendExpr(Step, Ty),
897 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000898 }
899 }
900 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000901
Dan Gohman1c343752009-06-27 21:21:31 +0000902 FoldingSetNodeID ID;
903 ID.AddInteger(scZeroExtend);
904 ID.AddPointer(Op);
905 ID.AddPointer(Ty);
906 void *IP = 0;
907 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
908 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
909 new (S) SCEVZeroExtendExpr(Op, Ty);
910 UniqueSCEVs.InsertNode(S, IP);
911 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000912}
913
Dan Gohman0bba49c2009-07-07 17:06:11 +0000914const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohman01ecca22009-04-27 20:16:15 +0000915 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000916 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000917 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000918 assert(isSCEVable(Ty) &&
919 "This is not a conversion to a SCEVable type!");
920 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000921
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000922 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000923 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000924 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000925 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
926 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000927 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000928 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000929
Dan Gohman20900ca2009-04-22 16:20:48 +0000930 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000931 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000932 return getSignExtendExpr(SS->getOperand(), Ty);
933
Dan Gohman01ecca22009-04-27 20:16:15 +0000934 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000935 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000936 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000937 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000938 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000939 if (AR->isAffine()) {
Dan Gohman1b342582009-07-10 16:42:52 +0000940 const SCEV *Start = AR->getStart();
941 const SCEV *Step = AR->getStepRecurrence(*this);
942 unsigned BitWidth = getTypeSizeInBits(AR->getType());
943 const Loop *L = AR->getLoop();
944
Dan Gohman01ecca22009-04-27 20:16:15 +0000945 // Check whether the backedge-taken count is SCEVCouldNotCompute.
946 // Note that this serves two purposes: It filters out loops that are
947 // simply not analyzable, and it covers the case where this code is
948 // being called from within backedge-taken count analysis, such that
949 // attempting to ask for the backedge-taken count would likely result
950 // in infinite recursion. In the later case, the analysis code will
951 // cope with a conservative value, and it will take care to purge
952 // that value once it has finished.
Dan Gohman1b342582009-07-10 16:42:52 +0000953 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000954 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000955 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000956 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000957
958 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000959 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000960 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000961 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000962 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000963 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
964 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman1b342582009-07-10 16:42:52 +0000965 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000966 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000967 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000968 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000969 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000970 const SCEV *Add = getAddExpr(Start, SMul);
971 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000972 getAddExpr(getSignExtendExpr(Start, WideTy),
973 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
974 getSignExtendExpr(Step, WideTy)));
975 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000976 // Return the expression with the addrec on the outside.
977 return getAddRecExpr(getSignExtendExpr(Start, Ty),
978 getSignExtendExpr(Step, Ty),
Dan Gohman1b342582009-07-10 16:42:52 +0000979 L);
980 }
981
982 // If the backedge is guarded by a comparison with the pre-inc value
983 // the addrec is safe. Also, if the entry is guarded by a comparison
984 // with the start value and the backedge is guarded by a comparison
985 // with the post-inc value, the addrec is safe.
986 if (isKnownPositive(Step)) {
987 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
988 getSignedRange(Step).getSignedMax());
989 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
990 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
991 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
992 AR->getPostIncExpr(*this), N)))
993 // Return the expression with the addrec on the outside.
994 return getAddRecExpr(getSignExtendExpr(Start, Ty),
995 getSignExtendExpr(Step, Ty),
996 L);
997 } else if (isKnownNegative(Step)) {
998 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
999 getSignedRange(Step).getSignedMin());
1000 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1001 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1002 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1003 AR->getPostIncExpr(*this), N)))
1004 // Return the expression with the addrec on the outside.
1005 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1006 getSignExtendExpr(Step, Ty),
1007 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001008 }
1009 }
1010 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001011
Dan Gohman1c343752009-06-27 21:21:31 +00001012 FoldingSetNodeID ID;
1013 ID.AddInteger(scSignExtend);
1014 ID.AddPointer(Op);
1015 ID.AddPointer(Ty);
1016 void *IP = 0;
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1018 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1019 new (S) SCEVSignExtendExpr(Op, Ty);
1020 UniqueSCEVs.InsertNode(S, IP);
1021 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001022}
1023
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001024/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1025/// unspecified bits out to the given type.
1026///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001027const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001028 const Type *Ty) {
1029 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1030 "This is not an extending conversion!");
1031 assert(isSCEVable(Ty) &&
1032 "This is not a conversion to a SCEVable type!");
1033 Ty = getEffectiveSCEVType(Ty);
1034
1035 // Sign-extend negative constants.
1036 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1037 if (SC->getValue()->getValue().isNegative())
1038 return getSignExtendExpr(Op, Ty);
1039
1040 // Peel off a truncate cast.
1041 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001042 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001043 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1044 return getAnyExtendExpr(NewOp, Ty);
1045 return getTruncateOrNoop(NewOp, Ty);
1046 }
1047
1048 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001049 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001050 if (!isa<SCEVZeroExtendExpr>(ZExt))
1051 return ZExt;
1052
1053 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001054 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001055 if (!isa<SCEVSignExtendExpr>(SExt))
1056 return SExt;
1057
1058 // If the expression is obviously signed, use the sext cast value.
1059 if (isa<SCEVSMaxExpr>(Op))
1060 return SExt;
1061
1062 // Absent any other information, use the zext cast value.
1063 return ZExt;
1064}
1065
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001066/// CollectAddOperandsWithScales - Process the given Ops list, which is
1067/// a list of operands to be added under the given scale, update the given
1068/// map. This is a helper function for getAddRecExpr. As an example of
1069/// what it does, given a sequence of operands that would form an add
1070/// expression like this:
1071///
1072/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1073///
1074/// where A and B are constants, update the map with these values:
1075///
1076/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1077///
1078/// and add 13 + A*B*29 to AccumulatedConstant.
1079/// This will allow getAddRecExpr to produce this:
1080///
1081/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1082///
1083/// This form often exposes folding opportunities that are hidden in
1084/// the original operand list.
1085///
1086/// Return true iff it appears that any interesting folding opportunities
1087/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1088/// the common case where no interesting opportunities are present, and
1089/// is also used as a check to avoid infinite recursion.
1090///
1091static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001092CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1093 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001094 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001095 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001096 const APInt &Scale,
1097 ScalarEvolution &SE) {
1098 bool Interesting = false;
1099
1100 // Iterate over the add operands.
1101 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1102 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1103 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1104 APInt NewScale =
1105 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1106 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1107 // A multiplication of a constant with another add; recurse.
1108 Interesting |=
1109 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1110 cast<SCEVAddExpr>(Mul->getOperand(1))
1111 ->getOperands(),
1112 NewScale, SE);
1113 } else {
1114 // A multiplication of a constant with some other value. Update
1115 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001116 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1117 const SCEV *Key = SE.getMulExpr(MulOps);
1118 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001119 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001120 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001121 NewOps.push_back(Pair.first->first);
1122 } else {
1123 Pair.first->second += NewScale;
1124 // The map already had an entry for this value, which may indicate
1125 // a folding opportunity.
1126 Interesting = true;
1127 }
1128 }
1129 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1130 // Pull a buried constant out to the outside.
1131 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1132 Interesting = true;
1133 AccumulatedConstant += Scale * C->getValue()->getValue();
1134 } else {
1135 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001136 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001137 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001138 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001139 NewOps.push_back(Pair.first->first);
1140 } else {
1141 Pair.first->second += Scale;
1142 // The map already had an entry for this value, which may indicate
1143 // a folding opportunity.
1144 Interesting = true;
1145 }
1146 }
1147 }
1148
1149 return Interesting;
1150}
1151
1152namespace {
1153 struct APIntCompare {
1154 bool operator()(const APInt &LHS, const APInt &RHS) const {
1155 return LHS.ult(RHS);
1156 }
1157 };
1158}
1159
Dan Gohman6c0866c2009-05-24 23:45:28 +00001160/// getAddExpr - Get a canonical add expression, or something simpler if
1161/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001162const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001163 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001164 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001165#ifndef NDEBUG
1166 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1167 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1168 getEffectiveSCEVType(Ops[0]->getType()) &&
1169 "SCEVAddExpr operand types don't match!");
1170#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001171
1172 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001173 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001174
1175 // If there are any constants, fold them together.
1176 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001177 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001178 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001179 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001180 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001181 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001182 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1183 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001184 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001185 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001186 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 }
1188
1189 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001190 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001191 Ops.erase(Ops.begin());
1192 --Idx;
1193 }
1194 }
1195
Chris Lattner627018b2004-04-07 16:16:11 +00001196 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001197
Chris Lattner53e677a2004-04-02 20:23:17 +00001198 // Okay, check to see if the same value occurs in the operand list twice. If
1199 // so, merge them together into an multiply expression. Since we sorted the
1200 // list, these values are required to be adjacent.
1201 const Type *Ty = Ops[0]->getType();
1202 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1203 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1204 // Found a match, merge the two values into a multiply, and add any
1205 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001206 const SCEV *Two = getIntegerSCEV(2, Ty);
1207 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001208 if (Ops.size() == 2)
1209 return Mul;
1210 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1211 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001212 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001213 }
1214
Dan Gohman728c7f32009-05-08 21:03:19 +00001215 // Check for truncates. If all the operands are truncated from the same
1216 // type, see if factoring out the truncate would permit the result to be
1217 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1218 // if the contents of the resulting outer trunc fold to something simple.
1219 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1220 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1221 const Type *DstType = Trunc->getType();
1222 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001223 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001224 bool Ok = true;
1225 // Check all the operands to see if they can be represented in the
1226 // source type of the truncate.
1227 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1228 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1229 if (T->getOperand()->getType() != SrcType) {
1230 Ok = false;
1231 break;
1232 }
1233 LargeOps.push_back(T->getOperand());
1234 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1235 // This could be either sign or zero extension, but sign extension
1236 // is much more likely to be foldable here.
1237 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1238 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001239 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001240 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1241 if (const SCEVTruncateExpr *T =
1242 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1243 if (T->getOperand()->getType() != SrcType) {
1244 Ok = false;
1245 break;
1246 }
1247 LargeMulOps.push_back(T->getOperand());
1248 } else if (const SCEVConstant *C =
1249 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1250 // This could be either sign or zero extension, but sign extension
1251 // is much more likely to be foldable here.
1252 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1253 } else {
1254 Ok = false;
1255 break;
1256 }
1257 }
1258 if (Ok)
1259 LargeOps.push_back(getMulExpr(LargeMulOps));
1260 } else {
1261 Ok = false;
1262 break;
1263 }
1264 }
1265 if (Ok) {
1266 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001267 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001268 // If it folds to something simple, use it. Otherwise, don't.
1269 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1270 return getTruncateExpr(Fold, DstType);
1271 }
1272 }
1273
1274 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001275 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1276 ++Idx;
1277
1278 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001279 if (Idx < Ops.size()) {
1280 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001281 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001282 // If we have an add, expand the add operands onto the end of the operands
1283 // list.
1284 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1285 Ops.erase(Ops.begin()+Idx);
1286 DeletedAdd = true;
1287 }
1288
1289 // If we deleted at least one add, we added operands to the end of the list,
1290 // and they are not necessarily sorted. Recurse to resort and resimplify
1291 // any operands we just aquired.
1292 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001293 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 }
1295
1296 // Skip over the add expression until we get to a multiply.
1297 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1298 ++Idx;
1299
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001300 // Check to see if there are any folding opportunities present with
1301 // operands multiplied by constant values.
1302 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1303 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001304 DenseMap<const SCEV *, APInt> M;
1305 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001306 APInt AccumulatedConstant(BitWidth, 0);
1307 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1308 Ops, APInt(BitWidth, 1), *this)) {
1309 // Some interesting folding opportunity is present, so its worthwhile to
1310 // re-generate the operands list. Group the operands by constant scale,
1311 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001312 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1313 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001314 E = NewOps.end(); I != E; ++I)
1315 MulOpLists[M.find(*I)->second].push_back(*I);
1316 // Re-generate the operands list.
1317 Ops.clear();
1318 if (AccumulatedConstant != 0)
1319 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001320 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1321 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001322 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001323 Ops.push_back(getMulExpr(getConstant(I->first),
1324 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001325 if (Ops.empty())
1326 return getIntegerSCEV(0, Ty);
1327 if (Ops.size() == 1)
1328 return Ops[0];
1329 return getAddExpr(Ops);
1330 }
1331 }
1332
Chris Lattner53e677a2004-04-02 20:23:17 +00001333 // If we are adding something to a multiply expression, make sure the
1334 // something is not already an operand of the multiply. If so, merge it into
1335 // the multiply.
1336 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001337 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001339 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001340 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001341 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001342 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001343 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001344 if (Mul->getNumOperands() != 2) {
1345 // If the multiply has more than two operands, we must get the
1346 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001347 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001348 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001349 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001350 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001351 const SCEV *One = getIntegerSCEV(1, Ty);
1352 const SCEV *AddOne = getAddExpr(InnerMul, One);
1353 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001354 if (Ops.size() == 2) return OuterMul;
1355 if (AddOp < Idx) {
1356 Ops.erase(Ops.begin()+AddOp);
1357 Ops.erase(Ops.begin()+Idx-1);
1358 } else {
1359 Ops.erase(Ops.begin()+Idx);
1360 Ops.erase(Ops.begin()+AddOp-1);
1361 }
1362 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001363 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001365
Chris Lattner53e677a2004-04-02 20:23:17 +00001366 // Check this multiply against other multiplies being added together.
1367 for (unsigned OtherMulIdx = Idx+1;
1368 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1369 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001370 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001371 // If MulOp occurs in OtherMul, we can fold the two multiplies
1372 // together.
1373 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1374 OMulOp != e; ++OMulOp)
1375 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1376 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001377 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001379 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1380 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001381 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001382 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001383 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001384 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001385 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001386 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1387 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001388 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001389 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001390 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001391 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1392 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001393 if (Ops.size() == 2) return OuterMul;
1394 Ops.erase(Ops.begin()+Idx);
1395 Ops.erase(Ops.begin()+OtherMulIdx-1);
1396 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001397 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001398 }
1399 }
1400 }
1401 }
1402
1403 // If there are any add recurrences in the operands list, see if any other
1404 // added values are loop invariant. If so, we can fold them into the
1405 // recurrence.
1406 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1407 ++Idx;
1408
1409 // Scan over all recurrences, trying to fold loop invariants into them.
1410 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1411 // Scan all of the other operands to this add and add them to the vector if
1412 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001413 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001414 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001415 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1416 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1417 LIOps.push_back(Ops[i]);
1418 Ops.erase(Ops.begin()+i);
1419 --i; --e;
1420 }
1421
1422 // If we found some loop invariants, fold them into the recurrence.
1423 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001424 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001425 LIOps.push_back(AddRec->getStart());
1426
Dan Gohman0bba49c2009-07-07 17:06:11 +00001427 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001428 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001429 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001430
Dan Gohman0bba49c2009-07-07 17:06:11 +00001431 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001432 // If all of the other operands were loop invariant, we are done.
1433 if (Ops.size() == 1) return NewRec;
1434
1435 // Otherwise, add the folded AddRec by the non-liv parts.
1436 for (unsigned i = 0;; ++i)
1437 if (Ops[i] == AddRec) {
1438 Ops[i] = NewRec;
1439 break;
1440 }
Dan Gohman246b2562007-10-22 18:31:58 +00001441 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001442 }
1443
1444 // Okay, if there weren't any loop invariants to be folded, check to see if
1445 // there are multiple AddRec's with the same loop induction variable being
1446 // added together. If so, we can fold them.
1447 for (unsigned OtherIdx = Idx+1;
1448 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1449 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001450 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001451 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1452 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001453 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1454 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001455 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1456 if (i >= NewOps.size()) {
1457 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1458 OtherAddRec->op_end());
1459 break;
1460 }
Dan Gohman246b2562007-10-22 18:31:58 +00001461 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001463 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001464
1465 if (Ops.size() == 2) return NewAddRec;
1466
1467 Ops.erase(Ops.begin()+Idx);
1468 Ops.erase(Ops.begin()+OtherIdx-1);
1469 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001470 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 }
1472 }
1473
1474 // Otherwise couldn't fold anything into this recurrence. Move onto the
1475 // next one.
1476 }
1477
1478 // Okay, it looks like we really DO need an add expr. Check to see if we
1479 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001480 FoldingSetNodeID ID;
1481 ID.AddInteger(scAddExpr);
1482 ID.AddInteger(Ops.size());
1483 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1484 ID.AddPointer(Ops[i]);
1485 void *IP = 0;
1486 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1487 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1488 new (S) SCEVAddExpr(Ops);
1489 UniqueSCEVs.InsertNode(S, IP);
1490 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001491}
1492
1493
Dan Gohman6c0866c2009-05-24 23:45:28 +00001494/// getMulExpr - Get a canonical multiply expression, or something simpler if
1495/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001496const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001497 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001498#ifndef NDEBUG
1499 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1500 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1501 getEffectiveSCEVType(Ops[0]->getType()) &&
1502 "SCEVMulExpr operand types don't match!");
1503#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001504
1505 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001506 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001507
1508 // If there are any constants, fold them together.
1509 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001510 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001511
1512 // C1*(C2+V) -> C1*C2 + C1*V
1513 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001514 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 if (Add->getNumOperands() == 2 &&
1516 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001517 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1518 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001519
1520
1521 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001522 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001523 // We found two constants, fold them together!
Dan Gohman64a845e2009-06-24 04:48:43 +00001524 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001525 RHSC->getValue()->getValue());
1526 Ops[0] = getConstant(Fold);
1527 Ops.erase(Ops.begin()+1); // Erase the folded element
1528 if (Ops.size() == 1) return Ops[0];
1529 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001530 }
1531
1532 // If we are left with a constant one being multiplied, strip it off.
1533 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1534 Ops.erase(Ops.begin());
1535 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001536 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 // If we have a multiply of zero, it will always be zero.
1538 return Ops[0];
1539 }
1540 }
1541
1542 // Skip over the add expression until we get to a multiply.
1543 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1544 ++Idx;
1545
1546 if (Ops.size() == 1)
1547 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001548
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 // If there are mul operands inline them all into this expression.
1550 if (Idx < Ops.size()) {
1551 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001552 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001553 // If we have an mul, expand the mul operands onto the end of the operands
1554 // list.
1555 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1556 Ops.erase(Ops.begin()+Idx);
1557 DeletedMul = true;
1558 }
1559
1560 // If we deleted at least one mul, we added operands to the end of the list,
1561 // and they are not necessarily sorted. Recurse to resort and resimplify
1562 // any operands we just aquired.
1563 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001564 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 }
1566
1567 // If there are any add recurrences in the operands list, see if any other
1568 // added values are loop invariant. If so, we can fold them into the
1569 // recurrence.
1570 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1571 ++Idx;
1572
1573 // Scan over all recurrences, trying to fold loop invariants into them.
1574 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1575 // Scan all of the other operands to this mul and add them to the vector if
1576 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001577 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001578 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1580 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1581 LIOps.push_back(Ops[i]);
1582 Ops.erase(Ops.begin()+i);
1583 --i; --e;
1584 }
1585
1586 // If we found some loop invariants, fold them into the recurrence.
1587 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001588 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001589 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 NewOps.reserve(AddRec->getNumOperands());
1591 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001592 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001593 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001594 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 } else {
1596 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001597 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001598 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001599 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001600 }
1601 }
1602
Dan Gohman0bba49c2009-07-07 17:06:11 +00001603 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001604
1605 // If all of the other operands were loop invariant, we are done.
1606 if (Ops.size() == 1) return NewRec;
1607
1608 // Otherwise, multiply the folded AddRec by the non-liv parts.
1609 for (unsigned i = 0;; ++i)
1610 if (Ops[i] == AddRec) {
1611 Ops[i] = NewRec;
1612 break;
1613 }
Dan Gohman246b2562007-10-22 18:31:58 +00001614 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 }
1616
1617 // Okay, if there weren't any loop invariants to be folded, check to see if
1618 // there are multiple AddRec's with the same loop induction variable being
1619 // multiplied together. If so, we can fold them.
1620 for (unsigned OtherIdx = Idx+1;
1621 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1622 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001623 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001624 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1625 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001626 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001627 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001628 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001629 const SCEV *B = F->getStepRecurrence(*this);
1630 const SCEV *D = G->getStepRecurrence(*this);
1631 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001632 getMulExpr(G, B),
1633 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001634 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001635 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001636 if (Ops.size() == 2) return NewAddRec;
1637
1638 Ops.erase(Ops.begin()+Idx);
1639 Ops.erase(Ops.begin()+OtherIdx-1);
1640 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001641 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001642 }
1643 }
1644
1645 // Otherwise couldn't fold anything into this recurrence. Move onto the
1646 // next one.
1647 }
1648
1649 // Okay, it looks like we really DO need an mul expr. Check to see if we
1650 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001651 FoldingSetNodeID ID;
1652 ID.AddInteger(scMulExpr);
1653 ID.AddInteger(Ops.size());
1654 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1655 ID.AddPointer(Ops[i]);
1656 void *IP = 0;
1657 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1658 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1659 new (S) SCEVMulExpr(Ops);
1660 UniqueSCEVs.InsertNode(S, IP);
1661 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001662}
1663
Dan Gohman6c0866c2009-05-24 23:45:28 +00001664/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1665/// possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001666const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1667 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001668 assert(getEffectiveSCEVType(LHS->getType()) ==
1669 getEffectiveSCEVType(RHS->getType()) &&
1670 "SCEVUDivExpr operand types don't match!");
1671
Dan Gohman622ed672009-05-04 22:02:23 +00001672 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001674 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001675 if (RHSC->isZero())
1676 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001677
Dan Gohman185cf032009-05-08 20:18:49 +00001678 // Determine if the division can be folded into the operands of
1679 // its operands.
1680 // TODO: Generalize this to non-constants by using known-bits information.
1681 const Type *Ty = LHS->getType();
1682 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1683 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1684 // For non-power-of-two values, effectively round the value up to the
1685 // nearest power of two.
1686 if (!RHSC->getValue()->getValue().isPowerOf2())
1687 ++MaxShiftAmt;
1688 const IntegerType *ExtTy =
1689 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1690 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1691 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1692 if (const SCEVConstant *Step =
1693 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1694 if (!Step->getValue()->getValue()
1695 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001696 getZeroExtendExpr(AR, ExtTy) ==
1697 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1698 getZeroExtendExpr(Step, ExtTy),
1699 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001700 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001701 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1702 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1703 return getAddRecExpr(Operands, AR->getLoop());
1704 }
1705 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001706 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001707 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001708 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1709 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1710 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001711 // Find an operand that's safely divisible.
1712 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001713 const SCEV *Op = M->getOperand(i);
1714 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001715 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001716 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1717 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001718 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001719 Operands[i] = Div;
1720 return getMulExpr(Operands);
1721 }
1722 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001723 }
Dan Gohman185cf032009-05-08 20:18:49 +00001724 // (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 +00001725 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001726 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001727 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1728 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1729 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1730 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001731 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001732 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001733 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1734 break;
1735 Operands.push_back(Op);
1736 }
1737 if (Operands.size() == A->getNumOperands())
1738 return getAddExpr(Operands);
1739 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001740 }
Dan Gohman185cf032009-05-08 20:18:49 +00001741
1742 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001743 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001744 Constant *LHSCV = LHSC->getValue();
1745 Constant *RHSCV = RHSC->getValue();
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001746 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1747 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 }
1749 }
1750
Dan Gohman1c343752009-06-27 21:21:31 +00001751 FoldingSetNodeID ID;
1752 ID.AddInteger(scUDivExpr);
1753 ID.AddPointer(LHS);
1754 ID.AddPointer(RHS);
1755 void *IP = 0;
1756 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1757 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1758 new (S) SCEVUDivExpr(LHS, RHS);
1759 UniqueSCEVs.InsertNode(S, IP);
1760 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001761}
1762
1763
Dan Gohman6c0866c2009-05-24 23:45:28 +00001764/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1765/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001766const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1767 const SCEV *Step, const Loop *L) {
1768 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001769 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001770 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001771 if (StepChrec->getLoop() == L) {
1772 Operands.insert(Operands.end(), StepChrec->op_begin(),
1773 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001774 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001775 }
1776
1777 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001778 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001779}
1780
Dan Gohman6c0866c2009-05-24 23:45:28 +00001781/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1782/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001783const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001784ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001785 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001787#ifndef NDEBUG
1788 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1789 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1790 getEffectiveSCEVType(Operands[0]->getType()) &&
1791 "SCEVAddRecExpr operand types don't match!");
1792#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001793
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001794 if (Operands.back()->isZero()) {
1795 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001796 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001797 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001798
Dan Gohmand9cc7492008-08-08 18:33:12 +00001799 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001800 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001801 const Loop* NestedLoop = NestedAR->getLoop();
1802 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001803 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001804 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001805 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001806 // AddRecs require their operands be loop-invariant with respect to their
1807 // loops. Don't perform this transformation if it would break this
1808 // requirement.
1809 bool AllInvariant = true;
1810 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1811 if (!Operands[i]->isLoopInvariant(L)) {
1812 AllInvariant = false;
1813 break;
1814 }
1815 if (AllInvariant) {
1816 NestedOperands[0] = getAddRecExpr(Operands, L);
1817 AllInvariant = true;
1818 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1819 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1820 AllInvariant = false;
1821 break;
1822 }
1823 if (AllInvariant)
1824 // Ok, both add recurrences are valid after the transformation.
1825 return getAddRecExpr(NestedOperands, NestedLoop);
1826 }
1827 // Reset Operands to its original state.
1828 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001829 }
1830 }
1831
Dan Gohman1c343752009-06-27 21:21:31 +00001832 FoldingSetNodeID ID;
1833 ID.AddInteger(scAddRecExpr);
1834 ID.AddInteger(Operands.size());
1835 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1836 ID.AddPointer(Operands[i]);
1837 ID.AddPointer(L);
1838 void *IP = 0;
1839 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1840 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1841 new (S) SCEVAddRecExpr(Operands, L);
1842 UniqueSCEVs.InsertNode(S, IP);
1843 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001844}
1845
Dan Gohman9311ef62009-06-24 14:49:00 +00001846const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1847 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001848 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001849 Ops.push_back(LHS);
1850 Ops.push_back(RHS);
1851 return getSMaxExpr(Ops);
1852}
1853
Dan Gohman0bba49c2009-07-07 17:06:11 +00001854const SCEV *
1855ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001856 assert(!Ops.empty() && "Cannot get empty smax!");
1857 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001858#ifndef NDEBUG
1859 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1860 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1861 getEffectiveSCEVType(Ops[0]->getType()) &&
1862 "SCEVSMaxExpr operand types don't match!");
1863#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001864
1865 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001866 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001867
1868 // If there are any constants, fold them together.
1869 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001870 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001871 ++Idx;
1872 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001873 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001874 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001875 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001876 APIntOps::smax(LHSC->getValue()->getValue(),
1877 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001878 Ops[0] = getConstant(Fold);
1879 Ops.erase(Ops.begin()+1); // Erase the folded element
1880 if (Ops.size() == 1) return Ops[0];
1881 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001882 }
1883
Dan Gohmane5aceed2009-06-24 14:46:22 +00001884 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001885 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1886 Ops.erase(Ops.begin());
1887 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001888 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1889 // If we have an smax with a constant maximum-int, it will always be
1890 // maximum-int.
1891 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001892 }
1893 }
1894
1895 if (Ops.size() == 1) return Ops[0];
1896
1897 // Find the first SMax
1898 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1899 ++Idx;
1900
1901 // Check to see if one of the operands is an SMax. If so, expand its operands
1902 // onto our operand list, and recurse to simplify.
1903 if (Idx < Ops.size()) {
1904 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001905 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001906 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1907 Ops.erase(Ops.begin()+Idx);
1908 DeletedSMax = true;
1909 }
1910
1911 if (DeletedSMax)
1912 return getSMaxExpr(Ops);
1913 }
1914
1915 // Okay, check to see if the same value occurs in the operand list twice. If
1916 // so, delete one. Since we sorted the list, these values are required to
1917 // be adjacent.
1918 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1919 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1920 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1921 --i; --e;
1922 }
1923
1924 if (Ops.size() == 1) return Ops[0];
1925
1926 assert(!Ops.empty() && "Reduced smax down to nothing!");
1927
Nick Lewycky3e630762008-02-20 06:48:22 +00001928 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001929 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001930 FoldingSetNodeID ID;
1931 ID.AddInteger(scSMaxExpr);
1932 ID.AddInteger(Ops.size());
1933 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1934 ID.AddPointer(Ops[i]);
1935 void *IP = 0;
1936 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1937 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1938 new (S) SCEVSMaxExpr(Ops);
1939 UniqueSCEVs.InsertNode(S, IP);
1940 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001941}
1942
Dan Gohman9311ef62009-06-24 14:49:00 +00001943const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1944 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001945 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001946 Ops.push_back(LHS);
1947 Ops.push_back(RHS);
1948 return getUMaxExpr(Ops);
1949}
1950
Dan Gohman0bba49c2009-07-07 17:06:11 +00001951const SCEV *
1952ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001953 assert(!Ops.empty() && "Cannot get empty umax!");
1954 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001955#ifndef NDEBUG
1956 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1957 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1958 getEffectiveSCEVType(Ops[0]->getType()) &&
1959 "SCEVUMaxExpr operand types don't match!");
1960#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001961
1962 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001963 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001964
1965 // If there are any constants, fold them together.
1966 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001967 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001968 ++Idx;
1969 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001970 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001971 // We found two constants, fold them together!
1972 ConstantInt *Fold = ConstantInt::get(
1973 APIntOps::umax(LHSC->getValue()->getValue(),
1974 RHSC->getValue()->getValue()));
1975 Ops[0] = getConstant(Fold);
1976 Ops.erase(Ops.begin()+1); // Erase the folded element
1977 if (Ops.size() == 1) return Ops[0];
1978 LHSC = cast<SCEVConstant>(Ops[0]);
1979 }
1980
Dan Gohmane5aceed2009-06-24 14:46:22 +00001981 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001982 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1983 Ops.erase(Ops.begin());
1984 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001985 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1986 // If we have an umax with a constant maximum-int, it will always be
1987 // maximum-int.
1988 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001989 }
1990 }
1991
1992 if (Ops.size() == 1) return Ops[0];
1993
1994 // Find the first UMax
1995 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1996 ++Idx;
1997
1998 // Check to see if one of the operands is a UMax. If so, expand its operands
1999 // onto our operand list, and recurse to simplify.
2000 if (Idx < Ops.size()) {
2001 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002002 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002003 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2004 Ops.erase(Ops.begin()+Idx);
2005 DeletedUMax = true;
2006 }
2007
2008 if (DeletedUMax)
2009 return getUMaxExpr(Ops);
2010 }
2011
2012 // Okay, check to see if the same value occurs in the operand list twice. If
2013 // so, delete one. Since we sorted the list, these values are required to
2014 // be adjacent.
2015 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2016 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2017 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2018 --i; --e;
2019 }
2020
2021 if (Ops.size() == 1) return Ops[0];
2022
2023 assert(!Ops.empty() && "Reduced umax down to nothing!");
2024
2025 // Okay, it looks like we really DO need a umax expr. Check to see if we
2026 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002027 FoldingSetNodeID ID;
2028 ID.AddInteger(scUMaxExpr);
2029 ID.AddInteger(Ops.size());
2030 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2031 ID.AddPointer(Ops[i]);
2032 void *IP = 0;
2033 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2034 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2035 new (S) SCEVUMaxExpr(Ops);
2036 UniqueSCEVs.InsertNode(S, IP);
2037 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002038}
2039
Dan Gohman9311ef62009-06-24 14:49:00 +00002040const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2041 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002042 // ~smax(~x, ~y) == smin(x, y).
2043 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2044}
2045
Dan Gohman9311ef62009-06-24 14:49:00 +00002046const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2047 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002048 // ~umax(~x, ~y) == umin(x, y)
2049 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2050}
2051
Dan Gohman0bba49c2009-07-07 17:06:11 +00002052const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002053 // Don't attempt to do anything other than create a SCEVUnknown object
2054 // here. createSCEV only calls getUnknown after checking for all other
2055 // interesting possibilities, and any other code that calls getUnknown
2056 // is doing so in order to hide a value from SCEV canonicalization.
2057
Dan Gohman1c343752009-06-27 21:21:31 +00002058 FoldingSetNodeID ID;
2059 ID.AddInteger(scUnknown);
2060 ID.AddPointer(V);
2061 void *IP = 0;
2062 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2063 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2064 new (S) SCEVUnknown(V);
2065 UniqueSCEVs.InsertNode(S, IP);
2066 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002067}
2068
Chris Lattner53e677a2004-04-02 20:23:17 +00002069//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002070// Basic SCEV Analysis and PHI Idiom Recognition Code
2071//
2072
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002073/// isSCEVable - Test if values of the given type are analyzable within
2074/// the SCEV framework. This primarily includes integer types, and it
2075/// can optionally include pointer types if the ScalarEvolution class
2076/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002077bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002078 // Integers are always SCEVable.
2079 if (Ty->isInteger())
2080 return true;
2081
2082 // Pointers are SCEVable if TargetData information is available
2083 // to provide pointer size information.
2084 if (isa<PointerType>(Ty))
2085 return TD != NULL;
2086
2087 // Otherwise it's not SCEVable.
2088 return false;
2089}
2090
2091/// getTypeSizeInBits - Return the size in bits of the specified type,
2092/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002093uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002094 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2095
2096 // If we have a TargetData, use it!
2097 if (TD)
2098 return TD->getTypeSizeInBits(Ty);
2099
2100 // Otherwise, we support only integer types.
2101 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2102 return Ty->getPrimitiveSizeInBits();
2103}
2104
2105/// getEffectiveSCEVType - Return a type with the same bitwidth as
2106/// the given type and which represents how SCEV will treat the given
2107/// type, for which isSCEVable must return true. For pointer types,
2108/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002109const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002110 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2111
2112 if (Ty->isInteger())
2113 return Ty;
2114
2115 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2116 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002117}
Chris Lattner53e677a2004-04-02 20:23:17 +00002118
Dan Gohman0bba49c2009-07-07 17:06:11 +00002119const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002120 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002121}
2122
Chris Lattner53e677a2004-04-02 20:23:17 +00002123/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2124/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002125const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002126 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002127
Dan Gohman0bba49c2009-07-07 17:06:11 +00002128 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002129 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002130 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002131 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002132 return S;
2133}
2134
Dan Gohman6bbcba12009-06-24 00:54:57 +00002135/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002136/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002137const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002138 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2139 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002140}
2141
2142/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2143///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002144const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002145 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanb8be8b72009-06-24 00:38:39 +00002146 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002147
2148 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002149 Ty = getEffectiveSCEVType(Ty);
2150 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002151}
2152
2153/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002154const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002155 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanb8be8b72009-06-24 00:38:39 +00002156 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002157
2158 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002159 Ty = getEffectiveSCEVType(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002160 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00002161 return getMinusSCEV(AllOnes, V);
2162}
2163
2164/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2165///
Dan Gohman9311ef62009-06-24 14:49:00 +00002166const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2167 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002168 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002169 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002170}
2171
2172/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2173/// input value to the specified type. If the type must be extended, it is zero
2174/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002175const SCEV *
2176ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002177 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002178 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002179 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2180 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002181 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002182 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002183 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002184 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002185 return getTruncateExpr(V, Ty);
2186 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002187}
2188
2189/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2190/// input value to the specified type. If the type must be extended, it is sign
2191/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002192const SCEV *
2193ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002194 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002195 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002196 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2197 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002198 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002199 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002200 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002201 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002202 return getTruncateExpr(V, Ty);
2203 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002204}
2205
Dan Gohman467c4302009-05-13 03:46:30 +00002206/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2207/// input value to the specified type. If the type must be extended, it is zero
2208/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002209const SCEV *
2210ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002211 const Type *SrcTy = V->getType();
2212 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2213 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2214 "Cannot noop or zero extend with non-integer arguments!");
2215 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2216 "getNoopOrZeroExtend cannot truncate!");
2217 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2218 return V; // No conversion
2219 return getZeroExtendExpr(V, Ty);
2220}
2221
2222/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2223/// input value to the specified type. If the type must be extended, it is sign
2224/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002225const SCEV *
2226ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002227 const Type *SrcTy = V->getType();
2228 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2229 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2230 "Cannot noop or sign extend with non-integer arguments!");
2231 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2232 "getNoopOrSignExtend cannot truncate!");
2233 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2234 return V; // No conversion
2235 return getSignExtendExpr(V, Ty);
2236}
2237
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002238/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2239/// the input value to the specified type. If the type must be extended,
2240/// it is extended with unspecified bits. The conversion must not be
2241/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002242const SCEV *
2243ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002244 const Type *SrcTy = V->getType();
2245 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2246 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2247 "Cannot noop or any extend with non-integer arguments!");
2248 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2249 "getNoopOrAnyExtend cannot truncate!");
2250 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2251 return V; // No conversion
2252 return getAnyExtendExpr(V, Ty);
2253}
2254
Dan Gohman467c4302009-05-13 03:46:30 +00002255/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2256/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002257const SCEV *
2258ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002259 const Type *SrcTy = V->getType();
2260 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2261 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2262 "Cannot truncate or noop with non-integer arguments!");
2263 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2264 "getTruncateOrNoop cannot extend!");
2265 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2266 return V; // No conversion
2267 return getTruncateExpr(V, Ty);
2268}
2269
Dan Gohmana334aa72009-06-22 00:31:57 +00002270/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2271/// the types using zero-extension, and then perform a umax operation
2272/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002273const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2274 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002275 const SCEV *PromotedLHS = LHS;
2276 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002277
2278 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2279 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2280 else
2281 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2282
2283 return getUMaxExpr(PromotedLHS, PromotedRHS);
2284}
2285
Dan Gohmanc9759e82009-06-22 15:03:27 +00002286/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2287/// the types using zero-extension, and then perform a umin operation
2288/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002289const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2290 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002291 const SCEV *PromotedLHS = LHS;
2292 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002293
2294 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2295 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2296 else
2297 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2298
2299 return getUMinExpr(PromotedLHS, PromotedRHS);
2300}
2301
Chris Lattner4dc534c2005-02-13 04:37:18 +00002302/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2303/// the specified instruction and replaces any references to the symbolic value
2304/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002305void
2306ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2307 const SCEV *SymName,
2308 const SCEV *NewVal) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002309 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002310 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002311 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002312
Dan Gohman0bba49c2009-07-07 17:06:11 +00002313 const SCEV *NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002314 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002315 if (NV == SI->second) return; // No change.
2316
2317 SI->second = NV; // Update the scalars map!
2318
2319 // Any instruction values that use this instruction might also need to be
2320 // updated!
2321 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2322 UI != E; ++UI)
2323 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2324}
Chris Lattner53e677a2004-04-02 20:23:17 +00002325
2326/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2327/// a loop header, making it a potential recurrence, or it doesn't.
2328///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002329const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002330 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002331 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002332 if (L->getHeader() == PN->getParent()) {
2333 // If it lives in the loop header, it has two incoming values, one
2334 // from outside the loop, and one from inside.
2335 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2336 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002337
Chris Lattner53e677a2004-04-02 20:23:17 +00002338 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002339 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002340 assert(Scalars.find(PN) == Scalars.end() &&
2341 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002342 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002343
2344 // Using this symbolic name for the PHI, analyze the value coming around
2345 // the back-edge.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002346 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002347
2348 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2349 // has a special value for the first iteration of the loop.
2350
2351 // If the value coming around the backedge is an add with the symbolic
2352 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002353 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002354 // If there is a single occurrence of the symbolic value, replace it
2355 // with a recurrence.
2356 unsigned FoundIndex = Add->getNumOperands();
2357 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2358 if (Add->getOperand(i) == SymbolicName)
2359 if (FoundIndex == e) {
2360 FoundIndex = i;
2361 break;
2362 }
2363
2364 if (FoundIndex != Add->getNumOperands()) {
2365 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002366 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002367 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2368 if (i != FoundIndex)
2369 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002370 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002371
2372 // This is not a valid addrec if the step amount is varying each
2373 // loop iteration, but is not itself an addrec in this loop.
2374 if (Accum->isLoopInvariant(L) ||
2375 (isa<SCEVAddRecExpr>(Accum) &&
2376 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002377 const SCEV *StartVal =
2378 getSCEV(PN->getIncomingValue(IncomingEdge));
2379 const SCEV *PHISCEV =
2380 getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002381
2382 // Okay, for the entire analysis of this edge we assumed the PHI
2383 // to be symbolic. We now need to go back and update all of the
2384 // entries for the scalars that use the PHI (except for the PHI
2385 // itself) to use the new analyzed value instead of the "symbolic"
2386 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002387 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002388 return PHISCEV;
2389 }
2390 }
Dan Gohman622ed672009-05-04 22:02:23 +00002391 } else if (const SCEVAddRecExpr *AddRec =
2392 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002393 // Otherwise, this could be a loop like this:
2394 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2395 // In this case, j = {1,+,1} and BEValue is j.
2396 // Because the other in-value of i (0) fits the evolution of BEValue
2397 // i really is an addrec evolution.
2398 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002399 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002400
2401 // If StartVal = j.start - j.stride, we can use StartVal as the
2402 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002403 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002404 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002405 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002406 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002407
2408 // Okay, for the entire analysis of this edge we assumed the PHI
2409 // to be symbolic. We now need to go back and update all of the
2410 // entries for the scalars that use the PHI (except for the PHI
2411 // itself) to use the new analyzed value instead of the "symbolic"
2412 // value.
2413 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2414 return PHISCEV;
2415 }
2416 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002417 }
2418
2419 return SymbolicName;
2420 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002421
Chris Lattner53e677a2004-04-02 20:23:17 +00002422 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002423 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002424}
2425
Dan Gohman26466c02009-05-08 20:26:55 +00002426/// createNodeForGEP - Expand GEP instructions into add and multiply
2427/// operations. This allows them to be analyzed by regular SCEV code.
2428///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002429const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002430
2431 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002432 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002433 // Don't attempt to analyze GEPs over unsized objects.
2434 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2435 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002436 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002437 gep_type_iterator GTI = gep_type_begin(GEP);
2438 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2439 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002440 I != E; ++I) {
2441 Value *Index = *I;
2442 // Compute the (potentially symbolic) offset in bytes for this index.
2443 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2444 // For a struct, add the member offset.
2445 const StructLayout &SL = *TD->getStructLayout(STy);
2446 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2447 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman1b342582009-07-10 16:42:52 +00002448 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002449 } else {
2450 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002451 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002452 if (!isa<PointerType>(LocalOffset->getType()))
2453 // Getelementptr indicies are signed.
Dan Gohman1b342582009-07-10 16:42:52 +00002454 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman26466c02009-05-08 20:26:55 +00002455 LocalOffset =
2456 getMulExpr(LocalOffset,
Dan Gohman1b342582009-07-10 16:42:52 +00002457 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002458 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2459 }
2460 }
2461 return getAddExpr(getSCEV(Base), TotalOffset);
2462}
2463
Nick Lewycky83bb0052007-11-22 07:59:40 +00002464/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2465/// guaranteed to end in (at every loop iteration). It is, at the same time,
2466/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2467/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002468uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002469ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002470 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002471 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002472
Dan Gohman622ed672009-05-04 22:02:23 +00002473 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002474 return std::min(GetMinTrailingZeros(T->getOperand()),
2475 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002476
Dan Gohman622ed672009-05-04 22:02:23 +00002477 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002478 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2479 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2480 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002481 }
2482
Dan Gohman622ed672009-05-04 22:02:23 +00002483 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002484 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2485 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2486 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002487 }
2488
Dan Gohman622ed672009-05-04 22:02:23 +00002489 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002490 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002491 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002492 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002493 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002494 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002495 }
2496
Dan Gohman622ed672009-05-04 22:02:23 +00002497 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002498 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002499 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2500 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002501 for (unsigned i = 1, e = M->getNumOperands();
2502 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002503 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002504 BitWidth);
2505 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002506 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002507
Dan Gohman622ed672009-05-04 22:02:23 +00002508 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002509 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002510 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002511 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002512 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002513 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002514 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002515
Dan Gohman622ed672009-05-04 22:02:23 +00002516 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002517 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002518 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002519 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002520 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002521 return MinOpRes;
2522 }
2523
Dan Gohman622ed672009-05-04 22:02:23 +00002524 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002525 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002526 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002527 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002528 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002529 return MinOpRes;
2530 }
2531
Dan Gohman2c364ad2009-06-19 23:29:04 +00002532 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2533 // For a SCEVUnknown, ask ValueTracking.
2534 unsigned BitWidth = getTypeSizeInBits(U->getType());
2535 APInt Mask = APInt::getAllOnesValue(BitWidth);
2536 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2537 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2538 return Zeros.countTrailingOnes();
2539 }
2540
2541 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002542 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002543}
Chris Lattner53e677a2004-04-02 20:23:17 +00002544
Dan Gohman1b342582009-07-10 16:42:52 +00002545/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2546///
2547ConstantRange
2548ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002549
2550 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman1b342582009-07-10 16:42:52 +00002551 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002552
Dan Gohman1b342582009-07-10 16:42:52 +00002553 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2554 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2555 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2556 X = X.add(getUnsignedRange(Add->getOperand(i)));
2557 return X;
2558 }
2559
2560 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2561 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2562 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2563 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2564 return X;
2565 }
2566
2567 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2568 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2569 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2570 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2571 return X;
2572 }
2573
2574 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2575 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2576 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2577 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2578 return X;
2579 }
2580
2581 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2582 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2583 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2584 return X.udiv(Y);
2585 }
2586
2587 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2588 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2589 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2590 }
2591
2592 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2593 ConstantRange X = getUnsignedRange(SExt->getOperand());
2594 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2595 }
2596
2597 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2598 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2599 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2600 }
2601
2602 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2603
2604 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2605 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2606 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2607 if (!Trip) return FullSet;
2608
2609 // TODO: non-affine addrec
2610 if (AddRec->isAffine()) {
2611 const Type *Ty = AddRec->getType();
2612 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2613 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2614 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2615
2616 const SCEV *Start = AddRec->getStart();
2617 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2618
2619 // Check for overflow.
2620 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2621 return FullSet;
2622
2623 ConstantRange StartRange = getUnsignedRange(Start);
2624 ConstantRange EndRange = getUnsignedRange(End);
2625 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2626 EndRange.getUnsignedMin());
2627 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2628 EndRange.getUnsignedMax());
2629 if (Min.isMinValue() && Max.isMaxValue())
2630 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2631 return ConstantRange(Min, Max+1);
2632 }
2633 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002634 }
2635
2636 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2637 // For a SCEVUnknown, ask ValueTracking.
2638 unsigned BitWidth = getTypeSizeInBits(U->getType());
2639 APInt Mask = APInt::getAllOnesValue(BitWidth);
2640 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2641 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman1b342582009-07-10 16:42:52 +00002642 return ConstantRange(Ones, ~Zeros);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002643 }
2644
Dan Gohman1b342582009-07-10 16:42:52 +00002645 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002646}
2647
Dan Gohman1b342582009-07-10 16:42:52 +00002648/// getSignedRange - Determine the signed range for a particular SCEV.
2649///
2650ConstantRange
2651ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002652
Dan Gohman1b342582009-07-10 16:42:52 +00002653 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2654 return ConstantRange(C->getValue()->getValue());
2655
2656 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2657 ConstantRange X = getSignedRange(Add->getOperand(0));
2658 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2659 X = X.add(getSignedRange(Add->getOperand(i)));
2660 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002661 }
2662
Dan Gohman1b342582009-07-10 16:42:52 +00002663 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2664 ConstantRange X = getSignedRange(Mul->getOperand(0));
2665 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2666 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2667 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002668 }
2669
Dan Gohman1b342582009-07-10 16:42:52 +00002670 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2671 ConstantRange X = getSignedRange(SMax->getOperand(0));
2672 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2673 X = X.smax(getSignedRange(SMax->getOperand(i)));
2674 return X;
2675 }
Dan Gohman62849c02009-06-24 01:05:09 +00002676
Dan Gohman1b342582009-07-10 16:42:52 +00002677 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2678 ConstantRange X = getSignedRange(UMax->getOperand(0));
2679 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2680 X = X.umax(getSignedRange(UMax->getOperand(i)));
2681 return X;
2682 }
Dan Gohman62849c02009-06-24 01:05:09 +00002683
Dan Gohman1b342582009-07-10 16:42:52 +00002684 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2685 ConstantRange X = getSignedRange(UDiv->getLHS());
2686 ConstantRange Y = getSignedRange(UDiv->getRHS());
2687 return X.udiv(Y);
2688 }
Dan Gohman62849c02009-06-24 01:05:09 +00002689
Dan Gohman1b342582009-07-10 16:42:52 +00002690 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2691 ConstantRange X = getSignedRange(ZExt->getOperand());
2692 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2693 }
2694
2695 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2696 ConstantRange X = getSignedRange(SExt->getOperand());
2697 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2698 }
2699
2700 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2701 ConstantRange X = getSignedRange(Trunc->getOperand());
2702 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2703 }
2704
2705 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2706
2707 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2708 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2709 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2710 if (!Trip) return FullSet;
2711
2712 // TODO: non-affine addrec
2713 if (AddRec->isAffine()) {
2714 const Type *Ty = AddRec->getType();
2715 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2716 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2717 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2718
2719 const SCEV *Start = AddRec->getStart();
2720 const SCEV *Step = AddRec->getStepRecurrence(*this);
2721 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2722
2723 // Check for overflow.
2724 if (!(isKnownPositive(Step) &&
2725 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2726 !(isKnownNegative(Step) &&
2727 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2728 return FullSet;
2729
2730 ConstantRange StartRange = getSignedRange(Start);
2731 ConstantRange EndRange = getSignedRange(End);
2732 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2733 EndRange.getSignedMin());
2734 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2735 EndRange.getSignedMax());
2736 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2737 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2738 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002739 }
Dan Gohman62849c02009-06-24 01:05:09 +00002740 }
Dan Gohman62849c02009-06-24 01:05:09 +00002741 }
2742
Dan Gohman2c364ad2009-06-19 23:29:04 +00002743 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2744 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman1b342582009-07-10 16:42:52 +00002745 unsigned BitWidth = getTypeSizeInBits(U->getType());
2746 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2747 if (NS == 1)
2748 return FullSet;
2749 return
2750 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2751 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002752 }
2753
Dan Gohman1b342582009-07-10 16:42:52 +00002754 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002755}
2756
Chris Lattner53e677a2004-04-02 20:23:17 +00002757/// createSCEV - We know that there is no SCEV for the specified value.
2758/// Analyze the expression.
2759///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002760const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002761 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002762 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002763
Dan Gohman6c459a22008-06-22 19:56:46 +00002764 unsigned Opcode = Instruction::UserOp1;
2765 if (Instruction *I = dyn_cast<Instruction>(V))
2766 Opcode = I->getOpcode();
2767 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2768 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002769 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2770 return getConstant(CI);
2771 else if (isa<ConstantPointerNull>(V))
2772 return getIntegerSCEV(0, V->getType());
2773 else if (isa<UndefValue>(V))
2774 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002775 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002776 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002777
Dan Gohman6c459a22008-06-22 19:56:46 +00002778 User *U = cast<User>(V);
2779 switch (Opcode) {
2780 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002781 return getAddExpr(getSCEV(U->getOperand(0)),
2782 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002783 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002784 return getMulExpr(getSCEV(U->getOperand(0)),
2785 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002786 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002787 return getUDivExpr(getSCEV(U->getOperand(0)),
2788 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002789 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002790 return getMinusSCEV(getSCEV(U->getOperand(0)),
2791 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002792 case Instruction::And:
2793 // For an expression like x&255 that merely masks off the high bits,
2794 // use zext(trunc(x)) as the SCEV expression.
2795 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002796 if (CI->isNullValue())
2797 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002798 if (CI->isAllOnesValue())
2799 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002800 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002801
2802 // Instcombine's ShrinkDemandedConstant may strip bits out of
2803 // constants, obscuring what would otherwise be a low-bits mask.
2804 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2805 // knew about to reconstruct a low-bits mask value.
2806 unsigned LZ = A.countLeadingZeros();
2807 unsigned BitWidth = A.getBitWidth();
2808 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2809 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2810 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2811
2812 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2813
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002814 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002815 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002816 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002817 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002818 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002819 }
2820 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002821
Dan Gohman6c459a22008-06-22 19:56:46 +00002822 case Instruction::Or:
2823 // If the RHS of the Or is a constant, we may have something like:
2824 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2825 // optimizations will transparently handle this case.
2826 //
2827 // In order for this transformation to be safe, the LHS must be of the
2828 // form X*(2^n) and the Or constant must be less than 2^n.
2829 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002830 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002831 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002832 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002833 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002834 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002835 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002836 break;
2837 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002838 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002839 // If the RHS of the xor is a signbit, then this is just an add.
2840 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002841 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002842 return getAddExpr(getSCEV(U->getOperand(0)),
2843 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002844
2845 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002846 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002847 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002848
2849 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2850 // This is a variant of the check for xor with -1, and it handles
2851 // the case where instcombine has trimmed non-demanded bits out
2852 // of an xor with -1.
2853 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2854 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2855 if (BO->getOpcode() == Instruction::And &&
2856 LCI->getValue() == CI->getValue())
2857 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002858 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002859 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002860 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002861 const Type *Z0Ty = Z0->getType();
2862 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2863
2864 // If C is a low-bits mask, the zero extend is zerving to
2865 // mask off the high bits. Complement the operand and
2866 // re-apply the zext.
2867 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2868 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2869
2870 // If C is a single bit, it may be in the sign-bit position
2871 // before the zero-extend. In this case, represent the xor
2872 // using an add, which is equivalent, and re-apply the zext.
2873 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2874 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2875 Trunc.isSignBit())
2876 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2877 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002878 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002879 }
2880 break;
2881
2882 case Instruction::Shl:
2883 // Turn shift left of a constant amount into a multiply.
2884 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2885 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2886 Constant *X = ConstantInt::get(
2887 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002888 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002889 }
2890 break;
2891
Nick Lewycky01eaf802008-07-07 06:15:49 +00002892 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002893 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002894 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2895 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2896 Constant *X = ConstantInt::get(
2897 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002898 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002899 }
2900 break;
2901
Dan Gohman4ee29af2009-04-21 02:26:00 +00002902 case Instruction::AShr:
2903 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2904 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2905 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2906 if (L->getOpcode() == Instruction::Shl &&
2907 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002908 unsigned BitWidth = getTypeSizeInBits(U->getType());
2909 uint64_t Amt = BitWidth - CI->getZExtValue();
2910 if (Amt == BitWidth)
2911 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2912 if (Amt > BitWidth)
2913 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002914 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002915 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002916 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002917 U->getType());
2918 }
2919 break;
2920
Dan Gohman6c459a22008-06-22 19:56:46 +00002921 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002922 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002923
2924 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002925 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002926
2927 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002928 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002929
2930 case Instruction::BitCast:
2931 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002932 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002933 return getSCEV(U->getOperand(0));
2934 break;
2935
Dan Gohman2d1be872009-04-16 03:18:22 +00002936 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002937 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002938 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002939 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002940
2941 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002942 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002943 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2944 U->getType());
2945
Dan Gohman26466c02009-05-08 20:26:55 +00002946 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002947 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002948 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002949
Dan Gohman6c459a22008-06-22 19:56:46 +00002950 case Instruction::PHI:
2951 return createNodeForPHI(cast<PHINode>(U));
2952
2953 case Instruction::Select:
2954 // This could be a smax or umax that was lowered earlier.
2955 // Try to recover it.
2956 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2957 Value *LHS = ICI->getOperand(0);
2958 Value *RHS = ICI->getOperand(1);
2959 switch (ICI->getPredicate()) {
2960 case ICmpInst::ICMP_SLT:
2961 case ICmpInst::ICMP_SLE:
2962 std::swap(LHS, RHS);
2963 // fall through
2964 case ICmpInst::ICMP_SGT:
2965 case ICmpInst::ICMP_SGE:
2966 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002967 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002968 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002969 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002970 break;
2971 case ICmpInst::ICMP_ULT:
2972 case ICmpInst::ICMP_ULE:
2973 std::swap(LHS, RHS);
2974 // fall through
2975 case ICmpInst::ICMP_UGT:
2976 case ICmpInst::ICMP_UGE:
2977 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002978 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002979 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002980 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002981 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002982 case ICmpInst::ICMP_NE:
2983 // n != 0 ? n : 1 -> umax(n, 1)
2984 if (LHS == U->getOperand(1) &&
2985 isa<ConstantInt>(U->getOperand(2)) &&
2986 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2987 isa<ConstantInt>(RHS) &&
2988 cast<ConstantInt>(RHS)->isZero())
2989 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2990 break;
2991 case ICmpInst::ICMP_EQ:
2992 // n == 0 ? 1 : n -> umax(n, 1)
2993 if (LHS == U->getOperand(2) &&
2994 isa<ConstantInt>(U->getOperand(1)) &&
2995 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2996 isa<ConstantInt>(RHS) &&
2997 cast<ConstantInt>(RHS)->isZero())
2998 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2999 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003000 default:
3001 break;
3002 }
3003 }
3004
3005 default: // We cannot analyze this expression.
3006 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003007 }
3008
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003009 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003010}
3011
3012
3013
3014//===----------------------------------------------------------------------===//
3015// Iteration Count Computation Code
3016//
3017
Dan Gohman46bdfb02009-02-24 18:55:53 +00003018/// getBackedgeTakenCount - If the specified loop has a predictable
3019/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3020/// object. The backedge-taken count is the number of times the loop header
3021/// will be branched to from within the loop. This is one less than the
3022/// trip count of the loop, since it doesn't count the first iteration,
3023/// when the header is branched to from outside the loop.
3024///
3025/// Note that it is not valid to call this method on a loop without a
3026/// loop-invariant backedge-taken count (see
3027/// hasLoopInvariantBackedgeTakenCount).
3028///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003029const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003030 return getBackedgeTakenInfo(L).Exact;
3031}
3032
3033/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3034/// return the least SCEV value that is known never to be less than the
3035/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003036const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003037 return getBackedgeTakenInfo(L).Max;
3038}
3039
Dan Gohman59ae6b92009-07-08 19:23:34 +00003040/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3041/// onto the given Worklist.
3042static void
3043PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3044 BasicBlock *Header = L->getHeader();
3045
3046 // Push all Loop-header PHIs onto the Worklist stack.
3047 for (BasicBlock::iterator I = Header->begin();
3048 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3049 Worklist.push_back(PN);
3050}
3051
3052/// PushDefUseChildren - Push users of the given Instruction
3053/// onto the given Worklist.
3054static void
3055PushDefUseChildren(Instruction *I,
3056 SmallVectorImpl<Instruction *> &Worklist) {
3057 // Push the def-use children onto the Worklist stack.
3058 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3059 UI != UE; ++UI)
3060 Worklist.push_back(cast<Instruction>(UI));
3061}
3062
Dan Gohmana1af7572009-04-30 20:47:05 +00003063const ScalarEvolution::BackedgeTakenInfo &
3064ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003065 // Initially insert a CouldNotCompute for this loop. If the insertion
3066 // succeeds, procede to actually compute a backedge-taken count and
3067 // update the value. The temporary CouldNotCompute value tells SCEV
3068 // code elsewhere that it shouldn't attempt to request a new
3069 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003070 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003071 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3072 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003073 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003074 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003075 assert(ItCount.Exact->isLoopInvariant(L) &&
3076 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003077 "Computed trip count isn't loop invariant for loop!");
3078 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003079
Dan Gohman01ecca22009-04-27 20:16:15 +00003080 // Update the value in the map.
3081 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003082 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003083 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003084 // Update the value in the map.
3085 Pair.first->second = ItCount;
3086 if (isa<PHINode>(L->getHeader()->begin()))
3087 // Only count loops that have phi nodes as not being computable.
3088 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003089 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003090
3091 // Now that we know more about the trip count for this loop, forget any
3092 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003093 // conservative estimates made without the benefit of trip count
3094 // information. This is similar to the code in
3095 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3096 // nodes specially.
3097 if (ItCount.hasAnyInfo()) {
3098 SmallVector<Instruction *, 16> Worklist;
3099 PushLoopPHIs(L, Worklist);
3100
3101 SmallPtrSet<Instruction *, 8> Visited;
3102 while (!Worklist.empty()) {
3103 Instruction *I = Worklist.pop_back_val();
3104 if (!Visited.insert(I)) continue;
3105
3106 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3107 Scalars.find(static_cast<Value *>(I));
3108 if (It != Scalars.end()) {
3109 // SCEVUnknown for a PHI either means that it has an unrecognized
3110 // structure, or it's a PHI that's in the progress of being computed
3111 // by createNodeForPHI. In the former case, additional loop trip count
3112 // information isn't going to change anything. In the later case,
3113 // createNodeForPHI will perform the necessary updates on its own when
3114 // it gets to that point.
3115 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3116 Scalars.erase(It);
3117 ValuesAtScopes.erase(I);
3118 if (PHINode *PN = dyn_cast<PHINode>(I))
3119 ConstantEvolutionLoopExitValue.erase(PN);
3120 }
3121
3122 PushDefUseChildren(I, Worklist);
3123 }
3124 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003125 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003126 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003127}
3128
Dan Gohman46bdfb02009-02-24 18:55:53 +00003129/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003130/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003131/// ScalarEvolution's ability to compute a trip count, or if the loop
3132/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003133void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003134 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003135
Dan Gohman35738ac2009-05-04 22:30:44 +00003136 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003137 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003138
Dan Gohman59ae6b92009-07-08 19:23:34 +00003139 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003140 while (!Worklist.empty()) {
3141 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003142 if (!Visited.insert(I)) continue;
3143
3144 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3145 Scalars.find(static_cast<Value *>(I));
3146 if (It != Scalars.end()) {
3147 Scalars.erase(It);
3148 ValuesAtScopes.erase(I);
3149 if (PHINode *PN = dyn_cast<PHINode>(I))
3150 ConstantEvolutionLoopExitValue.erase(PN);
3151 }
3152
3153 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003154 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003155}
3156
Dan Gohman46bdfb02009-02-24 18:55:53 +00003157/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3158/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003159ScalarEvolution::BackedgeTakenInfo
3160ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003161 SmallVector<BasicBlock*, 8> ExitingBlocks;
3162 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003163
Dan Gohmana334aa72009-06-22 00:31:57 +00003164 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003165 const SCEV *BECount = getCouldNotCompute();
3166 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003167 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003168 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3169 BackedgeTakenInfo NewBTI =
3170 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003171
Dan Gohman1c343752009-06-27 21:21:31 +00003172 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003173 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003174 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003175 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003176 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003177 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003178 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003179 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003180 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003181 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003182 }
Dan Gohman1c343752009-06-27 21:21:31 +00003183 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003184 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003185 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003186 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003187 }
3188
3189 return BackedgeTakenInfo(BECount, MaxBECount);
3190}
3191
3192/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3193/// of the specified loop will execute if it exits via the specified block.
3194ScalarEvolution::BackedgeTakenInfo
3195ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3196 BasicBlock *ExitingBlock) {
3197
3198 // Okay, we've chosen an exiting block. See what condition causes us to
3199 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003200 //
3201 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003202 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003203 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003204 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003205
Chris Lattner8b0e3602007-01-07 02:24:26 +00003206 // At this point, we know we have a conditional branch that determines whether
3207 // the loop is exited. However, we don't know if the branch is executed each
3208 // time through the loop. If not, then the execution count of the branch will
3209 // not be equal to the trip count of the loop.
3210 //
3211 // Currently we check for this by checking to see if the Exit branch goes to
3212 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003213 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003214 // loop header. This is common for un-rotated loops.
3215 //
3216 // If both of those tests fail, walk up the unique predecessor chain to the
3217 // header, stopping if there is an edge that doesn't exit the loop. If the
3218 // header is reached, the execution count of the branch will be equal to the
3219 // trip count of the loop.
3220 //
3221 // More extensive analysis could be done to handle more cases here.
3222 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003223 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003224 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003225 ExitBr->getParent() != L->getHeader()) {
3226 // The simple checks failed, try climbing the unique predecessor chain
3227 // up to the header.
3228 bool Ok = false;
3229 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3230 BasicBlock *Pred = BB->getUniquePredecessor();
3231 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003232 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003233 TerminatorInst *PredTerm = Pred->getTerminator();
3234 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3235 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3236 if (PredSucc == BB)
3237 continue;
3238 // If the predecessor has a successor that isn't BB and isn't
3239 // outside the loop, assume the worst.
3240 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003241 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003242 }
3243 if (Pred == L->getHeader()) {
3244 Ok = true;
3245 break;
3246 }
3247 BB = Pred;
3248 }
3249 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003250 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003251 }
3252
3253 // Procede to the next level to examine the exit condition expression.
3254 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3255 ExitBr->getSuccessor(0),
3256 ExitBr->getSuccessor(1));
3257}
3258
3259/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3260/// backedge of the specified loop will execute if its exit condition
3261/// were a conditional branch of ExitCond, TBB, and FBB.
3262ScalarEvolution::BackedgeTakenInfo
3263ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3264 Value *ExitCond,
3265 BasicBlock *TBB,
3266 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003267 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3269 if (BO->getOpcode() == Instruction::And) {
3270 // Recurse on the operands of the and.
3271 BackedgeTakenInfo BTI0 =
3272 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3273 BackedgeTakenInfo BTI1 =
3274 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003275 const SCEV *BECount = getCouldNotCompute();
3276 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003277 if (L->contains(TBB)) {
3278 // Both conditions must be true for the loop to continue executing.
3279 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003280 if (BTI0.Exact == getCouldNotCompute() ||
3281 BTI1.Exact == getCouldNotCompute())
3282 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003283 else
3284 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003285 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003286 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003287 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003288 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003289 else
3290 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003291 } else {
3292 // Both conditions must be true for the loop to exit.
3293 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003294 if (BTI0.Exact != getCouldNotCompute() &&
3295 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003296 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003297 if (BTI0.Max != getCouldNotCompute() &&
3298 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003299 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3300 }
3301
3302 return BackedgeTakenInfo(BECount, MaxBECount);
3303 }
3304 if (BO->getOpcode() == Instruction::Or) {
3305 // Recurse on the operands of the or.
3306 BackedgeTakenInfo BTI0 =
3307 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3308 BackedgeTakenInfo BTI1 =
3309 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003310 const SCEV *BECount = getCouldNotCompute();
3311 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003312 if (L->contains(FBB)) {
3313 // Both conditions must be false for the loop to continue executing.
3314 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003315 if (BTI0.Exact == getCouldNotCompute() ||
3316 BTI1.Exact == getCouldNotCompute())
3317 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003318 else
3319 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003320 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003321 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003322 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003323 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003324 else
3325 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003326 } else {
3327 // Both conditions must be false for the loop to exit.
3328 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003329 if (BTI0.Exact != getCouldNotCompute() &&
3330 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003331 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003332 if (BTI0.Max != getCouldNotCompute() &&
3333 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003334 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3335 }
3336
3337 return BackedgeTakenInfo(BECount, MaxBECount);
3338 }
3339 }
3340
3341 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3342 // Procede to the next level to examine the icmp.
3343 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3344 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003345
Eli Friedman361e54d2009-05-09 12:32:42 +00003346 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003347 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3348}
3349
3350/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3351/// backedge of the specified loop will execute if its exit condition
3352/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3353ScalarEvolution::BackedgeTakenInfo
3354ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3355 ICmpInst *ExitCond,
3356 BasicBlock *TBB,
3357 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003358
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359 // If the condition was exit on true, convert the condition to exit on false
3360 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003361 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003362 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003363 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003365
3366 // Handle common loops like: for (X = "string"; *X; ++X)
3367 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3368 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003369 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003370 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003371 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3372 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3373 return BackedgeTakenInfo(ItCnt,
3374 isa<SCEVConstant>(ItCnt) ? ItCnt :
3375 getConstant(APInt::getMaxValue(BitWidth)-1));
3376 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003377 }
3378
Dan Gohman0bba49c2009-07-07 17:06:11 +00003379 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3380 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003381
3382 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003383 LHS = getSCEVAtScope(LHS, L);
3384 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003385
Dan Gohman64a845e2009-06-24 04:48:43 +00003386 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003388 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3389 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003390 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003392 }
3393
Chris Lattner53e677a2004-04-02 20:23:17 +00003394 // If we have a comparison of a chrec against a constant, try to use value
3395 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003396 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3397 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003398 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003399 // Form the constant range.
3400 ConstantRange CompRange(
3401 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003402
Dan Gohman0bba49c2009-07-07 17:06:11 +00003403 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003404 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003405 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003406
Chris Lattner53e677a2004-04-02 20:23:17 +00003407 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003409 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003410 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003412 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003413 }
3414 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003415 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003416 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003418 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 }
3420 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003421 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3422 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003423 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003424 }
3425 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003426 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3427 getNotSCEV(RHS), L, true);
3428 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003429 break;
3430 }
3431 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003432 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3433 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003434 break;
3435 }
3436 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003437 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3438 getNotSCEV(RHS), L, false);
3439 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003440 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003442 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003443#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003444 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003445 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003446 errs() << "[unsigned] ";
3447 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003448 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003450#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003451 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003452 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003453 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003454 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003455}
3456
Chris Lattner673e02b2004-10-12 01:49:27 +00003457static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003458EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3459 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003460 const SCEV *InVal = SE.getConstant(C);
3461 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003462 assert(isa<SCEVConstant>(Val) &&
3463 "Evaluation of SCEV at constant didn't fold correctly?");
3464 return cast<SCEVConstant>(Val)->getValue();
3465}
3466
3467/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3468/// and a GEP expression (missing the pointer index) indexing into it, return
3469/// the addressed element of the initializer or null if the index expression is
3470/// invalid.
3471static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003472GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003473 const std::vector<ConstantInt*> &Indices) {
3474 Constant *Init = GV->getInitializer();
3475 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003476 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003477 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3478 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3479 Init = cast<Constant>(CS->getOperand(Idx));
3480 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3481 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3482 Init = cast<Constant>(CA->getOperand(Idx));
3483 } else if (isa<ConstantAggregateZero>(Init)) {
3484 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3485 assert(Idx < STy->getNumElements() && "Bad struct index!");
3486 Init = Constant::getNullValue(STy->getElementType(Idx));
3487 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3488 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3489 Init = Constant::getNullValue(ATy->getElementType());
3490 } else {
3491 assert(0 && "Unknown constant aggregate type!");
3492 }
3493 return 0;
3494 } else {
3495 return 0; // Unknown initializer type
3496 }
3497 }
3498 return Init;
3499}
3500
Dan Gohman46bdfb02009-02-24 18:55:53 +00003501/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3502/// 'icmp op load X, cst', try to see if we can compute the backedge
3503/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003504const SCEV *
3505ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3506 LoadInst *LI,
3507 Constant *RHS,
3508 const Loop *L,
3509 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003510 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003511
3512 // Check to see if the loaded pointer is a getelementptr of a global.
3513 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003514 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003515
3516 // Make sure that it is really a constant global we are gepping, with an
3517 // initializer, and make sure the first IDX is really 0.
3518 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3519 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3520 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3521 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003522 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003523
3524 // Okay, we allow one non-constant index into the GEP instruction.
3525 Value *VarIdx = 0;
3526 std::vector<ConstantInt*> Indexes;
3527 unsigned VarIdxNum = 0;
3528 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3529 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3530 Indexes.push_back(CI);
3531 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003532 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003533 VarIdx = GEP->getOperand(i);
3534 VarIdxNum = i-2;
3535 Indexes.push_back(0);
3536 }
3537
3538 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3539 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003540 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003541 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003542
3543 // We can only recognize very limited forms of loop index expressions, in
3544 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003545 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003546 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3547 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3548 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003549 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003550
3551 unsigned MaxSteps = MaxBruteForceIterations;
3552 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003553 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003554 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003555 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003556
3557 // Form the GEP offset.
3558 Indexes[VarIdxNum] = Val;
3559
3560 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3561 if (Result == 0) break; // Cannot compute!
3562
3563 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003564 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003565 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003566 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003567#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003568 errs() << "\n***\n*** Computed loop count " << *ItCst
3569 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3570 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003571#endif
3572 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003573 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003574 }
3575 }
Dan Gohman1c343752009-06-27 21:21:31 +00003576 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003577}
3578
3579
Chris Lattner3221ad02004-04-17 22:58:41 +00003580/// CanConstantFold - Return true if we can constant fold an instruction of the
3581/// specified type, assuming that all operands were constants.
3582static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003583 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003584 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3585 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003586
Chris Lattner3221ad02004-04-17 22:58:41 +00003587 if (const CallInst *CI = dyn_cast<CallInst>(I))
3588 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003589 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003590 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003591}
3592
Chris Lattner3221ad02004-04-17 22:58:41 +00003593/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3594/// in the loop that V is derived from. We allow arbitrary operations along the
3595/// way, but the operands of an operation must either be constants or a value
3596/// derived from a constant PHI. If this expression does not fit with these
3597/// constraints, return null.
3598static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3599 // If this is not an instruction, or if this is an instruction outside of the
3600 // loop, it can't be derived from a loop PHI.
3601 Instruction *I = dyn_cast<Instruction>(V);
3602 if (I == 0 || !L->contains(I->getParent())) return 0;
3603
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003604 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003605 if (L->getHeader() == I->getParent())
3606 return PN;
3607 else
3608 // We don't currently keep track of the control flow needed to evaluate
3609 // PHIs, so we cannot handle PHIs inside of loops.
3610 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003611 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003612
3613 // If we won't be able to constant fold this expression even if the operands
3614 // are constants, return early.
3615 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003616
Chris Lattner3221ad02004-04-17 22:58:41 +00003617 // Otherwise, we can evaluate this instruction if all of its operands are
3618 // constant or derived from a PHI node themselves.
3619 PHINode *PHI = 0;
3620 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3621 if (!(isa<Constant>(I->getOperand(Op)) ||
3622 isa<GlobalValue>(I->getOperand(Op)))) {
3623 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3624 if (P == 0) return 0; // Not evolving from PHI
3625 if (PHI == 0)
3626 PHI = P;
3627 else if (PHI != P)
3628 return 0; // Evolving from multiple different PHIs.
3629 }
3630
3631 // This is a expression evolving from a constant PHI!
3632 return PHI;
3633}
3634
3635/// EvaluateExpression - Given an expression that passes the
3636/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3637/// in the loop has the value PHIVal. If we can't fold this expression for some
3638/// reason, return null.
3639static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3640 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003641 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003642 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003643 Instruction *I = cast<Instruction>(V);
Owen Anderson07cf79e2009-07-06 23:00:19 +00003644 LLVMContext *Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003645
3646 std::vector<Constant*> Operands;
3647 Operands.resize(I->getNumOperands());
3648
3649 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3650 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3651 if (Operands[i] == 0) return 0;
3652 }
3653
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003654 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3655 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003656 &Operands[0], Operands.size(),
3657 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003658 else
3659 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003660 &Operands[0], Operands.size(),
3661 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003662}
3663
3664/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3665/// in the header of its containing loop, we know the loop executes a
3666/// constant number of times, and the PHI node is just a recurrence
3667/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003668Constant *
3669ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3670 const APInt& BEs,
3671 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003672 std::map<PHINode*, Constant*>::iterator I =
3673 ConstantEvolutionLoopExitValue.find(PN);
3674 if (I != ConstantEvolutionLoopExitValue.end())
3675 return I->second;
3676
Dan Gohman46bdfb02009-02-24 18:55:53 +00003677 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003678 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3679
3680 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3681
3682 // Since the loop is canonicalized, the PHI node must have two entries. One
3683 // entry must be a constant (coming in from outside of the loop), and the
3684 // second must be derived from the same PHI.
3685 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3686 Constant *StartCST =
3687 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3688 if (StartCST == 0)
3689 return RetVal = 0; // Must be a constant.
3690
3691 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3692 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3693 if (PN2 != PN)
3694 return RetVal = 0; // Not derived from same PHI.
3695
3696 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003697 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003698 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003699
Dan Gohman46bdfb02009-02-24 18:55:53 +00003700 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003701 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003702 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3703 if (IterationNum == NumIterations)
3704 return RetVal = PHIVal; // Got exit value!
3705
3706 // Compute the value of the PHI node for the next iteration.
3707 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3708 if (NextPHI == PHIVal)
3709 return RetVal = NextPHI; // Stopped evolving!
3710 if (NextPHI == 0)
3711 return 0; // Couldn't evaluate!
3712 PHIVal = NextPHI;
3713 }
3714}
3715
Dan Gohman46bdfb02009-02-24 18:55:53 +00003716/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003717/// constant number of times (the condition evolves only from constants),
3718/// try to evaluate a few iterations of the loop until we get the exit
3719/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003720/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003721const SCEV *
3722ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3723 Value *Cond,
3724 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003725 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003726 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003727
3728 // Since the loop is canonicalized, the PHI node must have two entries. One
3729 // entry must be a constant (coming in from outside of the loop), and the
3730 // second must be derived from the same PHI.
3731 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3732 Constant *StartCST =
3733 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003734 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003735
3736 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3737 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003738 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003739
3740 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3741 // the loop symbolically to determine when the condition gets a value of
3742 // "ExitWhen".
3743 unsigned IterationNum = 0;
3744 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3745 for (Constant *PHIVal = StartCST;
3746 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003747 ConstantInt *CondVal =
3748 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003749
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003750 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003751 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003752
Reid Spencere8019bb2007-03-01 07:25:48 +00003753 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003754 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003755 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003756 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003757
Chris Lattner3221ad02004-04-17 22:58:41 +00003758 // Compute the value of the PHI node for the next iteration.
3759 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3760 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003761 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003762 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003763 }
3764
3765 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003766 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003767}
3768
Dan Gohman66a7e852009-05-08 20:38:54 +00003769/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3770/// at the specified scope in the program. The L value specifies a loop
3771/// nest to evaluate the expression at, where null is the top-level or a
3772/// specified loop is immediately inside of the loop.
3773///
3774/// This method can be used to compute the exit value for a variable defined
3775/// in a loop by querying what the value will hold in the parent loop.
3776///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003777/// In the case that a relevant loop exit value cannot be computed, the
3778/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003779const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003780 // FIXME: this should be turned into a virtual method on SCEV!
3781
Chris Lattner3221ad02004-04-17 22:58:41 +00003782 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003783
Nick Lewycky3e630762008-02-20 06:48:22 +00003784 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003785 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003786 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003787 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003788 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003789 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3790 if (PHINode *PN = dyn_cast<PHINode>(I))
3791 if (PN->getParent() == LI->getHeader()) {
3792 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003793 // to see if the loop that contains it has a known backedge-taken
3794 // count. If so, we may be able to force computation of the exit
3795 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003796 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003797 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003798 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003799 // Okay, we know how many times the containing loop executes. If
3800 // this is a constant evolving PHI node, get the final value at
3801 // the specified iteration number.
3802 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003803 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003804 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003805 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003806 }
3807 }
3808
Reid Spencer09906f32006-12-04 21:33:23 +00003809 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003810 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003811 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003812 // result. This is particularly useful for computing loop exit values.
3813 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003814 // Check to see if we've folded this instruction at this loop before.
3815 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3816 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3817 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3818 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003819 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003820
Chris Lattner3221ad02004-04-17 22:58:41 +00003821 std::vector<Constant*> Operands;
3822 Operands.reserve(I->getNumOperands());
3823 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3824 Value *Op = I->getOperand(i);
3825 if (Constant *C = dyn_cast<Constant>(Op)) {
3826 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003827 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003828 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003829 // non-integer and non-pointer, don't even try to analyze them
3830 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003831 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003832 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003833
Dan Gohman1b342582009-07-10 16:42:52 +00003834 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00003835 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003836 Constant *C = SC->getValue();
3837 if (C->getType() != Op->getType())
3838 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3839 Op->getType(),
3840 false),
3841 C, Op->getType());
3842 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003843 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003844 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3845 if (C->getType() != Op->getType())
3846 C =
3847 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3848 Op->getType(),
3849 false),
3850 C, Op->getType());
3851 Operands.push_back(C);
3852 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003853 return V;
3854 } else {
3855 return V;
3856 }
3857 }
3858 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003859
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003860 Constant *C;
3861 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3862 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003863 &Operands[0], Operands.size(),
3864 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003865 else
3866 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003867 &Operands[0], Operands.size(), Context);
Dan Gohman6bce6432009-05-08 20:47:27 +00003868 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003869 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003870 }
3871 }
3872
3873 // This is some other type of SCEVUnknown, just return it.
3874 return V;
3875 }
3876
Dan Gohman622ed672009-05-04 22:02:23 +00003877 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003878 // Avoid performing the look-up in the common case where the specified
3879 // expression has no loop-variant portions.
3880 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003881 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003882 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003883 // Okay, at least one of these operands is loop variant but might be
3884 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00003885 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3886 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003887 NewOps.push_back(OpAtScope);
3888
3889 for (++i; i != e; ++i) {
3890 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003891 NewOps.push_back(OpAtScope);
3892 }
3893 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003894 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003895 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003896 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003897 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003898 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003899 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003900 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003901 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003902 }
3903 }
3904 // If we got here, all operands are loop invariant.
3905 return Comm;
3906 }
3907
Dan Gohman622ed672009-05-04 22:02:23 +00003908 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003909 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3910 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003911 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3912 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003913 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003914 }
3915
3916 // If this is a loop recurrence for a loop that does not contain L, then we
3917 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003918 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003919 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3920 // To evaluate this recurrence, we need to know how many times the AddRec
3921 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003922 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00003923 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003924
Eli Friedmanb42a6262008-08-04 23:49:06 +00003925 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003926 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003927 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003928 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003929 }
3930
Dan Gohman622ed672009-05-04 22:02:23 +00003931 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003932 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003933 if (Op == Cast->getOperand())
3934 return Cast; // must be loop invariant
3935 return getZeroExtendExpr(Op, Cast->getType());
3936 }
3937
Dan Gohman622ed672009-05-04 22:02:23 +00003938 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003939 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003940 if (Op == Cast->getOperand())
3941 return Cast; // must be loop invariant
3942 return getSignExtendExpr(Op, Cast->getType());
3943 }
3944
Dan Gohman622ed672009-05-04 22:02:23 +00003945 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003946 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003947 if (Op == Cast->getOperand())
3948 return Cast; // must be loop invariant
3949 return getTruncateExpr(Op, Cast->getType());
3950 }
3951
3952 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003953 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003954}
3955
Dan Gohman66a7e852009-05-08 20:38:54 +00003956/// getSCEVAtScope - This is a convenience function which does
3957/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00003958const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003959 return getSCEVAtScope(getSCEV(V), L);
3960}
3961
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003962/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3963/// following equation:
3964///
3965/// A * X = B (mod N)
3966///
3967/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3968/// A and B isn't important.
3969///
3970/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003971static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003972 ScalarEvolution &SE) {
3973 uint32_t BW = A.getBitWidth();
3974 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3975 assert(A != 0 && "A must be non-zero.");
3976
3977 // 1. D = gcd(A, N)
3978 //
3979 // The gcd of A and N may have only one prime factor: 2. The number of
3980 // trailing zeros in A is its multiplicity
3981 uint32_t Mult2 = A.countTrailingZeros();
3982 // D = 2^Mult2
3983
3984 // 2. Check if B is divisible by D.
3985 //
3986 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3987 // is not less than multiplicity of this prime factor for D.
3988 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003989 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003990
3991 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3992 // modulo (N / D).
3993 //
3994 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3995 // bit width during computations.
3996 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3997 APInt Mod(BW + 1, 0);
3998 Mod.set(BW - Mult2); // Mod = N / D
3999 APInt I = AD.multiplicativeInverse(Mod);
4000
4001 // 4. Compute the minimum unsigned root of the equation:
4002 // I * (B / D) mod (N / D)
4003 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4004
4005 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4006 // bits.
4007 return SE.getConstant(Result.trunc(BW));
4008}
Chris Lattner53e677a2004-04-02 20:23:17 +00004009
4010/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4011/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4012/// might be the same) or two SCEVCouldNotCompute objects.
4013///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004014static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004015SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004016 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004017 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4018 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4019 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004020
Chris Lattner53e677a2004-04-02 20:23:17 +00004021 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004022 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004023 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004024 return std::make_pair(CNC, CNC);
4025 }
4026
Reid Spencere8019bb2007-03-01 07:25:48 +00004027 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004028 const APInt &L = LC->getValue()->getValue();
4029 const APInt &M = MC->getValue()->getValue();
4030 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004031 APInt Two(BitWidth, 2);
4032 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004033
Dan Gohman64a845e2009-06-24 04:48:43 +00004034 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004035 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004036 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004037 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4038 // The B coefficient is M-N/2
4039 APInt B(M);
4040 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004041
Reid Spencere8019bb2007-03-01 07:25:48 +00004042 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004043 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004044
Reid Spencere8019bb2007-03-01 07:25:48 +00004045 // Compute the B^2-4ac term.
4046 APInt SqrtTerm(B);
4047 SqrtTerm *= B;
4048 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004049
Reid Spencere8019bb2007-03-01 07:25:48 +00004050 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4051 // integer value or else APInt::sqrt() will assert.
4052 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004053
Dan Gohman64a845e2009-06-24 04:48:43 +00004054 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004055 // The divisions must be performed as signed divisions.
4056 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004057 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004058 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004059 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004060 return std::make_pair(CNC, CNC);
4061 }
4062
Owen Anderson76f600b2009-07-06 22:37:39 +00004063 LLVMContext *Context = SE.getContext();
4064
4065 ConstantInt *Solution1 =
4066 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4067 ConstantInt *Solution2 =
4068 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004069
Dan Gohman64a845e2009-06-24 04:48:43 +00004070 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004071 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004072 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004073}
4074
4075/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004076/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004077const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004078 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004079 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004080 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004081 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004082 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004083 }
4084
Dan Gohman35738ac2009-05-04 22:30:44 +00004085 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004086 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004087 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004088
4089 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004090 // If this is an affine expression, the execution count of this branch is
4091 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004092 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004093 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004094 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004095 // equivalent to:
4096 //
4097 // Step*N = -Start (mod 2^BW)
4098 //
4099 // where BW is the common bit width of Start and Step.
4100
Chris Lattner53e677a2004-04-02 20:23:17 +00004101 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004102 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4103 L->getParentLoop());
4104 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4105 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004106
Dan Gohman622ed672009-05-04 22:02:23 +00004107 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004108 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004109
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004110 // First, handle unitary steps.
4111 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004112 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004113 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4114 return Start; // N = Start (as unsigned)
4115
4116 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004117 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004118 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004119 -StartC->getValue()->getValue(),
4120 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004121 }
Chris Lattner42a75512007-01-15 02:27:26 +00004122 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004123 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4124 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004125 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004126 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004127 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4128 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004129 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004130#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004131 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4132 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004133#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004134 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004135 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004136 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004137 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004138 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004139 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004140
Chris Lattner53e677a2004-04-02 20:23:17 +00004141 // We can only use this value if the chrec ends up with an exact zero
4142 // value at this index. When solving for "X*X != 5", for example, we
4143 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004144 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004145 if (Val->isZero())
4146 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004147 }
4148 }
4149 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004150
Dan Gohman1c343752009-06-27 21:21:31 +00004151 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004152}
4153
4154/// HowFarToNonZero - Return the number of times a backedge checking the
4155/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004156/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004157const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004158 // Loops that look like: while (X == 0) are very strange indeed. We don't
4159 // handle them yet except for the trivial case. This could be expanded in the
4160 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004161
Chris Lattner53e677a2004-04-02 20:23:17 +00004162 // If the value is a constant, check to see if it is known to be non-zero
4163 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004164 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004165 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004166 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004167 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004168 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004169
Chris Lattner53e677a2004-04-02 20:23:17 +00004170 // We could implement others, but I really doubt anyone writes loops like
4171 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004172 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004173}
4174
Dan Gohman859b4822009-05-18 15:36:09 +00004175/// getLoopPredecessor - If the given loop's header has exactly one unique
4176/// predecessor outside the loop, return it. Otherwise return null.
4177///
4178BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4179 BasicBlock *Header = L->getHeader();
4180 BasicBlock *Pred = 0;
4181 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4182 PI != E; ++PI)
4183 if (!L->contains(*PI)) {
4184 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4185 Pred = *PI;
4186 }
4187 return Pred;
4188}
4189
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004190/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4191/// (which may not be an immediate predecessor) which has exactly one
4192/// successor from which BB is reachable, or null if no such block is
4193/// found.
4194///
4195BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004196ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004197 // If the block has a unique predecessor, then there is no path from the
4198 // predecessor to the block that does not go through the direct edge
4199 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004200 if (BasicBlock *Pred = BB->getSinglePredecessor())
4201 return Pred;
4202
4203 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004204 // If the header has a unique predecessor outside the loop, it must be
4205 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004206 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004207 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004208
4209 return 0;
4210}
4211
Dan Gohman763bad12009-06-20 00:35:32 +00004212/// HasSameValue - SCEV structural equivalence is usually sufficient for
4213/// testing whether two expressions are equal, however for the purposes of
4214/// looking for a condition guarding a loop, it can be useful to be a little
4215/// more general, since a front-end may have replicated the controlling
4216/// expression.
4217///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004218static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004219 // Quick check to see if they are the same SCEV.
4220 if (A == B) return true;
4221
4222 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4223 // two different instructions with the same value. Check for this case.
4224 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4225 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4226 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4227 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4228 if (AI->isIdenticalTo(BI))
4229 return true;
4230
4231 // Otherwise assume they may have a different value.
4232 return false;
4233}
4234
Dan Gohman1b342582009-07-10 16:42:52 +00004235bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4236 return getSignedRange(S).getSignedMax().isNegative();
4237}
4238
4239bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4240 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4241}
4242
4243bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4244 return !getSignedRange(S).getSignedMin().isNegative();
4245}
4246
4247bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4248 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4249}
4250
4251bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4252 return isKnownNegative(S) || isKnownPositive(S);
4253}
4254
4255bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4256 const SCEV *LHS, const SCEV *RHS) {
4257
4258 if (HasSameValue(LHS, RHS))
4259 return ICmpInst::isTrueWhenEqual(Pred);
4260
4261 switch (Pred) {
4262 default:
4263 assert(0 && "Unexpected ICmpInst::Predicate value!");
4264 break;
4265 case ICmpInst::ICMP_SGT:
4266 Pred = ICmpInst::ICMP_SLT;
4267 std::swap(LHS, RHS);
4268 case ICmpInst::ICMP_SLT: {
4269 ConstantRange LHSRange = getSignedRange(LHS);
4270 ConstantRange RHSRange = getSignedRange(RHS);
4271 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4272 return true;
4273 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4274 return false;
4275
4276 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4277 ConstantRange DiffRange = getUnsignedRange(Diff);
4278 if (isKnownNegative(Diff)) {
4279 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4280 return true;
4281 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4282 return false;
4283 } else if (isKnownPositive(Diff)) {
4284 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4285 return true;
4286 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4287 return false;
4288 }
4289 break;
4290 }
4291 case ICmpInst::ICMP_SGE:
4292 Pred = ICmpInst::ICMP_SLE;
4293 std::swap(LHS, RHS);
4294 case ICmpInst::ICMP_SLE: {
4295 ConstantRange LHSRange = getSignedRange(LHS);
4296 ConstantRange RHSRange = getSignedRange(RHS);
4297 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4298 return true;
4299 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4300 return false;
4301
4302 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4303 ConstantRange DiffRange = getUnsignedRange(Diff);
4304 if (isKnownNonPositive(Diff)) {
4305 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4306 return true;
4307 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4308 return false;
4309 } else if (isKnownNonNegative(Diff)) {
4310 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4311 return true;
4312 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4313 return false;
4314 }
4315 break;
4316 }
4317 case ICmpInst::ICMP_UGT:
4318 Pred = ICmpInst::ICMP_ULT;
4319 std::swap(LHS, RHS);
4320 case ICmpInst::ICMP_ULT: {
4321 ConstantRange LHSRange = getUnsignedRange(LHS);
4322 ConstantRange RHSRange = getUnsignedRange(RHS);
4323 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4324 return true;
4325 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4326 return false;
4327
4328 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4329 ConstantRange DiffRange = getUnsignedRange(Diff);
4330 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4331 return true;
4332 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4333 return false;
4334 break;
4335 }
4336 case ICmpInst::ICMP_UGE:
4337 Pred = ICmpInst::ICMP_ULE;
4338 std::swap(LHS, RHS);
4339 case ICmpInst::ICMP_ULE: {
4340 ConstantRange LHSRange = getUnsignedRange(LHS);
4341 ConstantRange RHSRange = getUnsignedRange(RHS);
4342 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4343 return true;
4344 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4345 return false;
4346
4347 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4348 ConstantRange DiffRange = getUnsignedRange(Diff);
4349 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4350 return true;
4351 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4352 return false;
4353 break;
4354 }
4355 case ICmpInst::ICMP_NE: {
4356 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4357 return true;
4358 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4359 return true;
4360
4361 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4362 if (isKnownNonZero(Diff))
4363 return true;
4364 break;
4365 }
4366 case ICmpInst::ICMP_EQ:
4367 break;
4368 }
4369 return false;
4370}
4371
4372/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4373/// protected by a conditional between LHS and RHS. This is used to
4374/// to eliminate casts.
4375bool
4376ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4377 ICmpInst::Predicate Pred,
4378 const SCEV *LHS, const SCEV *RHS) {
4379 // Interpret a null as meaning no loop, where there is obviously no guard
4380 // (interprocedural conditions notwithstanding).
4381 if (!L) return true;
4382
4383 BasicBlock *Latch = L->getLoopLatch();
4384 if (!Latch)
4385 return false;
4386
4387 BranchInst *LoopContinuePredicate =
4388 dyn_cast<BranchInst>(Latch->getTerminator());
4389 if (!LoopContinuePredicate ||
4390 LoopContinuePredicate->isUnconditional())
4391 return false;
4392
4393 return
4394 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4395 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4396}
4397
4398/// isLoopGuardedByCond - Test whether entry to the loop is protected
4399/// by a conditional between LHS and RHS. This is used to help avoid max
4400/// expressions in loop trip counts, and to eliminate casts.
4401bool
4402ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4403 ICmpInst::Predicate Pred,
4404 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004405 // Interpret a null as meaning no loop, where there is obviously no guard
4406 // (interprocedural conditions notwithstanding).
4407 if (!L) return false;
4408
Dan Gohman859b4822009-05-18 15:36:09 +00004409 BasicBlock *Predecessor = getLoopPredecessor(L);
4410 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004411
Dan Gohman859b4822009-05-18 15:36:09 +00004412 // Starting at the loop predecessor, climb up the predecessor chain, as long
4413 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004414 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004415 for (; Predecessor;
4416 PredecessorDest = Predecessor,
4417 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004418
4419 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004420 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004421 if (!LoopEntryPredicate ||
4422 LoopEntryPredicate->isUnconditional())
4423 continue;
4424
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004425 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4426 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004427 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004428 }
4429
Dan Gohman38372182008-08-12 20:17:31 +00004430 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004431}
4432
Dan Gohman1b342582009-07-10 16:42:52 +00004433/// isNecessaryCond - Test whether the condition described by Pred, LHS,
4434/// and RHS is a necessary condition for the given Cond value to evaluate
4435/// to true.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004436bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4437 ICmpInst::Predicate Pred,
4438 const SCEV *LHS, const SCEV *RHS,
4439 bool Inverse) {
4440 // Recursivly handle And and Or conditions.
4441 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4442 if (BO->getOpcode() == Instruction::And) {
4443 if (!Inverse)
4444 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4445 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4446 } else if (BO->getOpcode() == Instruction::Or) {
4447 if (Inverse)
4448 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4449 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4450 }
4451 }
4452
4453 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4454 if (!ICI) return false;
4455
4456 // Now that we found a conditional branch that dominates the loop, check to
4457 // see if it is the comparison we are looking for.
4458 Value *PreCondLHS = ICI->getOperand(0);
4459 Value *PreCondRHS = ICI->getOperand(1);
Dan Gohman1b342582009-07-10 16:42:52 +00004460 ICmpInst::Predicate FoundPred;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004461 if (Inverse)
Dan Gohman1b342582009-07-10 16:42:52 +00004462 FoundPred = ICI->getInversePredicate();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004463 else
Dan Gohman1b342582009-07-10 16:42:52 +00004464 FoundPred = ICI->getPredicate();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004465
Dan Gohman1b342582009-07-10 16:42:52 +00004466 if (FoundPred == Pred)
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004467 ; // An exact match.
Dan Gohman1b342582009-07-10 16:42:52 +00004468 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4469 // The actual condition is beyond sufficient.
4470 FoundPred = ICmpInst::ICMP_NE;
4471 // NE is symmetric but the original comparison may not be. Swap
4472 // the operands if necessary so that they match below.
4473 if (isa<SCEVConstant>(LHS))
4474 std::swap(PreCondLHS, PreCondRHS);
4475 } else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004476 // Check a few special cases.
Dan Gohman1b342582009-07-10 16:42:52 +00004477 switch (FoundPred) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004478 case ICmpInst::ICMP_UGT:
4479 if (Pred == ICmpInst::ICMP_ULT) {
4480 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman1b342582009-07-10 16:42:52 +00004481 FoundPred = ICmpInst::ICMP_ULT;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004482 break;
4483 }
4484 return false;
4485 case ICmpInst::ICMP_SGT:
4486 if (Pred == ICmpInst::ICMP_SLT) {
4487 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman1b342582009-07-10 16:42:52 +00004488 FoundPred = ICmpInst::ICMP_SLT;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004489 break;
4490 }
4491 return false;
4492 case ICmpInst::ICMP_NE:
4493 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4494 // so check for this case by checking if the NE is comparing against
4495 // a minimum or maximum constant.
4496 if (!ICmpInst::isTrueWhenEqual(Pred))
Dan Gohman1b342582009-07-10 16:42:52 +00004497 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4498 const APInt &A = C->getValue()->getValue();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004499 switch (Pred) {
4500 case ICmpInst::ICMP_SLT:
4501 if (A.isMaxSignedValue()) break;
4502 return false;
4503 case ICmpInst::ICMP_SGT:
4504 if (A.isMinSignedValue()) break;
4505 return false;
4506 case ICmpInst::ICMP_ULT:
4507 if (A.isMaxValue()) break;
4508 return false;
4509 case ICmpInst::ICMP_UGT:
4510 if (A.isMinValue()) break;
4511 return false;
4512 default:
4513 return false;
4514 }
Dan Gohman1b342582009-07-10 16:42:52 +00004515 FoundPred = Pred;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004516 // NE is symmetric but the original comparison may not be. Swap
4517 // the operands if necessary so that they match below.
4518 if (isa<SCEVConstant>(LHS))
4519 std::swap(PreCondLHS, PreCondRHS);
4520 break;
4521 }
4522 return false;
4523 default:
4524 // We weren't able to reconcile the condition.
4525 return false;
4526 }
4527
Dan Gohman1b342582009-07-10 16:42:52 +00004528 assert(Pred == FoundPred && "Conditions were not reconciled!");
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004529
Dan Gohman1b342582009-07-10 16:42:52 +00004530 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4531 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4532
4533 // Balance the types.
4534 if (getTypeSizeInBits(LHS->getType()) >
4535 getTypeSizeInBits(FoundLHS->getType())) {
4536 if (CmpInst::isSigned(Pred)) {
4537 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4538 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4539 } else {
4540 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4541 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4542 }
4543 } else if (getTypeSizeInBits(LHS->getType()) <
4544 getTypeSizeInBits(FoundLHS->getType())) {
4545 // TODO: Cast LHS and RHS to FoundLHS' type. Currently this can
4546 // result in infinite recursion since the code to construct
4547 // cast expressions may want to know things about the loop
4548 // iteration in order to do simplifications.
4549 return false;
4550 }
4551
4552 return isNecessaryCondOperands(Pred, LHS, RHS,
4553 FoundLHS, FoundRHS) ||
4554 // ~x < ~y --> x > y
4555 isNecessaryCondOperands(Pred, LHS, RHS,
4556 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4557}
4558
4559/// isNecessaryCondOperands - Test whether the condition described by Pred,
4560/// LHS, and RHS is a necessary condition for the condition described by
4561/// Pred, FoundLHS, and FoundRHS to evaluate to true.
4562bool
4563ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4564 const SCEV *LHS, const SCEV *RHS,
4565 const SCEV *FoundLHS,
4566 const SCEV *FoundRHS) {
4567 switch (Pred) {
4568 default: break;
4569 case ICmpInst::ICMP_SLT:
4570 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4571 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4572 return true;
4573 break;
4574 case ICmpInst::ICMP_SGT:
4575 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4576 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4577 return true;
4578 break;
4579 case ICmpInst::ICMP_ULT:
4580 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4581 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4582 return true;
4583 break;
4584 case ICmpInst::ICMP_UGT:
4585 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4586 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4587 return true;
4588 break;
4589 }
4590
4591 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004592}
4593
Dan Gohman51f53b72009-06-21 23:46:38 +00004594/// getBECount - Subtract the end and start values and divide by the step,
4595/// rounding up, to get the number of times the backedge is executed. Return
4596/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004597const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4598 const SCEV *End,
4599 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004600 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004601 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4602 const SCEV *Diff = getMinusSCEV(End, Start);
4603 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004604
4605 // Add an adjustment to the difference between End and Start so that
4606 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004607 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004608
4609 // Check Add for unsigned overflow.
4610 // TODO: More sophisticated things could be done here.
Owen Anderson76f600b2009-07-06 22:37:39 +00004611 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004612 const SCEV *OperandExtendedAdd =
Dan Gohman51f53b72009-06-21 23:46:38 +00004613 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4614 getZeroExtendExpr(RoundUp, WideTy));
4615 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004616 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004617
4618 return getUDivExpr(Add, Step);
4619}
4620
Chris Lattnerdb25de42005-08-15 23:33:51 +00004621/// HowManyLessThans - Return the number of times a backedge containing the
4622/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004623/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004624ScalarEvolution::BackedgeTakenInfo
4625ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4626 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004627 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004628 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004629
Dan Gohman35738ac2009-05-04 22:30:44 +00004630 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004631 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004632 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004633
4634 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004635 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004636 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004637 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004638
4639 // TODO: handle non-constant strides.
4640 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4641 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004642 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004643 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004644 // With unit stride, the iteration never steps past the limit value.
4645 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4646 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4647 // Test whether a positive iteration iteration can step past the limit
4648 // value and past the maximum value for its type in a single step.
4649 if (isSigned) {
4650 APInt Max = APInt::getSignedMaxValue(BitWidth);
4651 if ((Max - CStep->getValue()->getValue())
4652 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004653 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004654 } else {
4655 APInt Max = APInt::getMaxValue(BitWidth);
4656 if ((Max - CStep->getValue()->getValue())
4657 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004658 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004659 }
4660 } else
4661 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004662 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004663 } else
4664 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004665 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004666
Dan Gohmana1af7572009-04-30 20:47:05 +00004667 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4668 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4669 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004670 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004671
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004672 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004673 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004674
Dan Gohmana1af7572009-04-30 20:47:05 +00004675 // Determine the minimum constant start value.
Dan Gohman1b342582009-07-10 16:42:52 +00004676 const SCEV *MinStart = getConstant(isSigned ?
4677 getSignedRange(Start).getSignedMin() :
4678 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004679
Dan Gohmana1af7572009-04-30 20:47:05 +00004680 // If we know that the condition is true in order to enter the loop,
4681 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004682 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4683 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004684 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004685 if (!isLoopGuardedByCond(L,
Dan Gohman1b342582009-07-10 16:42:52 +00004686 isSigned ? ICmpInst::ICMP_SLT :
4687 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004688 getMinusSCEV(Start, Step), RHS))
4689 End = isSigned ? getSMaxExpr(RHS, Start)
4690 : getUMaxExpr(RHS, Start);
4691
4692 // Determine the maximum constant end value.
Dan Gohman1b342582009-07-10 16:42:52 +00004693 const SCEV *MaxEnd = getConstant(isSigned ?
4694 getSignedRange(End).getSignedMax() :
4695 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004696
4697 // Finally, we subtract these two values and divide, rounding up, to get
4698 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004699 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004700
4701 // The maximum backedge count is similar, except using the minimum start
4702 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004703 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004704
4705 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004706 }
4707
Dan Gohman1c343752009-06-27 21:21:31 +00004708 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004709}
4710
Chris Lattner53e677a2004-04-02 20:23:17 +00004711/// getNumIterationsInRange - Return the number of iterations of this loop that
4712/// produce values in the specified constant range. Another way of looking at
4713/// this is that it returns the first iteration number where the value is not in
4714/// the condition, thus computing the exit count. If the iteration count can't
4715/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004716const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004717 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004718 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004719 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004720
4721 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004722 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004723 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004724 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004725 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004726 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004727 if (const SCEVAddRecExpr *ShiftedAddRec =
4728 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004729 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004730 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004731 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004732 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004733 }
4734
4735 // The only time we can solve this is when we have all constant indices.
4736 // Otherwise, we cannot determine the overflow conditions.
4737 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4738 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004739 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004740
4741
4742 // Okay at this point we know that all elements of the chrec are constants and
4743 // that the start element is zero.
4744
4745 // First check to see if the range contains zero. If not, the first
4746 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004747 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004748 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004749 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004750
Chris Lattner53e677a2004-04-02 20:23:17 +00004751 if (isAffine()) {
4752 // If this is an affine expression then we have this situation:
4753 // Solve {0,+,A} in Range === Ax in Range
4754
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004755 // We know that zero is in the range. If A is positive then we know that
4756 // the upper value of the range must be the first possible exit value.
4757 // If A is negative then the lower of the range is the last possible loop
4758 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004759 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004760 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4761 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004762
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004763 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004764 APInt ExitVal = (End + A).udiv(A);
Owen Anderson76f600b2009-07-06 22:37:39 +00004765 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004766
4767 // Evaluate at the exit value. If we really did fall out of the valid
4768 // range, then we computed our trip count, otherwise wrap around or other
4769 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004770 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004771 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004772 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004773
4774 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004775 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004776 EvaluateConstantChrecAtConstant(this,
Owen Anderson76f600b2009-07-06 22:37:39 +00004777 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004778 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004779 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004780 } else if (isQuadratic()) {
4781 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4782 // quadratic equation to solve it. To do this, we must frame our problem in
4783 // terms of figuring out when zero is crossed, instead of when
4784 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004785 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004786 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004787 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004788
4789 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004790 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004791 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004792 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4793 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004794 if (R1) {
4795 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004796 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004797 dyn_cast<ConstantInt>(
4798 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4799 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004800 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004801 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004802
Chris Lattner53e677a2004-04-02 20:23:17 +00004803 // Make sure the root is not off by one. The returned iteration should
4804 // not be in the range, but the previous one should be. When solving
4805 // for "X*X < 5", for example, we should not return a root of 2.
4806 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004807 R1->getValue(),
4808 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004809 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004810 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004811 ConstantInt *NextVal =
4812 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004813
Dan Gohman246b2562007-10-22 18:31:58 +00004814 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004815 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004816 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004817 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004818 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004819
Chris Lattner53e677a2004-04-02 20:23:17 +00004820 // If R1 was not in the range, then it is a good return value. Make
4821 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00004822 ConstantInt *NextVal =
4823 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004824 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004825 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004826 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004827 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004828 }
4829 }
4830 }
4831
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004832 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004833}
4834
4835
4836
4837//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004838// SCEVCallbackVH Class Implementation
4839//===----------------------------------------------------------------------===//
4840
Dan Gohman1959b752009-05-19 19:22:47 +00004841void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00004842 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4843 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4844 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004845 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4846 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004847 SE->Scalars.erase(getValPtr());
4848 // this now dangles!
4849}
4850
Dan Gohman1959b752009-05-19 19:22:47 +00004851void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004852 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4853
4854 // Forget all the expressions associated with users of the old value,
4855 // so that future queries will recompute the expressions using the new
4856 // value.
4857 SmallVector<User *, 16> Worklist;
4858 Value *Old = getValPtr();
4859 bool DeleteOld = false;
4860 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4861 UI != UE; ++UI)
4862 Worklist.push_back(*UI);
4863 while (!Worklist.empty()) {
4864 User *U = Worklist.pop_back_val();
4865 // Deleting the Old value will cause this to dangle. Postpone
4866 // that until everything else is done.
4867 if (U == Old) {
4868 DeleteOld = true;
4869 continue;
4870 }
4871 if (PHINode *PN = dyn_cast<PHINode>(U))
4872 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004873 if (Instruction *I = dyn_cast<Instruction>(U))
4874 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004875 if (SE->Scalars.erase(U))
4876 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4877 UI != UE; ++UI)
4878 Worklist.push_back(*UI);
4879 }
4880 if (DeleteOld) {
4881 if (PHINode *PN = dyn_cast<PHINode>(Old))
4882 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004883 if (Instruction *I = dyn_cast<Instruction>(Old))
4884 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004885 SE->Scalars.erase(Old);
4886 // this now dangles!
4887 }
4888 // this may dangle!
4889}
4890
Dan Gohman1959b752009-05-19 19:22:47 +00004891ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004892 : CallbackVH(V), SE(se) {}
4893
4894//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004895// ScalarEvolution Class Implementation
4896//===----------------------------------------------------------------------===//
4897
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004898ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00004899 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004900}
4901
Chris Lattner53e677a2004-04-02 20:23:17 +00004902bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004903 this->F = &F;
4904 LI = &getAnalysis<LoopInfo>();
4905 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004906 return false;
4907}
4908
4909void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004910 Scalars.clear();
4911 BackedgeTakenCounts.clear();
4912 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004913 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00004914 UniqueSCEVs.clear();
4915 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00004916}
4917
4918void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4919 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004920 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004921}
4922
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004923bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004924 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004925}
4926
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004927static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004928 const Loop *L) {
4929 // Print all inner loops first
4930 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4931 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004932
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004933 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004934
Devang Patelb7211a22007-08-21 00:31:24 +00004935 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004936 L->getExitBlocks(ExitBlocks);
4937 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004938 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004939
Dan Gohman46bdfb02009-02-24 18:55:53 +00004940 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4941 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004942 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004943 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004944 }
4945
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004946 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00004947 OS << "Loop " << L->getHeader()->getName() << ": ";
4948
4949 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4950 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4951 } else {
4952 OS << "Unpredictable max backedge-taken count. ";
4953 }
4954
4955 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004956}
4957
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004958void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004959 // ScalarEvolution's implementaiton of the print method is to print
4960 // out SCEV values of all instructions that are interesting. Doing
4961 // this potentially causes it to create new SCEV objects though,
4962 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00004963 // observable from outside the class though, so casting away the
4964 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004965 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004966
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004967 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004968 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004969 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004970 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004971 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004972 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004973 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004974
Dan Gohman0c689c52009-06-19 17:49:54 +00004975 const Loop *L = LI->getLoopFor((*I).getParent());
4976
Dan Gohman0bba49c2009-07-07 17:06:11 +00004977 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004978 if (AtUse != SV) {
4979 OS << " --> ";
4980 AtUse->print(OS);
4981 }
4982
4983 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004984 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004985 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004986 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004987 OS << "<<Unknown>>";
4988 } else {
4989 OS << *ExitValue;
4990 }
4991 }
4992
Chris Lattner53e677a2004-04-02 20:23:17 +00004993 OS << "\n";
4994 }
4995
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004996 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4997 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4998 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004999}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005000
5001void ScalarEvolution::print(std::ostream &o, const Module *M) const {
5002 raw_os_ostream OS(o);
5003 print(OS, M);
5004}