blob: 3c54491967ee3e1e1a757153a00684acc12c519c [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()) {
814 // Check whether the backedge-taken count is SCEVCouldNotCompute.
815 // Note that this serves two purposes: It filters out loops that are
816 // simply not analyzable, and it covers the case where this code is
817 // being called from within backedge-taken count analysis, such that
818 // attempting to ask for the backedge-taken count would likely result
819 // in infinite recursion. In the later case, the analysis code will
820 // cope with a conservative value, and it will take care to purge
821 // that value once it has finished.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000822 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000823 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000824 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000825 // overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000826 const SCEV *Start = AR->getStart();
827 const SCEV *Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000828
829 // Check whether the backedge-taken count can be losslessly casted to
830 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000831 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000832 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000833 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000834 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
835 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000836 const Type *WideTy =
837 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000838 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000839 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000840 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000841 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000842 const SCEV *Add = getAddExpr(Start, ZMul);
843 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000844 getAddExpr(getZeroExtendExpr(Start, WideTy),
845 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
846 getZeroExtendExpr(Step, WideTy)));
847 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000848 // Return the expression with the addrec on the outside.
849 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
850 getZeroExtendExpr(Step, Ty),
851 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000852
853 // Similar to above, only this time treat the step value as signed.
854 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000855 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000856 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000857 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000858 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000859 OperandExtendedAdd =
860 getAddExpr(getZeroExtendExpr(Start, WideTy),
861 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
862 getSignExtendExpr(Step, WideTy)));
863 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000864 // Return the expression with the addrec on the outside.
865 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
866 getSignExtendExpr(Step, Ty),
867 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000868 }
869 }
870 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000871
Dan Gohman1c343752009-06-27 21:21:31 +0000872 FoldingSetNodeID ID;
873 ID.AddInteger(scZeroExtend);
874 ID.AddPointer(Op);
875 ID.AddPointer(Ty);
876 void *IP = 0;
877 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
878 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
879 new (S) SCEVZeroExtendExpr(Op, Ty);
880 UniqueSCEVs.InsertNode(S, IP);
881 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000882}
883
Dan Gohman0bba49c2009-07-07 17:06:11 +0000884const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohman01ecca22009-04-27 20:16:15 +0000885 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000886 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000887 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000888 assert(isSCEVable(Ty) &&
889 "This is not a conversion to a SCEVable type!");
890 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000891
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000892 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000893 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000894 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000895 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
896 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000897 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000898 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000899
Dan Gohman20900ca2009-04-22 16:20:48 +0000900 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000901 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000902 return getSignExtendExpr(SS->getOperand(), Ty);
903
Dan Gohman01ecca22009-04-27 20:16:15 +0000904 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000905 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000906 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000907 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000908 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000909 if (AR->isAffine()) {
910 // Check whether the backedge-taken count is SCEVCouldNotCompute.
911 // Note that this serves two purposes: It filters out loops that are
912 // simply not analyzable, and it covers the case where this code is
913 // being called from within backedge-taken count analysis, such that
914 // attempting to ask for the backedge-taken count would likely result
915 // in infinite recursion. In the later case, the analysis code will
916 // cope with a conservative value, and it will take care to purge
917 // that value once it has finished.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000918 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000919 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000920 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000921 // overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000922 const SCEV *Start = AR->getStart();
923 const SCEV *Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000924
925 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000926 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000927 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000928 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000929 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000930 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
931 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000932 const Type *WideTy =
933 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000934 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000935 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000936 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000937 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000938 const SCEV *Add = getAddExpr(Start, SMul);
939 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000940 getAddExpr(getSignExtendExpr(Start, WideTy),
941 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
942 getSignExtendExpr(Step, WideTy)));
943 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000944 // Return the expression with the addrec on the outside.
945 return getAddRecExpr(getSignExtendExpr(Start, Ty),
946 getSignExtendExpr(Step, Ty),
947 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000948 }
949 }
950 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000951
Dan Gohman1c343752009-06-27 21:21:31 +0000952 FoldingSetNodeID ID;
953 ID.AddInteger(scSignExtend);
954 ID.AddPointer(Op);
955 ID.AddPointer(Ty);
956 void *IP = 0;
957 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
958 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
959 new (S) SCEVSignExtendExpr(Op, Ty);
960 UniqueSCEVs.InsertNode(S, IP);
961 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +0000962}
963
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000964/// getAnyExtendExpr - Return a SCEV for the given operand extended with
965/// unspecified bits out to the given type.
966///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000967const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000968 const Type *Ty) {
969 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
970 "This is not an extending conversion!");
971 assert(isSCEVable(Ty) &&
972 "This is not a conversion to a SCEVable type!");
973 Ty = getEffectiveSCEVType(Ty);
974
975 // Sign-extend negative constants.
976 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
977 if (SC->getValue()->getValue().isNegative())
978 return getSignExtendExpr(Op, Ty);
979
980 // Peel off a truncate cast.
981 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000982 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000983 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
984 return getAnyExtendExpr(NewOp, Ty);
985 return getTruncateOrNoop(NewOp, Ty);
986 }
987
988 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000989 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000990 if (!isa<SCEVZeroExtendExpr>(ZExt))
991 return ZExt;
992
993 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000994 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000995 if (!isa<SCEVSignExtendExpr>(SExt))
996 return SExt;
997
998 // If the expression is obviously signed, use the sext cast value.
999 if (isa<SCEVSMaxExpr>(Op))
1000 return SExt;
1001
1002 // Absent any other information, use the zext cast value.
1003 return ZExt;
1004}
1005
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001006/// CollectAddOperandsWithScales - Process the given Ops list, which is
1007/// a list of operands to be added under the given scale, update the given
1008/// map. This is a helper function for getAddRecExpr. As an example of
1009/// what it does, given a sequence of operands that would form an add
1010/// expression like this:
1011///
1012/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1013///
1014/// where A and B are constants, update the map with these values:
1015///
1016/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1017///
1018/// and add 13 + A*B*29 to AccumulatedConstant.
1019/// This will allow getAddRecExpr to produce this:
1020///
1021/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1022///
1023/// This form often exposes folding opportunities that are hidden in
1024/// the original operand list.
1025///
1026/// Return true iff it appears that any interesting folding opportunities
1027/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1028/// the common case where no interesting opportunities are present, and
1029/// is also used as a check to avoid infinite recursion.
1030///
1031static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001032CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1033 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001034 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001035 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001036 const APInt &Scale,
1037 ScalarEvolution &SE) {
1038 bool Interesting = false;
1039
1040 // Iterate over the add operands.
1041 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1042 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1043 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1044 APInt NewScale =
1045 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1046 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1047 // A multiplication of a constant with another add; recurse.
1048 Interesting |=
1049 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1050 cast<SCEVAddExpr>(Mul->getOperand(1))
1051 ->getOperands(),
1052 NewScale, SE);
1053 } else {
1054 // A multiplication of a constant with some other value. Update
1055 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001056 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1057 const SCEV *Key = SE.getMulExpr(MulOps);
1058 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001059 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001060 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001061 NewOps.push_back(Pair.first->first);
1062 } else {
1063 Pair.first->second += NewScale;
1064 // The map already had an entry for this value, which may indicate
1065 // a folding opportunity.
1066 Interesting = true;
1067 }
1068 }
1069 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1070 // Pull a buried constant out to the outside.
1071 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1072 Interesting = true;
1073 AccumulatedConstant += Scale * C->getValue()->getValue();
1074 } else {
1075 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001076 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001077 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001078 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001079 NewOps.push_back(Pair.first->first);
1080 } else {
1081 Pair.first->second += Scale;
1082 // The map already had an entry for this value, which may indicate
1083 // a folding opportunity.
1084 Interesting = true;
1085 }
1086 }
1087 }
1088
1089 return Interesting;
1090}
1091
1092namespace {
1093 struct APIntCompare {
1094 bool operator()(const APInt &LHS, const APInt &RHS) const {
1095 return LHS.ult(RHS);
1096 }
1097 };
1098}
1099
Dan Gohman6c0866c2009-05-24 23:45:28 +00001100/// getAddExpr - Get a canonical add expression, or something simpler if
1101/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001102const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001103 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001104 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001105#ifndef NDEBUG
1106 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1107 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1108 getEffectiveSCEVType(Ops[0]->getType()) &&
1109 "SCEVAddExpr operand types don't match!");
1110#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001111
1112 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001113 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001114
1115 // If there are any constants, fold them together.
1116 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001117 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001119 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001120 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001121 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001122 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1123 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001124 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001125 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001126 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001127 }
1128
1129 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001130 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001131 Ops.erase(Ops.begin());
1132 --Idx;
1133 }
1134 }
1135
Chris Lattner627018b2004-04-07 16:16:11 +00001136 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001137
Chris Lattner53e677a2004-04-02 20:23:17 +00001138 // Okay, check to see if the same value occurs in the operand list twice. If
1139 // so, merge them together into an multiply expression. Since we sorted the
1140 // list, these values are required to be adjacent.
1141 const Type *Ty = Ops[0]->getType();
1142 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1143 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1144 // Found a match, merge the two values into a multiply, and add any
1145 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001146 const SCEV *Two = getIntegerSCEV(2, Ty);
1147 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001148 if (Ops.size() == 2)
1149 return Mul;
1150 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1151 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001152 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001153 }
1154
Dan Gohman728c7f32009-05-08 21:03:19 +00001155 // Check for truncates. If all the operands are truncated from the same
1156 // type, see if factoring out the truncate would permit the result to be
1157 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1158 // if the contents of the resulting outer trunc fold to something simple.
1159 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1160 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1161 const Type *DstType = Trunc->getType();
1162 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001163 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001164 bool Ok = true;
1165 // Check all the operands to see if they can be represented in the
1166 // source type of the truncate.
1167 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1168 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1169 if (T->getOperand()->getType() != SrcType) {
1170 Ok = false;
1171 break;
1172 }
1173 LargeOps.push_back(T->getOperand());
1174 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1175 // This could be either sign or zero extension, but sign extension
1176 // is much more likely to be foldable here.
1177 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1178 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001179 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001180 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1181 if (const SCEVTruncateExpr *T =
1182 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1183 if (T->getOperand()->getType() != SrcType) {
1184 Ok = false;
1185 break;
1186 }
1187 LargeMulOps.push_back(T->getOperand());
1188 } else if (const SCEVConstant *C =
1189 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1190 // This could be either sign or zero extension, but sign extension
1191 // is much more likely to be foldable here.
1192 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1193 } else {
1194 Ok = false;
1195 break;
1196 }
1197 }
1198 if (Ok)
1199 LargeOps.push_back(getMulExpr(LargeMulOps));
1200 } else {
1201 Ok = false;
1202 break;
1203 }
1204 }
1205 if (Ok) {
1206 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001207 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001208 // If it folds to something simple, use it. Otherwise, don't.
1209 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1210 return getTruncateExpr(Fold, DstType);
1211 }
1212 }
1213
1214 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001215 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1216 ++Idx;
1217
1218 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 if (Idx < Ops.size()) {
1220 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001221 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 // If we have an add, expand the add operands onto the end of the operands
1223 // list.
1224 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1225 Ops.erase(Ops.begin()+Idx);
1226 DeletedAdd = true;
1227 }
1228
1229 // If we deleted at least one add, we added operands to the end of the list,
1230 // and they are not necessarily sorted. Recurse to resort and resimplify
1231 // any operands we just aquired.
1232 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001233 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001234 }
1235
1236 // Skip over the add expression until we get to a multiply.
1237 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1238 ++Idx;
1239
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001240 // Check to see if there are any folding opportunities present with
1241 // operands multiplied by constant values.
1242 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1243 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001244 DenseMap<const SCEV *, APInt> M;
1245 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001246 APInt AccumulatedConstant(BitWidth, 0);
1247 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1248 Ops, APInt(BitWidth, 1), *this)) {
1249 // Some interesting folding opportunity is present, so its worthwhile to
1250 // re-generate the operands list. Group the operands by constant scale,
1251 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001252 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1253 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001254 E = NewOps.end(); I != E; ++I)
1255 MulOpLists[M.find(*I)->second].push_back(*I);
1256 // Re-generate the operands list.
1257 Ops.clear();
1258 if (AccumulatedConstant != 0)
1259 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001260 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1261 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001262 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001263 Ops.push_back(getMulExpr(getConstant(I->first),
1264 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001265 if (Ops.empty())
1266 return getIntegerSCEV(0, Ty);
1267 if (Ops.size() == 1)
1268 return Ops[0];
1269 return getAddExpr(Ops);
1270 }
1271 }
1272
Chris Lattner53e677a2004-04-02 20:23:17 +00001273 // If we are adding something to a multiply expression, make sure the
1274 // something is not already an operand of the multiply. If so, merge it into
1275 // the multiply.
1276 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001277 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001279 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001280 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001281 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001282 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001283 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001284 if (Mul->getNumOperands() != 2) {
1285 // If the multiply has more than two operands, we must get the
1286 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001287 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001288 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001289 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001290 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001291 const SCEV *One = getIntegerSCEV(1, Ty);
1292 const SCEV *AddOne = getAddExpr(InnerMul, One);
1293 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 if (Ops.size() == 2) return OuterMul;
1295 if (AddOp < Idx) {
1296 Ops.erase(Ops.begin()+AddOp);
1297 Ops.erase(Ops.begin()+Idx-1);
1298 } else {
1299 Ops.erase(Ops.begin()+Idx);
1300 Ops.erase(Ops.begin()+AddOp-1);
1301 }
1302 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001303 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001304 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001305
Chris Lattner53e677a2004-04-02 20:23:17 +00001306 // Check this multiply against other multiplies being added together.
1307 for (unsigned OtherMulIdx = Idx+1;
1308 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1309 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001310 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001311 // If MulOp occurs in OtherMul, we can fold the two multiplies
1312 // together.
1313 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1314 OMulOp != e; ++OMulOp)
1315 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1316 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001317 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001318 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001319 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1320 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001321 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001322 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001324 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001325 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001326 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1327 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001328 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001329 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001331 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1332 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001333 if (Ops.size() == 2) return OuterMul;
1334 Ops.erase(Ops.begin()+Idx);
1335 Ops.erase(Ops.begin()+OtherMulIdx-1);
1336 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001337 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 }
1339 }
1340 }
1341 }
1342
1343 // If there are any add recurrences in the operands list, see if any other
1344 // added values are loop invariant. If so, we can fold them into the
1345 // recurrence.
1346 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1347 ++Idx;
1348
1349 // Scan over all recurrences, trying to fold loop invariants into them.
1350 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1351 // Scan all of the other operands to this add and add them to the vector if
1352 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001353 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001354 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1356 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1357 LIOps.push_back(Ops[i]);
1358 Ops.erase(Ops.begin()+i);
1359 --i; --e;
1360 }
1361
1362 // If we found some loop invariants, fold them into the recurrence.
1363 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001364 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001365 LIOps.push_back(AddRec->getStart());
1366
Dan Gohman0bba49c2009-07-07 17:06:11 +00001367 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001368 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001369 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001370
Dan Gohman0bba49c2009-07-07 17:06:11 +00001371 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 // If all of the other operands were loop invariant, we are done.
1373 if (Ops.size() == 1) return NewRec;
1374
1375 // Otherwise, add the folded AddRec by the non-liv parts.
1376 for (unsigned i = 0;; ++i)
1377 if (Ops[i] == AddRec) {
1378 Ops[i] = NewRec;
1379 break;
1380 }
Dan Gohman246b2562007-10-22 18:31:58 +00001381 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 }
1383
1384 // Okay, if there weren't any loop invariants to be folded, check to see if
1385 // there are multiple AddRec's with the same loop induction variable being
1386 // added together. If so, we can fold them.
1387 for (unsigned OtherIdx = Idx+1;
1388 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1389 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001390 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001391 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1392 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001393 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1394 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1396 if (i >= NewOps.size()) {
1397 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1398 OtherAddRec->op_end());
1399 break;
1400 }
Dan Gohman246b2562007-10-22 18:31:58 +00001401 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001402 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001403 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001404
1405 if (Ops.size() == 2) return NewAddRec;
1406
1407 Ops.erase(Ops.begin()+Idx);
1408 Ops.erase(Ops.begin()+OtherIdx-1);
1409 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001410 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 }
1412 }
1413
1414 // Otherwise couldn't fold anything into this recurrence. Move onto the
1415 // next one.
1416 }
1417
1418 // Okay, it looks like we really DO need an add expr. Check to see if we
1419 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001420 FoldingSetNodeID ID;
1421 ID.AddInteger(scAddExpr);
1422 ID.AddInteger(Ops.size());
1423 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1424 ID.AddPointer(Ops[i]);
1425 void *IP = 0;
1426 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1427 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1428 new (S) SCEVAddExpr(Ops);
1429 UniqueSCEVs.InsertNode(S, IP);
1430 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001431}
1432
1433
Dan Gohman6c0866c2009-05-24 23:45:28 +00001434/// getMulExpr - Get a canonical multiply expression, or something simpler if
1435/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001436const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001438#ifndef NDEBUG
1439 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1440 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1441 getEffectiveSCEVType(Ops[0]->getType()) &&
1442 "SCEVMulExpr operand types don't match!");
1443#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001444
1445 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001446 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001447
1448 // If there are any constants, fold them together.
1449 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001450 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001451
1452 // C1*(C2+V) -> C1*C2 + C1*V
1453 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001454 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001455 if (Add->getNumOperands() == 2 &&
1456 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001457 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1458 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001459
1460
1461 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001462 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 // We found two constants, fold them together!
Dan Gohman64a845e2009-06-24 04:48:43 +00001464 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001465 RHSC->getValue()->getValue());
1466 Ops[0] = getConstant(Fold);
1467 Ops.erase(Ops.begin()+1); // Erase the folded element
1468 if (Ops.size() == 1) return Ops[0];
1469 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 }
1471
1472 // If we are left with a constant one being multiplied, strip it off.
1473 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1474 Ops.erase(Ops.begin());
1475 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001476 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 // If we have a multiply of zero, it will always be zero.
1478 return Ops[0];
1479 }
1480 }
1481
1482 // Skip over the add expression until we get to a multiply.
1483 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1484 ++Idx;
1485
1486 if (Ops.size() == 1)
1487 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001488
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 // If there are mul operands inline them all into this expression.
1490 if (Idx < Ops.size()) {
1491 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001492 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 // If we have an mul, expand the mul operands onto the end of the operands
1494 // list.
1495 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1496 Ops.erase(Ops.begin()+Idx);
1497 DeletedMul = true;
1498 }
1499
1500 // If we deleted at least one mul, we added operands to the end of the list,
1501 // and they are not necessarily sorted. Recurse to resort and resimplify
1502 // any operands we just aquired.
1503 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001504 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 }
1506
1507 // If there are any add recurrences in the operands list, see if any other
1508 // added values are loop invariant. If so, we can fold them into the
1509 // recurrence.
1510 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1511 ++Idx;
1512
1513 // Scan over all recurrences, trying to fold loop invariants into them.
1514 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1515 // Scan all of the other operands to this mul and add them to the vector if
1516 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001517 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001518 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001519 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1520 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1521 LIOps.push_back(Ops[i]);
1522 Ops.erase(Ops.begin()+i);
1523 --i; --e;
1524 }
1525
1526 // If we found some loop invariants, fold them into the recurrence.
1527 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001528 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001529 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001530 NewOps.reserve(AddRec->getNumOperands());
1531 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001532 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001534 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001535 } else {
1536 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001537 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001539 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 }
1541 }
1542
Dan Gohman0bba49c2009-07-07 17:06:11 +00001543 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001544
1545 // If all of the other operands were loop invariant, we are done.
1546 if (Ops.size() == 1) return NewRec;
1547
1548 // Otherwise, multiply the folded AddRec by the non-liv parts.
1549 for (unsigned i = 0;; ++i)
1550 if (Ops[i] == AddRec) {
1551 Ops[i] = NewRec;
1552 break;
1553 }
Dan Gohman246b2562007-10-22 18:31:58 +00001554 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001555 }
1556
1557 // Okay, if there weren't any loop invariants to be folded, check to see if
1558 // there are multiple AddRec's with the same loop induction variable being
1559 // multiplied together. If so, we can fold them.
1560 for (unsigned OtherIdx = Idx+1;
1561 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1562 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001563 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001564 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1565 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001566 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001567 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001569 const SCEV *B = F->getStepRecurrence(*this);
1570 const SCEV *D = G->getStepRecurrence(*this);
1571 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001572 getMulExpr(G, B),
1573 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001574 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001575 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001576 if (Ops.size() == 2) return NewAddRec;
1577
1578 Ops.erase(Ops.begin()+Idx);
1579 Ops.erase(Ops.begin()+OtherIdx-1);
1580 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001581 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001582 }
1583 }
1584
1585 // Otherwise couldn't fold anything into this recurrence. Move onto the
1586 // next one.
1587 }
1588
1589 // Okay, it looks like we really DO need an mul expr. Check to see if we
1590 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001591 FoldingSetNodeID ID;
1592 ID.AddInteger(scMulExpr);
1593 ID.AddInteger(Ops.size());
1594 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1595 ID.AddPointer(Ops[i]);
1596 void *IP = 0;
1597 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1598 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1599 new (S) SCEVMulExpr(Ops);
1600 UniqueSCEVs.InsertNode(S, IP);
1601 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001602}
1603
Dan Gohman6c0866c2009-05-24 23:45:28 +00001604/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1605/// possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001606const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1607 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001608 assert(getEffectiveSCEVType(LHS->getType()) ==
1609 getEffectiveSCEVType(RHS->getType()) &&
1610 "SCEVUDivExpr operand types don't match!");
1611
Dan Gohman622ed672009-05-04 22:02:23 +00001612 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001613 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001614 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001615 if (RHSC->isZero())
1616 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001617
Dan Gohman185cf032009-05-08 20:18:49 +00001618 // Determine if the division can be folded into the operands of
1619 // its operands.
1620 // TODO: Generalize this to non-constants by using known-bits information.
1621 const Type *Ty = LHS->getType();
1622 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1623 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1624 // For non-power-of-two values, effectively round the value up to the
1625 // nearest power of two.
1626 if (!RHSC->getValue()->getValue().isPowerOf2())
1627 ++MaxShiftAmt;
1628 const IntegerType *ExtTy =
1629 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1630 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1631 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1632 if (const SCEVConstant *Step =
1633 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1634 if (!Step->getValue()->getValue()
1635 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001636 getZeroExtendExpr(AR, ExtTy) ==
1637 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1638 getZeroExtendExpr(Step, ExtTy),
1639 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001640 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001641 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1642 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1643 return getAddRecExpr(Operands, AR->getLoop());
1644 }
1645 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001646 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001647 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001648 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1649 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1650 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001651 // Find an operand that's safely divisible.
1652 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001653 const SCEV *Op = M->getOperand(i);
1654 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001655 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001656 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1657 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001658 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001659 Operands[i] = Div;
1660 return getMulExpr(Operands);
1661 }
1662 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001663 }
Dan Gohman185cf032009-05-08 20:18:49 +00001664 // (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 +00001665 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001666 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001667 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1668 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1669 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1670 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001671 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001672 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001673 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1674 break;
1675 Operands.push_back(Op);
1676 }
1677 if (Operands.size() == A->getNumOperands())
1678 return getAddExpr(Operands);
1679 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001680 }
Dan Gohman185cf032009-05-08 20:18:49 +00001681
1682 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001683 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001684 Constant *LHSCV = LHSC->getValue();
1685 Constant *RHSCV = RHSC->getValue();
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001686 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1687 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001688 }
1689 }
1690
Dan Gohman1c343752009-06-27 21:21:31 +00001691 FoldingSetNodeID ID;
1692 ID.AddInteger(scUDivExpr);
1693 ID.AddPointer(LHS);
1694 ID.AddPointer(RHS);
1695 void *IP = 0;
1696 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1697 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1698 new (S) SCEVUDivExpr(LHS, RHS);
1699 UniqueSCEVs.InsertNode(S, IP);
1700 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001701}
1702
1703
Dan Gohman6c0866c2009-05-24 23:45:28 +00001704/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1705/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001706const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1707 const SCEV *Step, const Loop *L) {
1708 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001709 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001710 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001711 if (StepChrec->getLoop() == L) {
1712 Operands.insert(Operands.end(), StepChrec->op_begin(),
1713 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001714 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 }
1716
1717 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001718 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001719}
1720
Dan Gohman6c0866c2009-05-24 23:45:28 +00001721/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1722/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001723const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001724ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001725 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001726 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001727#ifndef NDEBUG
1728 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1729 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1730 getEffectiveSCEVType(Operands[0]->getType()) &&
1731 "SCEVAddRecExpr operand types don't match!");
1732#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001733
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001734 if (Operands.back()->isZero()) {
1735 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001736 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001737 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001738
Dan Gohmand9cc7492008-08-08 18:33:12 +00001739 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001740 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001741 const Loop* NestedLoop = NestedAR->getLoop();
1742 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001743 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001744 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001745 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001746 // AddRecs require their operands be loop-invariant with respect to their
1747 // loops. Don't perform this transformation if it would break this
1748 // requirement.
1749 bool AllInvariant = true;
1750 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1751 if (!Operands[i]->isLoopInvariant(L)) {
1752 AllInvariant = false;
1753 break;
1754 }
1755 if (AllInvariant) {
1756 NestedOperands[0] = getAddRecExpr(Operands, L);
1757 AllInvariant = true;
1758 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1759 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1760 AllInvariant = false;
1761 break;
1762 }
1763 if (AllInvariant)
1764 // Ok, both add recurrences are valid after the transformation.
1765 return getAddRecExpr(NestedOperands, NestedLoop);
1766 }
1767 // Reset Operands to its original state.
1768 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001769 }
1770 }
1771
Dan Gohman1c343752009-06-27 21:21:31 +00001772 FoldingSetNodeID ID;
1773 ID.AddInteger(scAddRecExpr);
1774 ID.AddInteger(Operands.size());
1775 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1776 ID.AddPointer(Operands[i]);
1777 ID.AddPointer(L);
1778 void *IP = 0;
1779 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1780 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1781 new (S) SCEVAddRecExpr(Operands, L);
1782 UniqueSCEVs.InsertNode(S, IP);
1783 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001784}
1785
Dan Gohman9311ef62009-06-24 14:49:00 +00001786const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1787 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001788 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001789 Ops.push_back(LHS);
1790 Ops.push_back(RHS);
1791 return getSMaxExpr(Ops);
1792}
1793
Dan Gohman0bba49c2009-07-07 17:06:11 +00001794const SCEV *
1795ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001796 assert(!Ops.empty() && "Cannot get empty smax!");
1797 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001798#ifndef NDEBUG
1799 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1800 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1801 getEffectiveSCEVType(Ops[0]->getType()) &&
1802 "SCEVSMaxExpr operand types don't match!");
1803#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001804
1805 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001806 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001807
1808 // If there are any constants, fold them together.
1809 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001810 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001811 ++Idx;
1812 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001813 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001814 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001815 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001816 APIntOps::smax(LHSC->getValue()->getValue(),
1817 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001818 Ops[0] = getConstant(Fold);
1819 Ops.erase(Ops.begin()+1); // Erase the folded element
1820 if (Ops.size() == 1) return Ops[0];
1821 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001822 }
1823
Dan Gohmane5aceed2009-06-24 14:46:22 +00001824 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001825 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1826 Ops.erase(Ops.begin());
1827 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001828 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1829 // If we have an smax with a constant maximum-int, it will always be
1830 // maximum-int.
1831 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001832 }
1833 }
1834
1835 if (Ops.size() == 1) return Ops[0];
1836
1837 // Find the first SMax
1838 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1839 ++Idx;
1840
1841 // Check to see if one of the operands is an SMax. If so, expand its operands
1842 // onto our operand list, and recurse to simplify.
1843 if (Idx < Ops.size()) {
1844 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001845 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001846 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1847 Ops.erase(Ops.begin()+Idx);
1848 DeletedSMax = true;
1849 }
1850
1851 if (DeletedSMax)
1852 return getSMaxExpr(Ops);
1853 }
1854
1855 // Okay, check to see if the same value occurs in the operand list twice. If
1856 // so, delete one. Since we sorted the list, these values are required to
1857 // be adjacent.
1858 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1859 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1860 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1861 --i; --e;
1862 }
1863
1864 if (Ops.size() == 1) return Ops[0];
1865
1866 assert(!Ops.empty() && "Reduced smax down to nothing!");
1867
Nick Lewycky3e630762008-02-20 06:48:22 +00001868 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001869 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001870 FoldingSetNodeID ID;
1871 ID.AddInteger(scSMaxExpr);
1872 ID.AddInteger(Ops.size());
1873 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1874 ID.AddPointer(Ops[i]);
1875 void *IP = 0;
1876 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1877 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1878 new (S) SCEVSMaxExpr(Ops);
1879 UniqueSCEVs.InsertNode(S, IP);
1880 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001881}
1882
Dan Gohman9311ef62009-06-24 14:49:00 +00001883const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1884 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001885 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001886 Ops.push_back(LHS);
1887 Ops.push_back(RHS);
1888 return getUMaxExpr(Ops);
1889}
1890
Dan Gohman0bba49c2009-07-07 17:06:11 +00001891const SCEV *
1892ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001893 assert(!Ops.empty() && "Cannot get empty umax!");
1894 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001895#ifndef NDEBUG
1896 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1897 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1898 getEffectiveSCEVType(Ops[0]->getType()) &&
1899 "SCEVUMaxExpr operand types don't match!");
1900#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001901
1902 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001903 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001904
1905 // If there are any constants, fold them together.
1906 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001907 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001908 ++Idx;
1909 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001910 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001911 // We found two constants, fold them together!
1912 ConstantInt *Fold = ConstantInt::get(
1913 APIntOps::umax(LHSC->getValue()->getValue(),
1914 RHSC->getValue()->getValue()));
1915 Ops[0] = getConstant(Fold);
1916 Ops.erase(Ops.begin()+1); // Erase the folded element
1917 if (Ops.size() == 1) return Ops[0];
1918 LHSC = cast<SCEVConstant>(Ops[0]);
1919 }
1920
Dan Gohmane5aceed2009-06-24 14:46:22 +00001921 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001922 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1923 Ops.erase(Ops.begin());
1924 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001925 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1926 // If we have an umax with a constant maximum-int, it will always be
1927 // maximum-int.
1928 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001929 }
1930 }
1931
1932 if (Ops.size() == 1) return Ops[0];
1933
1934 // Find the first UMax
1935 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1936 ++Idx;
1937
1938 // Check to see if one of the operands is a UMax. If so, expand its operands
1939 // onto our operand list, and recurse to simplify.
1940 if (Idx < Ops.size()) {
1941 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001942 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001943 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1944 Ops.erase(Ops.begin()+Idx);
1945 DeletedUMax = true;
1946 }
1947
1948 if (DeletedUMax)
1949 return getUMaxExpr(Ops);
1950 }
1951
1952 // Okay, check to see if the same value occurs in the operand list twice. If
1953 // so, delete one. Since we sorted the list, these values are required to
1954 // be adjacent.
1955 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1956 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1957 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1958 --i; --e;
1959 }
1960
1961 if (Ops.size() == 1) return Ops[0];
1962
1963 assert(!Ops.empty() && "Reduced umax down to nothing!");
1964
1965 // Okay, it looks like we really DO need a umax expr. Check to see if we
1966 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001967 FoldingSetNodeID ID;
1968 ID.AddInteger(scUMaxExpr);
1969 ID.AddInteger(Ops.size());
1970 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1971 ID.AddPointer(Ops[i]);
1972 void *IP = 0;
1973 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1974 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1975 new (S) SCEVUMaxExpr(Ops);
1976 UniqueSCEVs.InsertNode(S, IP);
1977 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00001978}
1979
Dan Gohman9311ef62009-06-24 14:49:00 +00001980const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1981 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001982 // ~smax(~x, ~y) == smin(x, y).
1983 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1984}
1985
Dan Gohman9311ef62009-06-24 14:49:00 +00001986const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1987 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001988 // ~umax(~x, ~y) == umin(x, y)
1989 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1990}
1991
Dan Gohman0bba49c2009-07-07 17:06:11 +00001992const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00001993 // Don't attempt to do anything other than create a SCEVUnknown object
1994 // here. createSCEV only calls getUnknown after checking for all other
1995 // interesting possibilities, and any other code that calls getUnknown
1996 // is doing so in order to hide a value from SCEV canonicalization.
1997
Dan Gohman1c343752009-06-27 21:21:31 +00001998 FoldingSetNodeID ID;
1999 ID.AddInteger(scUnknown);
2000 ID.AddPointer(V);
2001 void *IP = 0;
2002 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2003 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2004 new (S) SCEVUnknown(V);
2005 UniqueSCEVs.InsertNode(S, IP);
2006 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002007}
2008
Chris Lattner53e677a2004-04-02 20:23:17 +00002009//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002010// Basic SCEV Analysis and PHI Idiom Recognition Code
2011//
2012
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002013/// isSCEVable - Test if values of the given type are analyzable within
2014/// the SCEV framework. This primarily includes integer types, and it
2015/// can optionally include pointer types if the ScalarEvolution class
2016/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002017bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002018 // Integers are always SCEVable.
2019 if (Ty->isInteger())
2020 return true;
2021
2022 // Pointers are SCEVable if TargetData information is available
2023 // to provide pointer size information.
2024 if (isa<PointerType>(Ty))
2025 return TD != NULL;
2026
2027 // Otherwise it's not SCEVable.
2028 return false;
2029}
2030
2031/// getTypeSizeInBits - Return the size in bits of the specified type,
2032/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002033uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002034 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2035
2036 // If we have a TargetData, use it!
2037 if (TD)
2038 return TD->getTypeSizeInBits(Ty);
2039
2040 // Otherwise, we support only integer types.
2041 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2042 return Ty->getPrimitiveSizeInBits();
2043}
2044
2045/// getEffectiveSCEVType - Return a type with the same bitwidth as
2046/// the given type and which represents how SCEV will treat the given
2047/// type, for which isSCEVable must return true. For pointer types,
2048/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002049const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002050 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2051
2052 if (Ty->isInteger())
2053 return Ty;
2054
2055 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2056 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002057}
Chris Lattner53e677a2004-04-02 20:23:17 +00002058
Dan Gohman0bba49c2009-07-07 17:06:11 +00002059const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002060 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002061}
2062
Dan Gohman92fa56e2009-05-04 22:20:30 +00002063/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00002064/// computed.
2065bool ScalarEvolution::hasSCEV(Value *V) const {
2066 return Scalars.count(V);
2067}
2068
Chris Lattner53e677a2004-04-02 20:23:17 +00002069/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2070/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002071const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002072 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002073
Dan Gohman0bba49c2009-07-07 17:06:11 +00002074 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002075 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002076 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002077 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002078 return S;
2079}
2080
Dan Gohman6bbcba12009-06-24 00:54:57 +00002081/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002082/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002083const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002084 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2085 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002086}
2087
2088/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2089///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002090const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002091 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanb8be8b72009-06-24 00:38:39 +00002092 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002093
2094 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002095 Ty = getEffectiveSCEVType(Ty);
2096 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002097}
2098
2099/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002100const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002101 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanb8be8b72009-06-24 00:38:39 +00002102 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002103
2104 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002105 Ty = getEffectiveSCEVType(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002106 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00002107 return getMinusSCEV(AllOnes, V);
2108}
2109
2110/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2111///
Dan Gohman9311ef62009-06-24 14:49:00 +00002112const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2113 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002114 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002115 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002116}
2117
2118/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2119/// input value to the specified type. If the type must be extended, it is zero
2120/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002121const SCEV *
2122ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002123 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002124 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002125 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2126 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002127 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002128 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002129 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002130 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002131 return getTruncateExpr(V, Ty);
2132 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002133}
2134
2135/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2136/// input value to the specified type. If the type must be extended, it is sign
2137/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002138const SCEV *
2139ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002140 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002141 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002142 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2143 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002144 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002145 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002146 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002147 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002148 return getTruncateExpr(V, Ty);
2149 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002150}
2151
Dan Gohman467c4302009-05-13 03:46:30 +00002152/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2153/// input value to the specified type. If the type must be extended, it is zero
2154/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002155const SCEV *
2156ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002157 const Type *SrcTy = V->getType();
2158 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2159 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2160 "Cannot noop or zero extend with non-integer arguments!");
2161 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2162 "getNoopOrZeroExtend cannot truncate!");
2163 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2164 return V; // No conversion
2165 return getZeroExtendExpr(V, Ty);
2166}
2167
2168/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2169/// input value to the specified type. If the type must be extended, it is sign
2170/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002171const SCEV *
2172ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002173 const Type *SrcTy = V->getType();
2174 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2175 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2176 "Cannot noop or sign extend with non-integer arguments!");
2177 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2178 "getNoopOrSignExtend cannot truncate!");
2179 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2180 return V; // No conversion
2181 return getSignExtendExpr(V, Ty);
2182}
2183
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002184/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2185/// the input value to the specified type. If the type must be extended,
2186/// it is extended with unspecified bits. The conversion must not be
2187/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002188const SCEV *
2189ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002190 const Type *SrcTy = V->getType();
2191 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2192 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2193 "Cannot noop or any extend with non-integer arguments!");
2194 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2195 "getNoopOrAnyExtend cannot truncate!");
2196 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2197 return V; // No conversion
2198 return getAnyExtendExpr(V, Ty);
2199}
2200
Dan Gohman467c4302009-05-13 03:46:30 +00002201/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2202/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002203const SCEV *
2204ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002205 const Type *SrcTy = V->getType();
2206 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2207 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2208 "Cannot truncate or noop with non-integer arguments!");
2209 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2210 "getTruncateOrNoop cannot extend!");
2211 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2212 return V; // No conversion
2213 return getTruncateExpr(V, Ty);
2214}
2215
Dan Gohmana334aa72009-06-22 00:31:57 +00002216/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2217/// the types using zero-extension, and then perform a umax operation
2218/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002219const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2220 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002221 const SCEV *PromotedLHS = LHS;
2222 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002223
2224 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2225 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2226 else
2227 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2228
2229 return getUMaxExpr(PromotedLHS, PromotedRHS);
2230}
2231
Dan Gohmanc9759e82009-06-22 15:03:27 +00002232/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2233/// the types using zero-extension, and then perform a umin operation
2234/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002235const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2236 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002237 const SCEV *PromotedLHS = LHS;
2238 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002239
2240 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2241 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2242 else
2243 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2244
2245 return getUMinExpr(PromotedLHS, PromotedRHS);
2246}
2247
Chris Lattner4dc534c2005-02-13 04:37:18 +00002248/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2249/// the specified instruction and replaces any references to the symbolic value
2250/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002251void
2252ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2253 const SCEV *SymName,
2254 const SCEV *NewVal) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002255 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002256 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002257 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002258
Dan Gohman0bba49c2009-07-07 17:06:11 +00002259 const SCEV *NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002260 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002261 if (NV == SI->second) return; // No change.
2262
2263 SI->second = NV; // Update the scalars map!
2264
2265 // Any instruction values that use this instruction might also need to be
2266 // updated!
2267 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2268 UI != E; ++UI)
2269 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2270}
Chris Lattner53e677a2004-04-02 20:23:17 +00002271
2272/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2273/// a loop header, making it a potential recurrence, or it doesn't.
2274///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002275const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002276 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002277 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002278 if (L->getHeader() == PN->getParent()) {
2279 // If it lives in the loop header, it has two incoming values, one
2280 // from outside the loop, and one from inside.
2281 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2282 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002283
Chris Lattner53e677a2004-04-02 20:23:17 +00002284 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002285 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002286 assert(Scalars.find(PN) == Scalars.end() &&
2287 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002288 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002289
2290 // Using this symbolic name for the PHI, analyze the value coming around
2291 // the back-edge.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002292 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002293
2294 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2295 // has a special value for the first iteration of the loop.
2296
2297 // If the value coming around the backedge is an add with the symbolic
2298 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002299 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002300 // If there is a single occurrence of the symbolic value, replace it
2301 // with a recurrence.
2302 unsigned FoundIndex = Add->getNumOperands();
2303 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2304 if (Add->getOperand(i) == SymbolicName)
2305 if (FoundIndex == e) {
2306 FoundIndex = i;
2307 break;
2308 }
2309
2310 if (FoundIndex != Add->getNumOperands()) {
2311 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002312 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002313 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2314 if (i != FoundIndex)
2315 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002316 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002317
2318 // This is not a valid addrec if the step amount is varying each
2319 // loop iteration, but is not itself an addrec in this loop.
2320 if (Accum->isLoopInvariant(L) ||
2321 (isa<SCEVAddRecExpr>(Accum) &&
2322 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002323 const SCEV *StartVal =
2324 getSCEV(PN->getIncomingValue(IncomingEdge));
2325 const SCEV *PHISCEV =
2326 getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002327
2328 // Okay, for the entire analysis of this edge we assumed the PHI
2329 // to be symbolic. We now need to go back and update all of the
2330 // entries for the scalars that use the PHI (except for the PHI
2331 // itself) to use the new analyzed value instead of the "symbolic"
2332 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002333 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002334 return PHISCEV;
2335 }
2336 }
Dan Gohman622ed672009-05-04 22:02:23 +00002337 } else if (const SCEVAddRecExpr *AddRec =
2338 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002339 // Otherwise, this could be a loop like this:
2340 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2341 // In this case, j = {1,+,1} and BEValue is j.
2342 // Because the other in-value of i (0) fits the evolution of BEValue
2343 // i really is an addrec evolution.
2344 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002345 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002346
2347 // If StartVal = j.start - j.stride, we can use StartVal as the
2348 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002349 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002350 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002351 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002352 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002353
2354 // Okay, for the entire analysis of this edge we assumed the PHI
2355 // to be symbolic. We now need to go back and update all of the
2356 // entries for the scalars that use the PHI (except for the PHI
2357 // itself) to use the new analyzed value instead of the "symbolic"
2358 // value.
2359 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2360 return PHISCEV;
2361 }
2362 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002363 }
2364
2365 return SymbolicName;
2366 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002367
Chris Lattner53e677a2004-04-02 20:23:17 +00002368 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002369 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002370}
2371
Dan Gohman26466c02009-05-08 20:26:55 +00002372/// createNodeForGEP - Expand GEP instructions into add and multiply
2373/// operations. This allows them to be analyzed by regular SCEV code.
2374///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002375const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002376
2377 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002378 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002379 // Don't attempt to analyze GEPs over unsized objects.
2380 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2381 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002382 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002383 gep_type_iterator GTI = gep_type_begin(GEP);
2384 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2385 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002386 I != E; ++I) {
2387 Value *Index = *I;
2388 // Compute the (potentially symbolic) offset in bytes for this index.
2389 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2390 // For a struct, add the member offset.
2391 const StructLayout &SL = *TD->getStructLayout(STy);
2392 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2393 uint64_t Offset = SL.getElementOffset(FieldNo);
2394 TotalOffset = getAddExpr(TotalOffset,
2395 getIntegerSCEV(Offset, IntPtrTy));
2396 } else {
2397 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002398 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002399 if (!isa<PointerType>(LocalOffset->getType()))
2400 // Getelementptr indicies are signed.
2401 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2402 IntPtrTy);
2403 LocalOffset =
2404 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002405 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002406 IntPtrTy));
2407 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2408 }
2409 }
2410 return getAddExpr(getSCEV(Base), TotalOffset);
2411}
2412
Nick Lewycky83bb0052007-11-22 07:59:40 +00002413/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2414/// guaranteed to end in (at every loop iteration). It is, at the same time,
2415/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2416/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002417uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002418ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002419 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002420 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002421
Dan Gohman622ed672009-05-04 22:02:23 +00002422 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002423 return std::min(GetMinTrailingZeros(T->getOperand()),
2424 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002425
Dan Gohman622ed672009-05-04 22:02:23 +00002426 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002427 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2428 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2429 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002430 }
2431
Dan Gohman622ed672009-05-04 22:02:23 +00002432 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002433 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2434 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2435 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002436 }
2437
Dan Gohman622ed672009-05-04 22:02:23 +00002438 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002439 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002440 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002441 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002442 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002443 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002444 }
2445
Dan Gohman622ed672009-05-04 22:02:23 +00002446 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002447 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002448 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2449 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002450 for (unsigned i = 1, e = M->getNumOperands();
2451 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002452 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002453 BitWidth);
2454 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002455 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002456
Dan Gohman622ed672009-05-04 22:02:23 +00002457 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002458 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002459 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002460 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002461 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002462 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002463 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002464
Dan Gohman622ed672009-05-04 22:02:23 +00002465 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002466 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002467 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002468 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002469 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002470 return MinOpRes;
2471 }
2472
Dan Gohman622ed672009-05-04 22:02:23 +00002473 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002474 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002475 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002476 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002477 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002478 return MinOpRes;
2479 }
2480
Dan Gohman2c364ad2009-06-19 23:29:04 +00002481 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2482 // For a SCEVUnknown, ask ValueTracking.
2483 unsigned BitWidth = getTypeSizeInBits(U->getType());
2484 APInt Mask = APInt::getAllOnesValue(BitWidth);
2485 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2486 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2487 return Zeros.countTrailingOnes();
2488 }
2489
2490 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002491 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002492}
Chris Lattner53e677a2004-04-02 20:23:17 +00002493
Dan Gohman2c364ad2009-06-19 23:29:04 +00002494uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002495ScalarEvolution::GetMinLeadingZeros(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002496 // TODO: Handle other SCEV expression types here.
2497
2498 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2499 return C->getValue()->getValue().countLeadingZeros();
2500
2501 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2502 // A zero-extension cast adds zero bits.
2503 return GetMinLeadingZeros(C->getOperand()) +
2504 (getTypeSizeInBits(C->getType()) -
2505 getTypeSizeInBits(C->getOperand()->getType()));
2506 }
2507
2508 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2509 // For a SCEVUnknown, ask ValueTracking.
2510 unsigned BitWidth = getTypeSizeInBits(U->getType());
2511 APInt Mask = APInt::getAllOnesValue(BitWidth);
2512 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2513 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2514 return Zeros.countLeadingOnes();
2515 }
2516
2517 return 1;
2518}
2519
2520uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002521ScalarEvolution::GetMinSignBits(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002522 // TODO: Handle other SCEV expression types here.
2523
2524 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2525 const APInt &A = C->getValue()->getValue();
2526 return A.isNegative() ? A.countLeadingOnes() :
2527 A.countLeadingZeros();
2528 }
2529
2530 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2531 // A sign-extension cast adds sign bits.
2532 return GetMinSignBits(C->getOperand()) +
2533 (getTypeSizeInBits(C->getType()) -
2534 getTypeSizeInBits(C->getOperand()->getType()));
2535 }
2536
Dan Gohman62849c02009-06-24 01:05:09 +00002537 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2538 unsigned BitWidth = getTypeSizeInBits(A->getType());
2539
2540 // Special case decrementing a value (ADD X, -1):
2541 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2542 if (CRHS->isAllOnesValue()) {
2543 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2544 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2545 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2546
2547 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2548 // sign bits set.
2549 if (LZ == BitWidth - 1)
2550 return BitWidth;
2551
2552 // If we are subtracting one from a positive number, there is no carry
2553 // out of the result.
2554 if (LZ > 0)
2555 return GetMinSignBits(OtherOpsAdd);
2556 }
2557
2558 // Add can have at most one carry bit. Thus we know that the output
2559 // is, at worst, one more bit than the inputs.
2560 unsigned Min = BitWidth;
2561 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2562 unsigned N = GetMinSignBits(A->getOperand(i));
2563 Min = std::min(Min, N) - 1;
2564 if (Min == 0) return 1;
2565 }
2566 return 1;
2567 }
2568
Dan Gohman2c364ad2009-06-19 23:29:04 +00002569 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2570 // For a SCEVUnknown, ask ValueTracking.
2571 return ComputeNumSignBits(U->getValue(), TD);
2572 }
2573
2574 return 1;
2575}
2576
Chris Lattner53e677a2004-04-02 20:23:17 +00002577/// createSCEV - We know that there is no SCEV for the specified value.
2578/// Analyze the expression.
2579///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002580const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002581 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002582 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002583
Dan Gohman6c459a22008-06-22 19:56:46 +00002584 unsigned Opcode = Instruction::UserOp1;
2585 if (Instruction *I = dyn_cast<Instruction>(V))
2586 Opcode = I->getOpcode();
2587 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2588 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002589 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2590 return getConstant(CI);
2591 else if (isa<ConstantPointerNull>(V))
2592 return getIntegerSCEV(0, V->getType());
2593 else if (isa<UndefValue>(V))
2594 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002595 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002596 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002597
Dan Gohman6c459a22008-06-22 19:56:46 +00002598 User *U = cast<User>(V);
2599 switch (Opcode) {
2600 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002601 return getAddExpr(getSCEV(U->getOperand(0)),
2602 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002603 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002604 return getMulExpr(getSCEV(U->getOperand(0)),
2605 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002606 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002607 return getUDivExpr(getSCEV(U->getOperand(0)),
2608 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002609 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002610 return getMinusSCEV(getSCEV(U->getOperand(0)),
2611 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002612 case Instruction::And:
2613 // For an expression like x&255 that merely masks off the high bits,
2614 // use zext(trunc(x)) as the SCEV expression.
2615 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002616 if (CI->isNullValue())
2617 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002618 if (CI->isAllOnesValue())
2619 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002620 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002621
2622 // Instcombine's ShrinkDemandedConstant may strip bits out of
2623 // constants, obscuring what would otherwise be a low-bits mask.
2624 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2625 // knew about to reconstruct a low-bits mask value.
2626 unsigned LZ = A.countLeadingZeros();
2627 unsigned BitWidth = A.getBitWidth();
2628 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2629 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2630 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2631
2632 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2633
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002634 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002635 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002636 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002637 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002638 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002639 }
2640 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002641
Dan Gohman6c459a22008-06-22 19:56:46 +00002642 case Instruction::Or:
2643 // If the RHS of the Or is a constant, we may have something like:
2644 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2645 // optimizations will transparently handle this case.
2646 //
2647 // In order for this transformation to be safe, the LHS must be of the
2648 // form X*(2^n) and the Or constant must be less than 2^n.
2649 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002650 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002651 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002652 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002653 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002654 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002655 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002656 break;
2657 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002658 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002659 // If the RHS of the xor is a signbit, then this is just an add.
2660 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002661 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002662 return getAddExpr(getSCEV(U->getOperand(0)),
2663 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002664
2665 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002666 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002667 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002668
2669 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2670 // This is a variant of the check for xor with -1, and it handles
2671 // the case where instcombine has trimmed non-demanded bits out
2672 // of an xor with -1.
2673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2674 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2675 if (BO->getOpcode() == Instruction::And &&
2676 LCI->getValue() == CI->getValue())
2677 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002678 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002679 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002680 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002681 const Type *Z0Ty = Z0->getType();
2682 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2683
2684 // If C is a low-bits mask, the zero extend is zerving to
2685 // mask off the high bits. Complement the operand and
2686 // re-apply the zext.
2687 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2688 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2689
2690 // If C is a single bit, it may be in the sign-bit position
2691 // before the zero-extend. In this case, represent the xor
2692 // using an add, which is equivalent, and re-apply the zext.
2693 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2694 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2695 Trunc.isSignBit())
2696 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2697 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002698 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002699 }
2700 break;
2701
2702 case Instruction::Shl:
2703 // Turn shift left of a constant amount into a multiply.
2704 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2705 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2706 Constant *X = ConstantInt::get(
2707 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002708 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002709 }
2710 break;
2711
Nick Lewycky01eaf802008-07-07 06:15:49 +00002712 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002713 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002714 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2715 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2716 Constant *X = ConstantInt::get(
2717 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002718 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002719 }
2720 break;
2721
Dan Gohman4ee29af2009-04-21 02:26:00 +00002722 case Instruction::AShr:
2723 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2724 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2725 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2726 if (L->getOpcode() == Instruction::Shl &&
2727 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002728 unsigned BitWidth = getTypeSizeInBits(U->getType());
2729 uint64_t Amt = BitWidth - CI->getZExtValue();
2730 if (Amt == BitWidth)
2731 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2732 if (Amt > BitWidth)
2733 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002734 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002735 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002736 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002737 U->getType());
2738 }
2739 break;
2740
Dan Gohman6c459a22008-06-22 19:56:46 +00002741 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002742 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002743
2744 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002745 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002746
2747 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002748 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002749
2750 case Instruction::BitCast:
2751 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002752 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002753 return getSCEV(U->getOperand(0));
2754 break;
2755
Dan Gohman2d1be872009-04-16 03:18:22 +00002756 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002757 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002758 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002759 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002760
2761 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002762 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002763 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2764 U->getType());
2765
Dan Gohman26466c02009-05-08 20:26:55 +00002766 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002767 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002768 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002769
Dan Gohman6c459a22008-06-22 19:56:46 +00002770 case Instruction::PHI:
2771 return createNodeForPHI(cast<PHINode>(U));
2772
2773 case Instruction::Select:
2774 // This could be a smax or umax that was lowered earlier.
2775 // Try to recover it.
2776 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2777 Value *LHS = ICI->getOperand(0);
2778 Value *RHS = ICI->getOperand(1);
2779 switch (ICI->getPredicate()) {
2780 case ICmpInst::ICMP_SLT:
2781 case ICmpInst::ICMP_SLE:
2782 std::swap(LHS, RHS);
2783 // fall through
2784 case ICmpInst::ICMP_SGT:
2785 case ICmpInst::ICMP_SGE:
2786 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002787 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002788 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002789 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002790 break;
2791 case ICmpInst::ICMP_ULT:
2792 case ICmpInst::ICMP_ULE:
2793 std::swap(LHS, RHS);
2794 // fall through
2795 case ICmpInst::ICMP_UGT:
2796 case ICmpInst::ICMP_UGE:
2797 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002798 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002799 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002800 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002801 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002802 case ICmpInst::ICMP_NE:
2803 // n != 0 ? n : 1 -> umax(n, 1)
2804 if (LHS == U->getOperand(1) &&
2805 isa<ConstantInt>(U->getOperand(2)) &&
2806 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2807 isa<ConstantInt>(RHS) &&
2808 cast<ConstantInt>(RHS)->isZero())
2809 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2810 break;
2811 case ICmpInst::ICMP_EQ:
2812 // n == 0 ? 1 : n -> umax(n, 1)
2813 if (LHS == U->getOperand(2) &&
2814 isa<ConstantInt>(U->getOperand(1)) &&
2815 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2816 isa<ConstantInt>(RHS) &&
2817 cast<ConstantInt>(RHS)->isZero())
2818 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2819 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002820 default:
2821 break;
2822 }
2823 }
2824
2825 default: // We cannot analyze this expression.
2826 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002827 }
2828
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002829 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002830}
2831
2832
2833
2834//===----------------------------------------------------------------------===//
2835// Iteration Count Computation Code
2836//
2837
Dan Gohman46bdfb02009-02-24 18:55:53 +00002838/// getBackedgeTakenCount - If the specified loop has a predictable
2839/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2840/// object. The backedge-taken count is the number of times the loop header
2841/// will be branched to from within the loop. This is one less than the
2842/// trip count of the loop, since it doesn't count the first iteration,
2843/// when the header is branched to from outside the loop.
2844///
2845/// Note that it is not valid to call this method on a loop without a
2846/// loop-invariant backedge-taken count (see
2847/// hasLoopInvariantBackedgeTakenCount).
2848///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002849const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002850 return getBackedgeTakenInfo(L).Exact;
2851}
2852
2853/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2854/// return the least SCEV value that is known never to be less than the
2855/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002856const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002857 return getBackedgeTakenInfo(L).Max;
2858}
2859
Dan Gohman59ae6b92009-07-08 19:23:34 +00002860/// PushLoopPHIs - Push PHI nodes in the header of the given loop
2861/// onto the given Worklist.
2862static void
2863PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
2864 BasicBlock *Header = L->getHeader();
2865
2866 // Push all Loop-header PHIs onto the Worklist stack.
2867 for (BasicBlock::iterator I = Header->begin();
2868 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2869 Worklist.push_back(PN);
2870}
2871
2872/// PushDefUseChildren - Push users of the given Instruction
2873/// onto the given Worklist.
2874static void
2875PushDefUseChildren(Instruction *I,
2876 SmallVectorImpl<Instruction *> &Worklist) {
2877 // Push the def-use children onto the Worklist stack.
2878 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2879 UI != UE; ++UI)
2880 Worklist.push_back(cast<Instruction>(UI));
2881}
2882
Dan Gohmana1af7572009-04-30 20:47:05 +00002883const ScalarEvolution::BackedgeTakenInfo &
2884ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002885 // Initially insert a CouldNotCompute for this loop. If the insertion
2886 // succeeds, procede to actually compute a backedge-taken count and
2887 // update the value. The temporary CouldNotCompute value tells SCEV
2888 // code elsewhere that it shouldn't attempt to request a new
2889 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002890 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002891 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2892 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002893 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00002894 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002895 assert(ItCount.Exact->isLoopInvariant(L) &&
2896 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002897 "Computed trip count isn't loop invariant for loop!");
2898 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002899
Dan Gohman01ecca22009-04-27 20:16:15 +00002900 // Update the value in the map.
2901 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00002902 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00002903 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00002904 // Update the value in the map.
2905 Pair.first->second = ItCount;
2906 if (isa<PHINode>(L->getHeader()->begin()))
2907 // Only count loops that have phi nodes as not being computable.
2908 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00002909 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002910
2911 // Now that we know more about the trip count for this loop, forget any
2912 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00002913 // conservative estimates made without the benefit of trip count
2914 // information. This is similar to the code in
2915 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
2916 // nodes specially.
2917 if (ItCount.hasAnyInfo()) {
2918 SmallVector<Instruction *, 16> Worklist;
2919 PushLoopPHIs(L, Worklist);
2920
2921 SmallPtrSet<Instruction *, 8> Visited;
2922 while (!Worklist.empty()) {
2923 Instruction *I = Worklist.pop_back_val();
2924 if (!Visited.insert(I)) continue;
2925
2926 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2927 Scalars.find(static_cast<Value *>(I));
2928 if (It != Scalars.end()) {
2929 // SCEVUnknown for a PHI either means that it has an unrecognized
2930 // structure, or it's a PHI that's in the progress of being computed
2931 // by createNodeForPHI. In the former case, additional loop trip count
2932 // information isn't going to change anything. In the later case,
2933 // createNodeForPHI will perform the necessary updates on its own when
2934 // it gets to that point.
2935 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2936 Scalars.erase(It);
2937 ValuesAtScopes.erase(I);
2938 if (PHINode *PN = dyn_cast<PHINode>(I))
2939 ConstantEvolutionLoopExitValue.erase(PN);
2940 }
2941
2942 PushDefUseChildren(I, Worklist);
2943 }
2944 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002945 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002946 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002947}
2948
Dan Gohman46bdfb02009-02-24 18:55:53 +00002949/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002950/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002951/// ScalarEvolution's ability to compute a trip count, or if the loop
2952/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002953void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002954 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002955
Dan Gohman35738ac2009-05-04 22:30:44 +00002956 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00002957 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00002958
Dan Gohman59ae6b92009-07-08 19:23:34 +00002959 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00002960 while (!Worklist.empty()) {
2961 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00002962 if (!Visited.insert(I)) continue;
2963
2964 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2965 Scalars.find(static_cast<Value *>(I));
2966 if (It != Scalars.end()) {
2967 Scalars.erase(It);
2968 ValuesAtScopes.erase(I);
2969 if (PHINode *PN = dyn_cast<PHINode>(I))
2970 ConstantEvolutionLoopExitValue.erase(PN);
2971 }
2972
2973 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00002974 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002975}
2976
Dan Gohman46bdfb02009-02-24 18:55:53 +00002977/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2978/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002979ScalarEvolution::BackedgeTakenInfo
2980ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002981 SmallVector<BasicBlock*, 8> ExitingBlocks;
2982 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00002983
Dan Gohmana334aa72009-06-22 00:31:57 +00002984 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002985 const SCEV *BECount = getCouldNotCompute();
2986 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00002987 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00002988 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2989 BackedgeTakenInfo NewBTI =
2990 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00002991
Dan Gohman1c343752009-06-27 21:21:31 +00002992 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002993 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002994 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002995 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00002996 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00002997 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00002998 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00002999 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003000 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003001 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003002 }
Dan Gohman1c343752009-06-27 21:21:31 +00003003 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003004 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003005 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003006 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003007 }
3008
3009 return BackedgeTakenInfo(BECount, MaxBECount);
3010}
3011
3012/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3013/// of the specified loop will execute if it exits via the specified block.
3014ScalarEvolution::BackedgeTakenInfo
3015ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3016 BasicBlock *ExitingBlock) {
3017
3018 // Okay, we've chosen an exiting block. See what condition causes us to
3019 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003020 //
3021 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003022 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003023 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003024 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003025
Chris Lattner8b0e3602007-01-07 02:24:26 +00003026 // At this point, we know we have a conditional branch that determines whether
3027 // the loop is exited. However, we don't know if the branch is executed each
3028 // time through the loop. If not, then the execution count of the branch will
3029 // not be equal to the trip count of the loop.
3030 //
3031 // Currently we check for this by checking to see if the Exit branch goes to
3032 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003033 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003034 // loop header. This is common for un-rotated loops.
3035 //
3036 // If both of those tests fail, walk up the unique predecessor chain to the
3037 // header, stopping if there is an edge that doesn't exit the loop. If the
3038 // header is reached, the execution count of the branch will be equal to the
3039 // trip count of the loop.
3040 //
3041 // More extensive analysis could be done to handle more cases here.
3042 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003043 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003044 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003045 ExitBr->getParent() != L->getHeader()) {
3046 // The simple checks failed, try climbing the unique predecessor chain
3047 // up to the header.
3048 bool Ok = false;
3049 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3050 BasicBlock *Pred = BB->getUniquePredecessor();
3051 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003052 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003053 TerminatorInst *PredTerm = Pred->getTerminator();
3054 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3055 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3056 if (PredSucc == BB)
3057 continue;
3058 // If the predecessor has a successor that isn't BB and isn't
3059 // outside the loop, assume the worst.
3060 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003061 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003062 }
3063 if (Pred == L->getHeader()) {
3064 Ok = true;
3065 break;
3066 }
3067 BB = Pred;
3068 }
3069 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003070 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003071 }
3072
3073 // Procede to the next level to examine the exit condition expression.
3074 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3075 ExitBr->getSuccessor(0),
3076 ExitBr->getSuccessor(1));
3077}
3078
3079/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3080/// backedge of the specified loop will execute if its exit condition
3081/// were a conditional branch of ExitCond, TBB, and FBB.
3082ScalarEvolution::BackedgeTakenInfo
3083ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3084 Value *ExitCond,
3085 BasicBlock *TBB,
3086 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003087 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3089 if (BO->getOpcode() == Instruction::And) {
3090 // Recurse on the operands of the and.
3091 BackedgeTakenInfo BTI0 =
3092 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3093 BackedgeTakenInfo BTI1 =
3094 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003095 const SCEV *BECount = getCouldNotCompute();
3096 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003097 if (L->contains(TBB)) {
3098 // Both conditions must be true for the loop to continue executing.
3099 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003100 if (BTI0.Exact == getCouldNotCompute() ||
3101 BTI1.Exact == getCouldNotCompute())
3102 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003103 else
3104 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003105 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003106 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003107 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003108 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003109 else
3110 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003111 } else {
3112 // Both conditions must be true for the loop to exit.
3113 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003114 if (BTI0.Exact != getCouldNotCompute() &&
3115 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003116 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003117 if (BTI0.Max != getCouldNotCompute() &&
3118 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003119 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3120 }
3121
3122 return BackedgeTakenInfo(BECount, MaxBECount);
3123 }
3124 if (BO->getOpcode() == Instruction::Or) {
3125 // Recurse on the operands of the or.
3126 BackedgeTakenInfo BTI0 =
3127 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3128 BackedgeTakenInfo BTI1 =
3129 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003130 const SCEV *BECount = getCouldNotCompute();
3131 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003132 if (L->contains(FBB)) {
3133 // Both conditions must be false for the loop to continue executing.
3134 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003135 if (BTI0.Exact == getCouldNotCompute() ||
3136 BTI1.Exact == getCouldNotCompute())
3137 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003138 else
3139 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003140 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003141 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003142 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003143 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003144 else
3145 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003146 } else {
3147 // Both conditions must be false for the loop to exit.
3148 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003149 if (BTI0.Exact != getCouldNotCompute() &&
3150 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003151 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003152 if (BTI0.Max != getCouldNotCompute() &&
3153 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003154 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3155 }
3156
3157 return BackedgeTakenInfo(BECount, MaxBECount);
3158 }
3159 }
3160
3161 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3162 // Procede to the next level to examine the icmp.
3163 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3164 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003165
Eli Friedman361e54d2009-05-09 12:32:42 +00003166 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003167 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3168}
3169
3170/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3171/// backedge of the specified loop will execute if its exit condition
3172/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3173ScalarEvolution::BackedgeTakenInfo
3174ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3175 ICmpInst *ExitCond,
3176 BasicBlock *TBB,
3177 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003178
Reid Spencere4d87aa2006-12-23 06:05:41 +00003179 // If the condition was exit on true, convert the condition to exit on false
3180 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003181 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003182 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003183 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003184 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003185
3186 // Handle common loops like: for (X = "string"; *X; ++X)
3187 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3188 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003189 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003190 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003191 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3192 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3193 return BackedgeTakenInfo(ItCnt,
3194 isa<SCEVConstant>(ItCnt) ? ItCnt :
3195 getConstant(APInt::getMaxValue(BitWidth)-1));
3196 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003197 }
3198
Dan Gohman0bba49c2009-07-07 17:06:11 +00003199 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3200 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003201
3202 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003203 LHS = getSCEVAtScope(LHS, L);
3204 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003205
Dan Gohman64a845e2009-06-24 04:48:43 +00003206 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003207 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003208 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3209 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003210 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003211 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003212 }
3213
Chris Lattner53e677a2004-04-02 20:23:17 +00003214 // If we have a comparison of a chrec against a constant, try to use value
3215 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003216 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3217 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003218 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003219 // Form the constant range.
3220 ConstantRange CompRange(
3221 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003222
Dan Gohman0bba49c2009-07-07 17:06:11 +00003223 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003224 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003225 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003226
Chris Lattner53e677a2004-04-02 20:23:17 +00003227 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003228 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003229 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003230 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003231 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003232 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003233 }
3234 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003235 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003236 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003237 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003238 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003239 }
3240 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003241 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3242 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003243 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003244 }
3245 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003246 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3247 getNotSCEV(RHS), L, true);
3248 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003249 break;
3250 }
3251 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003252 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3253 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003254 break;
3255 }
3256 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003257 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3258 getNotSCEV(RHS), L, false);
3259 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003260 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003261 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003262 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003263#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003264 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003265 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003266 errs() << "[unsigned] ";
3267 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003268 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003269 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003270#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003271 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003272 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003273 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003274 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003275}
3276
Chris Lattner673e02b2004-10-12 01:49:27 +00003277static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003278EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3279 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003280 const SCEV *InVal = SE.getConstant(C);
3281 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003282 assert(isa<SCEVConstant>(Val) &&
3283 "Evaluation of SCEV at constant didn't fold correctly?");
3284 return cast<SCEVConstant>(Val)->getValue();
3285}
3286
3287/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3288/// and a GEP expression (missing the pointer index) indexing into it, return
3289/// the addressed element of the initializer or null if the index expression is
3290/// invalid.
3291static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003292GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003293 const std::vector<ConstantInt*> &Indices) {
3294 Constant *Init = GV->getInitializer();
3295 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003296 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003297 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3298 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3299 Init = cast<Constant>(CS->getOperand(Idx));
3300 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3301 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3302 Init = cast<Constant>(CA->getOperand(Idx));
3303 } else if (isa<ConstantAggregateZero>(Init)) {
3304 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3305 assert(Idx < STy->getNumElements() && "Bad struct index!");
3306 Init = Constant::getNullValue(STy->getElementType(Idx));
3307 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3308 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3309 Init = Constant::getNullValue(ATy->getElementType());
3310 } else {
3311 assert(0 && "Unknown constant aggregate type!");
3312 }
3313 return 0;
3314 } else {
3315 return 0; // Unknown initializer type
3316 }
3317 }
3318 return Init;
3319}
3320
Dan Gohman46bdfb02009-02-24 18:55:53 +00003321/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3322/// 'icmp op load X, cst', try to see if we can compute the backedge
3323/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003324const SCEV *
3325ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3326 LoadInst *LI,
3327 Constant *RHS,
3328 const Loop *L,
3329 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003330 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003331
3332 // Check to see if the loaded pointer is a getelementptr of a global.
3333 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003334 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003335
3336 // Make sure that it is really a constant global we are gepping, with an
3337 // initializer, and make sure the first IDX is really 0.
3338 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3339 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3340 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3341 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003342 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003343
3344 // Okay, we allow one non-constant index into the GEP instruction.
3345 Value *VarIdx = 0;
3346 std::vector<ConstantInt*> Indexes;
3347 unsigned VarIdxNum = 0;
3348 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3349 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3350 Indexes.push_back(CI);
3351 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003352 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003353 VarIdx = GEP->getOperand(i);
3354 VarIdxNum = i-2;
3355 Indexes.push_back(0);
3356 }
3357
3358 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3359 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003360 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003361 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003362
3363 // We can only recognize very limited forms of loop index expressions, in
3364 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003365 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003366 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3367 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3368 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003369 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003370
3371 unsigned MaxSteps = MaxBruteForceIterations;
3372 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003373 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003374 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003375 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003376
3377 // Form the GEP offset.
3378 Indexes[VarIdxNum] = Val;
3379
3380 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3381 if (Result == 0) break; // Cannot compute!
3382
3383 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003385 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003386 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003387#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003388 errs() << "\n***\n*** Computed loop count " << *ItCst
3389 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3390 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003391#endif
3392 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003393 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003394 }
3395 }
Dan Gohman1c343752009-06-27 21:21:31 +00003396 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003397}
3398
3399
Chris Lattner3221ad02004-04-17 22:58:41 +00003400/// CanConstantFold - Return true if we can constant fold an instruction of the
3401/// specified type, assuming that all operands were constants.
3402static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003403 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003404 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3405 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003406
Chris Lattner3221ad02004-04-17 22:58:41 +00003407 if (const CallInst *CI = dyn_cast<CallInst>(I))
3408 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003409 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003410 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003411}
3412
Chris Lattner3221ad02004-04-17 22:58:41 +00003413/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3414/// in the loop that V is derived from. We allow arbitrary operations along the
3415/// way, but the operands of an operation must either be constants or a value
3416/// derived from a constant PHI. If this expression does not fit with these
3417/// constraints, return null.
3418static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3419 // If this is not an instruction, or if this is an instruction outside of the
3420 // loop, it can't be derived from a loop PHI.
3421 Instruction *I = dyn_cast<Instruction>(V);
3422 if (I == 0 || !L->contains(I->getParent())) return 0;
3423
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003424 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003425 if (L->getHeader() == I->getParent())
3426 return PN;
3427 else
3428 // We don't currently keep track of the control flow needed to evaluate
3429 // PHIs, so we cannot handle PHIs inside of loops.
3430 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003431 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003432
3433 // If we won't be able to constant fold this expression even if the operands
3434 // are constants, return early.
3435 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003436
Chris Lattner3221ad02004-04-17 22:58:41 +00003437 // Otherwise, we can evaluate this instruction if all of its operands are
3438 // constant or derived from a PHI node themselves.
3439 PHINode *PHI = 0;
3440 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3441 if (!(isa<Constant>(I->getOperand(Op)) ||
3442 isa<GlobalValue>(I->getOperand(Op)))) {
3443 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3444 if (P == 0) return 0; // Not evolving from PHI
3445 if (PHI == 0)
3446 PHI = P;
3447 else if (PHI != P)
3448 return 0; // Evolving from multiple different PHIs.
3449 }
3450
3451 // This is a expression evolving from a constant PHI!
3452 return PHI;
3453}
3454
3455/// EvaluateExpression - Given an expression that passes the
3456/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3457/// in the loop has the value PHIVal. If we can't fold this expression for some
3458/// reason, return null.
3459static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3460 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003461 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003462 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003463 Instruction *I = cast<Instruction>(V);
Owen Anderson07cf79e2009-07-06 23:00:19 +00003464 LLVMContext *Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003465
3466 std::vector<Constant*> Operands;
3467 Operands.resize(I->getNumOperands());
3468
3469 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3470 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3471 if (Operands[i] == 0) return 0;
3472 }
3473
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003474 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3475 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003476 &Operands[0], Operands.size(),
3477 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003478 else
3479 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003480 &Operands[0], Operands.size(),
3481 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003482}
3483
3484/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3485/// in the header of its containing loop, we know the loop executes a
3486/// constant number of times, and the PHI node is just a recurrence
3487/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003488Constant *
3489ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3490 const APInt& BEs,
3491 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003492 std::map<PHINode*, Constant*>::iterator I =
3493 ConstantEvolutionLoopExitValue.find(PN);
3494 if (I != ConstantEvolutionLoopExitValue.end())
3495 return I->second;
3496
Dan Gohman46bdfb02009-02-24 18:55:53 +00003497 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003498 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3499
3500 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3501
3502 // Since the loop is canonicalized, the PHI node must have two entries. One
3503 // entry must be a constant (coming in from outside of the loop), and the
3504 // second must be derived from the same PHI.
3505 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3506 Constant *StartCST =
3507 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3508 if (StartCST == 0)
3509 return RetVal = 0; // Must be a constant.
3510
3511 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3512 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3513 if (PN2 != PN)
3514 return RetVal = 0; // Not derived from same PHI.
3515
3516 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003517 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003518 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003519
Dan Gohman46bdfb02009-02-24 18:55:53 +00003520 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003521 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003522 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3523 if (IterationNum == NumIterations)
3524 return RetVal = PHIVal; // Got exit value!
3525
3526 // Compute the value of the PHI node for the next iteration.
3527 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3528 if (NextPHI == PHIVal)
3529 return RetVal = NextPHI; // Stopped evolving!
3530 if (NextPHI == 0)
3531 return 0; // Couldn't evaluate!
3532 PHIVal = NextPHI;
3533 }
3534}
3535
Dan Gohman46bdfb02009-02-24 18:55:53 +00003536/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003537/// constant number of times (the condition evolves only from constants),
3538/// try to evaluate a few iterations of the loop until we get the exit
3539/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003540/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003541const SCEV *
3542ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3543 Value *Cond,
3544 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003545 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003546 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003547
3548 // Since the loop is canonicalized, the PHI node must have two entries. One
3549 // entry must be a constant (coming in from outside of the loop), and the
3550 // second must be derived from the same PHI.
3551 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3552 Constant *StartCST =
3553 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003554 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003555
3556 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3557 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003558 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003559
3560 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3561 // the loop symbolically to determine when the condition gets a value of
3562 // "ExitWhen".
3563 unsigned IterationNum = 0;
3564 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3565 for (Constant *PHIVal = StartCST;
3566 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003567 ConstantInt *CondVal =
3568 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003569
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003570 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003571 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003572
Reid Spencere8019bb2007-03-01 07:25:48 +00003573 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003574 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003575 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003576 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003577
Chris Lattner3221ad02004-04-17 22:58:41 +00003578 // Compute the value of the PHI node for the next iteration.
3579 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3580 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003581 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003582 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003583 }
3584
3585 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003586 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003587}
3588
Dan Gohman66a7e852009-05-08 20:38:54 +00003589/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3590/// at the specified scope in the program. The L value specifies a loop
3591/// nest to evaluate the expression at, where null is the top-level or a
3592/// specified loop is immediately inside of the loop.
3593///
3594/// This method can be used to compute the exit value for a variable defined
3595/// in a loop by querying what the value will hold in the parent loop.
3596///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003597/// In the case that a relevant loop exit value cannot be computed, the
3598/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003599const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003600 // FIXME: this should be turned into a virtual method on SCEV!
3601
Chris Lattner3221ad02004-04-17 22:58:41 +00003602 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003603
Nick Lewycky3e630762008-02-20 06:48:22 +00003604 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003605 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003606 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003607 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003608 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003609 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3610 if (PHINode *PN = dyn_cast<PHINode>(I))
3611 if (PN->getParent() == LI->getHeader()) {
3612 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003613 // to see if the loop that contains it has a known backedge-taken
3614 // count. If so, we may be able to force computation of the exit
3615 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003616 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003617 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003618 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003619 // Okay, we know how many times the containing loop executes. If
3620 // this is a constant evolving PHI node, get the final value at
3621 // the specified iteration number.
3622 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003623 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003624 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003625 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003626 }
3627 }
3628
Reid Spencer09906f32006-12-04 21:33:23 +00003629 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003630 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003631 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003632 // result. This is particularly useful for computing loop exit values.
3633 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003634 // Check to see if we've folded this instruction at this loop before.
3635 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3636 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3637 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3638 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003639 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003640
Chris Lattner3221ad02004-04-17 22:58:41 +00003641 std::vector<Constant*> Operands;
3642 Operands.reserve(I->getNumOperands());
3643 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3644 Value *Op = I->getOperand(i);
3645 if (Constant *C = dyn_cast<Constant>(Op)) {
3646 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003647 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003648 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003649 // non-integer and non-pointer, don't even try to analyze them
3650 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003651 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003652 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003653
Dan Gohman0bba49c2009-07-07 17:06:11 +00003654 const SCEV *OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00003655 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003656 Constant *C = SC->getValue();
3657 if (C->getType() != Op->getType())
3658 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3659 Op->getType(),
3660 false),
3661 C, Op->getType());
3662 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003663 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003664 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3665 if (C->getType() != Op->getType())
3666 C =
3667 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3668 Op->getType(),
3669 false),
3670 C, Op->getType());
3671 Operands.push_back(C);
3672 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003673 return V;
3674 } else {
3675 return V;
3676 }
3677 }
3678 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003679
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003680 Constant *C;
3681 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3682 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003683 &Operands[0], Operands.size(),
3684 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003685 else
3686 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003687 &Operands[0], Operands.size(), Context);
Dan Gohman6bce6432009-05-08 20:47:27 +00003688 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003689 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003690 }
3691 }
3692
3693 // This is some other type of SCEVUnknown, just return it.
3694 return V;
3695 }
3696
Dan Gohman622ed672009-05-04 22:02:23 +00003697 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003698 // Avoid performing the look-up in the common case where the specified
3699 // expression has no loop-variant portions.
3700 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003701 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003702 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003703 // Okay, at least one of these operands is loop variant but might be
3704 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00003705 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3706 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003707 NewOps.push_back(OpAtScope);
3708
3709 for (++i; i != e; ++i) {
3710 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003711 NewOps.push_back(OpAtScope);
3712 }
3713 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003714 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003715 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003716 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003717 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003718 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003719 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003720 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003721 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003722 }
3723 }
3724 // If we got here, all operands are loop invariant.
3725 return Comm;
3726 }
3727
Dan Gohman622ed672009-05-04 22:02:23 +00003728 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003729 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3730 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003731 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3732 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003733 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003734 }
3735
3736 // If this is a loop recurrence for a loop that does not contain L, then we
3737 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003738 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003739 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3740 // To evaluate this recurrence, we need to know how many times the AddRec
3741 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003742 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00003743 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003744
Eli Friedmanb42a6262008-08-04 23:49:06 +00003745 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003746 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003747 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003748 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003749 }
3750
Dan Gohman622ed672009-05-04 22:02:23 +00003751 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003752 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003753 if (Op == Cast->getOperand())
3754 return Cast; // must be loop invariant
3755 return getZeroExtendExpr(Op, Cast->getType());
3756 }
3757
Dan Gohman622ed672009-05-04 22:02:23 +00003758 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003759 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003760 if (Op == Cast->getOperand())
3761 return Cast; // must be loop invariant
3762 return getSignExtendExpr(Op, Cast->getType());
3763 }
3764
Dan Gohman622ed672009-05-04 22:02:23 +00003765 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003766 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003767 if (Op == Cast->getOperand())
3768 return Cast; // must be loop invariant
3769 return getTruncateExpr(Op, Cast->getType());
3770 }
3771
3772 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003773 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003774}
3775
Dan Gohman66a7e852009-05-08 20:38:54 +00003776/// getSCEVAtScope - This is a convenience function which does
3777/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00003778const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003779 return getSCEVAtScope(getSCEV(V), L);
3780}
3781
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003782/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3783/// following equation:
3784///
3785/// A * X = B (mod N)
3786///
3787/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3788/// A and B isn't important.
3789///
3790/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003791static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003792 ScalarEvolution &SE) {
3793 uint32_t BW = A.getBitWidth();
3794 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3795 assert(A != 0 && "A must be non-zero.");
3796
3797 // 1. D = gcd(A, N)
3798 //
3799 // The gcd of A and N may have only one prime factor: 2. The number of
3800 // trailing zeros in A is its multiplicity
3801 uint32_t Mult2 = A.countTrailingZeros();
3802 // D = 2^Mult2
3803
3804 // 2. Check if B is divisible by D.
3805 //
3806 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3807 // is not less than multiplicity of this prime factor for D.
3808 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003809 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003810
3811 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3812 // modulo (N / D).
3813 //
3814 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3815 // bit width during computations.
3816 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3817 APInt Mod(BW + 1, 0);
3818 Mod.set(BW - Mult2); // Mod = N / D
3819 APInt I = AD.multiplicativeInverse(Mod);
3820
3821 // 4. Compute the minimum unsigned root of the equation:
3822 // I * (B / D) mod (N / D)
3823 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3824
3825 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3826 // bits.
3827 return SE.getConstant(Result.trunc(BW));
3828}
Chris Lattner53e677a2004-04-02 20:23:17 +00003829
3830/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3831/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3832/// might be the same) or two SCEVCouldNotCompute objects.
3833///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003834static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00003835SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003836 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003837 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3838 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3839 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003840
Chris Lattner53e677a2004-04-02 20:23:17 +00003841 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003842 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003843 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003844 return std::make_pair(CNC, CNC);
3845 }
3846
Reid Spencere8019bb2007-03-01 07:25:48 +00003847 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003848 const APInt &L = LC->getValue()->getValue();
3849 const APInt &M = MC->getValue()->getValue();
3850 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003851 APInt Two(BitWidth, 2);
3852 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003853
Dan Gohman64a845e2009-06-24 04:48:43 +00003854 {
Reid Spencere8019bb2007-03-01 07:25:48 +00003855 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003856 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003857 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3858 // The B coefficient is M-N/2
3859 APInt B(M);
3860 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003861
Reid Spencere8019bb2007-03-01 07:25:48 +00003862 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003863 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003864
Reid Spencere8019bb2007-03-01 07:25:48 +00003865 // Compute the B^2-4ac term.
3866 APInt SqrtTerm(B);
3867 SqrtTerm *= B;
3868 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003869
Reid Spencere8019bb2007-03-01 07:25:48 +00003870 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3871 // integer value or else APInt::sqrt() will assert.
3872 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003873
Dan Gohman64a845e2009-06-24 04:48:43 +00003874 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00003875 // The divisions must be performed as signed divisions.
3876 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003877 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003878 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003879 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003880 return std::make_pair(CNC, CNC);
3881 }
3882
Owen Anderson76f600b2009-07-06 22:37:39 +00003883 LLVMContext *Context = SE.getContext();
3884
3885 ConstantInt *Solution1 =
3886 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
3887 ConstantInt *Solution2 =
3888 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003889
Dan Gohman64a845e2009-06-24 04:48:43 +00003890 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00003891 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003892 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003893}
3894
3895/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003896/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003897const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003898 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003899 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003900 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003901 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00003902 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003903 }
3904
Dan Gohman35738ac2009-05-04 22:30:44 +00003905 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003906 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00003907 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003908
3909 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003910 // If this is an affine expression, the execution count of this branch is
3911 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003912 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003913 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003914 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003915 // equivalent to:
3916 //
3917 // Step*N = -Start (mod 2^BW)
3918 //
3919 // where BW is the common bit width of Start and Step.
3920
Chris Lattner53e677a2004-04-02 20:23:17 +00003921 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00003922 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3923 L->getParentLoop());
3924 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3925 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003926
Dan Gohman622ed672009-05-04 22:02:23 +00003927 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003928 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003929
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003930 // First, handle unitary steps.
3931 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003932 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003933 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3934 return Start; // N = Start (as unsigned)
3935
3936 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003937 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003938 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003939 -StartC->getValue()->getValue(),
3940 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003941 }
Chris Lattner42a75512007-01-15 02:27:26 +00003942 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003943 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3944 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003945 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003946 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003947 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3948 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003949 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003950#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003951 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3952 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003953#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003954 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003955 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00003956 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003957 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003958 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003959 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003960
Chris Lattner53e677a2004-04-02 20:23:17 +00003961 // We can only use this value if the chrec ends up with an exact zero
3962 // value at this index. When solving for "X*X != 5", for example, we
3963 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003964 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003965 if (Val->isZero())
3966 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003967 }
3968 }
3969 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003970
Dan Gohman1c343752009-06-27 21:21:31 +00003971 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003972}
3973
3974/// HowFarToNonZero - Return the number of times a backedge checking the
3975/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003976/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00003977const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003978 // Loops that look like: while (X == 0) are very strange indeed. We don't
3979 // handle them yet except for the trivial case. This could be expanded in the
3980 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003981
Chris Lattner53e677a2004-04-02 20:23:17 +00003982 // If the value is a constant, check to see if it is known to be non-zero
3983 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003984 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003985 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003986 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00003987 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003988 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003989
Chris Lattner53e677a2004-04-02 20:23:17 +00003990 // We could implement others, but I really doubt anyone writes loops like
3991 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00003992 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003993}
3994
Dan Gohman859b4822009-05-18 15:36:09 +00003995/// getLoopPredecessor - If the given loop's header has exactly one unique
3996/// predecessor outside the loop, return it. Otherwise return null.
3997///
3998BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3999 BasicBlock *Header = L->getHeader();
4000 BasicBlock *Pred = 0;
4001 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4002 PI != E; ++PI)
4003 if (!L->contains(*PI)) {
4004 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4005 Pred = *PI;
4006 }
4007 return Pred;
4008}
4009
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004010/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4011/// (which may not be an immediate predecessor) which has exactly one
4012/// successor from which BB is reachable, or null if no such block is
4013/// found.
4014///
4015BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004016ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004017 // If the block has a unique predecessor, then there is no path from the
4018 // predecessor to the block that does not go through the direct edge
4019 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004020 if (BasicBlock *Pred = BB->getSinglePredecessor())
4021 return Pred;
4022
4023 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004024 // If the header has a unique predecessor outside the loop, it must be
4025 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004026 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004027 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004028
4029 return 0;
4030}
4031
Dan Gohman763bad12009-06-20 00:35:32 +00004032/// HasSameValue - SCEV structural equivalence is usually sufficient for
4033/// testing whether two expressions are equal, however for the purposes of
4034/// looking for a condition guarding a loop, it can be useful to be a little
4035/// more general, since a front-end may have replicated the controlling
4036/// expression.
4037///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004038static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004039 // Quick check to see if they are the same SCEV.
4040 if (A == B) return true;
4041
4042 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4043 // two different instructions with the same value. Check for this case.
4044 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4045 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4046 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4047 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4048 if (AI->isIdenticalTo(BI))
4049 return true;
4050
4051 // Otherwise assume they may have a different value.
4052 return false;
4053}
4054
Dan Gohmanc2390b12009-02-12 22:19:27 +00004055/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00004056/// a conditional between LHS and RHS. This is used to help avoid max
4057/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004058bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00004059 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00004060 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004061 // Interpret a null as meaning no loop, where there is obviously no guard
4062 // (interprocedural conditions notwithstanding).
4063 if (!L) return false;
4064
Dan Gohman859b4822009-05-18 15:36:09 +00004065 BasicBlock *Predecessor = getLoopPredecessor(L);
4066 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004067
Dan Gohman859b4822009-05-18 15:36:09 +00004068 // Starting at the loop predecessor, climb up the predecessor chain, as long
4069 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004070 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004071 for (; Predecessor;
4072 PredecessorDest = Predecessor,
4073 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004074
4075 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004076 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004077 if (!LoopEntryPredicate ||
4078 LoopEntryPredicate->isUnconditional())
4079 continue;
4080
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004081 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4082 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004083 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004084 }
4085
Dan Gohman38372182008-08-12 20:17:31 +00004086 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004087}
4088
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004089/// isNecessaryCond - Test whether the given CondValue value is a condition
4090/// which is at least as strict as the one described by Pred, LHS, and RHS.
4091bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4092 ICmpInst::Predicate Pred,
4093 const SCEV *LHS, const SCEV *RHS,
4094 bool Inverse) {
4095 // Recursivly handle And and Or conditions.
4096 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4097 if (BO->getOpcode() == Instruction::And) {
4098 if (!Inverse)
4099 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4100 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4101 } else if (BO->getOpcode() == Instruction::Or) {
4102 if (Inverse)
4103 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4104 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4105 }
4106 }
4107
4108 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4109 if (!ICI) return false;
4110
4111 // Now that we found a conditional branch that dominates the loop, check to
4112 // see if it is the comparison we are looking for.
4113 Value *PreCondLHS = ICI->getOperand(0);
4114 Value *PreCondRHS = ICI->getOperand(1);
4115 ICmpInst::Predicate Cond;
4116 if (Inverse)
4117 Cond = ICI->getInversePredicate();
4118 else
4119 Cond = ICI->getPredicate();
4120
4121 if (Cond == Pred)
4122 ; // An exact match.
4123 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4124 ; // The actual condition is beyond sufficient.
4125 else
4126 // Check a few special cases.
4127 switch (Cond) {
4128 case ICmpInst::ICMP_UGT:
4129 if (Pred == ICmpInst::ICMP_ULT) {
4130 std::swap(PreCondLHS, PreCondRHS);
4131 Cond = ICmpInst::ICMP_ULT;
4132 break;
4133 }
4134 return false;
4135 case ICmpInst::ICMP_SGT:
4136 if (Pred == ICmpInst::ICMP_SLT) {
4137 std::swap(PreCondLHS, PreCondRHS);
4138 Cond = ICmpInst::ICMP_SLT;
4139 break;
4140 }
4141 return false;
4142 case ICmpInst::ICMP_NE:
4143 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4144 // so check for this case by checking if the NE is comparing against
4145 // a minimum or maximum constant.
4146 if (!ICmpInst::isTrueWhenEqual(Pred))
4147 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4148 const APInt &A = CI->getValue();
4149 switch (Pred) {
4150 case ICmpInst::ICMP_SLT:
4151 if (A.isMaxSignedValue()) break;
4152 return false;
4153 case ICmpInst::ICMP_SGT:
4154 if (A.isMinSignedValue()) break;
4155 return false;
4156 case ICmpInst::ICMP_ULT:
4157 if (A.isMaxValue()) break;
4158 return false;
4159 case ICmpInst::ICMP_UGT:
4160 if (A.isMinValue()) break;
4161 return false;
4162 default:
4163 return false;
4164 }
4165 Cond = ICmpInst::ICMP_NE;
4166 // NE is symmetric but the original comparison may not be. Swap
4167 // the operands if necessary so that they match below.
4168 if (isa<SCEVConstant>(LHS))
4169 std::swap(PreCondLHS, PreCondRHS);
4170 break;
4171 }
4172 return false;
4173 default:
4174 // We weren't able to reconcile the condition.
4175 return false;
4176 }
4177
4178 if (!PreCondLHS->getType()->isInteger()) return false;
4179
4180 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4181 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4182 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4183 HasSameValue(RHS, PreCondRHSSCEV)) ||
4184 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4185 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4186}
4187
Dan Gohman51f53b72009-06-21 23:46:38 +00004188/// getBECount - Subtract the end and start values and divide by the step,
4189/// rounding up, to get the number of times the backedge is executed. Return
4190/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004191const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4192 const SCEV *End,
4193 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004194 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004195 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4196 const SCEV *Diff = getMinusSCEV(End, Start);
4197 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004198
4199 // Add an adjustment to the difference between End and Start so that
4200 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004201 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004202
4203 // Check Add for unsigned overflow.
4204 // TODO: More sophisticated things could be done here.
Owen Anderson76f600b2009-07-06 22:37:39 +00004205 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004206 const SCEV *OperandExtendedAdd =
Dan Gohman51f53b72009-06-21 23:46:38 +00004207 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4208 getZeroExtendExpr(RoundUp, WideTy));
4209 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004210 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004211
4212 return getUDivExpr(Add, Step);
4213}
4214
Chris Lattnerdb25de42005-08-15 23:33:51 +00004215/// HowManyLessThans - Return the number of times a backedge containing the
4216/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004217/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004218ScalarEvolution::BackedgeTakenInfo
4219ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4220 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004221 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004222 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004223
Dan Gohman35738ac2009-05-04 22:30:44 +00004224 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004225 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004226 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004227
4228 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004229 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004230 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004231 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004232
4233 // TODO: handle non-constant strides.
4234 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4235 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004236 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004237 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004238 // With unit stride, the iteration never steps past the limit value.
4239 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4240 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4241 // Test whether a positive iteration iteration can step past the limit
4242 // value and past the maximum value for its type in a single step.
4243 if (isSigned) {
4244 APInt Max = APInt::getSignedMaxValue(BitWidth);
4245 if ((Max - CStep->getValue()->getValue())
4246 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004247 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004248 } else {
4249 APInt Max = APInt::getMaxValue(BitWidth);
4250 if ((Max - CStep->getValue()->getValue())
4251 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004252 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004253 }
4254 } else
4255 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004256 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004257 } else
4258 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004259 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004260
Dan Gohmana1af7572009-04-30 20:47:05 +00004261 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4262 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4263 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004264 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004265
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004266 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004267 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004268
Dan Gohmana1af7572009-04-30 20:47:05 +00004269 // Determine the minimum constant start value.
Dan Gohman64a845e2009-06-24 04:48:43 +00004270 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmana1af7572009-04-30 20:47:05 +00004271 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4272 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004273
Dan Gohmana1af7572009-04-30 20:47:05 +00004274 // If we know that the condition is true in order to enter the loop,
4275 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004276 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4277 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004278 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004279 if (!isLoopGuardedByCond(L,
4280 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4281 getMinusSCEV(Start, Step), RHS))
4282 End = isSigned ? getSMaxExpr(RHS, Start)
4283 : getUMaxExpr(RHS, Start);
4284
4285 // Determine the maximum constant end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004286 const SCEV *MaxEnd =
Dan Gohman3964acc2009-06-20 00:32:22 +00004287 isa<SCEVConstant>(End) ? End :
4288 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4289 .ashr(GetMinSignBits(End) - 1) :
4290 APInt::getMaxValue(BitWidth)
4291 .lshr(GetMinLeadingZeros(End)));
Dan Gohmana1af7572009-04-30 20:47:05 +00004292
4293 // Finally, we subtract these two values and divide, rounding up, to get
4294 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004295 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004296
4297 // The maximum backedge count is similar, except using the minimum start
4298 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004299 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004300
4301 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004302 }
4303
Dan Gohman1c343752009-06-27 21:21:31 +00004304 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004305}
4306
Chris Lattner53e677a2004-04-02 20:23:17 +00004307/// getNumIterationsInRange - Return the number of iterations of this loop that
4308/// produce values in the specified constant range. Another way of looking at
4309/// this is that it returns the first iteration number where the value is not in
4310/// the condition, thus computing the exit count. If the iteration count can't
4311/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004312const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004313 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004314 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004315 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004316
4317 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004318 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004319 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004320 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004321 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004322 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004323 if (const SCEVAddRecExpr *ShiftedAddRec =
4324 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004325 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004326 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004327 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004328 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004329 }
4330
4331 // The only time we can solve this is when we have all constant indices.
4332 // Otherwise, we cannot determine the overflow conditions.
4333 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4334 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004335 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004336
4337
4338 // Okay at this point we know that all elements of the chrec are constants and
4339 // that the start element is zero.
4340
4341 // First check to see if the range contains zero. If not, the first
4342 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004343 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004344 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004345 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004346
Chris Lattner53e677a2004-04-02 20:23:17 +00004347 if (isAffine()) {
4348 // If this is an affine expression then we have this situation:
4349 // Solve {0,+,A} in Range === Ax in Range
4350
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004351 // We know that zero is in the range. If A is positive then we know that
4352 // the upper value of the range must be the first possible exit value.
4353 // If A is negative then the lower of the range is the last possible loop
4354 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004355 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004356 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4357 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004358
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004359 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004360 APInt ExitVal = (End + A).udiv(A);
Owen Anderson76f600b2009-07-06 22:37:39 +00004361 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004362
4363 // Evaluate at the exit value. If we really did fall out of the valid
4364 // range, then we computed our trip count, otherwise wrap around or other
4365 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004366 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004367 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004368 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004369
4370 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004371 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004372 EvaluateConstantChrecAtConstant(this,
Owen Anderson76f600b2009-07-06 22:37:39 +00004373 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004374 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004375 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004376 } else if (isQuadratic()) {
4377 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4378 // quadratic equation to solve it. To do this, we must frame our problem in
4379 // terms of figuring out when zero is crossed, instead of when
4380 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004381 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004382 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004383 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004384
4385 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004386 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004387 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004388 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4389 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004390 if (R1) {
4391 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004392 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004393 dyn_cast<ConstantInt>(
4394 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4395 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004396 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004397 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004398
Chris Lattner53e677a2004-04-02 20:23:17 +00004399 // Make sure the root is not off by one. The returned iteration should
4400 // not be in the range, but the previous one should be. When solving
4401 // for "X*X < 5", for example, we should not return a root of 2.
4402 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004403 R1->getValue(),
4404 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004405 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004406 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004407 ConstantInt *NextVal =
4408 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004409
Dan Gohman246b2562007-10-22 18:31:58 +00004410 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004411 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004412 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004413 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004414 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004415
Chris Lattner53e677a2004-04-02 20:23:17 +00004416 // If R1 was not in the range, then it is a good return value. Make
4417 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00004418 ConstantInt *NextVal =
4419 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004420 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004421 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004422 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004423 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004424 }
4425 }
4426 }
4427
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004428 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004429}
4430
4431
4432
4433//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004434// SCEVCallbackVH Class Implementation
4435//===----------------------------------------------------------------------===//
4436
Dan Gohman1959b752009-05-19 19:22:47 +00004437void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00004438 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4439 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4440 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004441 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4442 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004443 SE->Scalars.erase(getValPtr());
4444 // this now dangles!
4445}
4446
Dan Gohman1959b752009-05-19 19:22:47 +00004447void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004448 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4449
4450 // Forget all the expressions associated with users of the old value,
4451 // so that future queries will recompute the expressions using the new
4452 // value.
4453 SmallVector<User *, 16> Worklist;
4454 Value *Old = getValPtr();
4455 bool DeleteOld = false;
4456 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4457 UI != UE; ++UI)
4458 Worklist.push_back(*UI);
4459 while (!Worklist.empty()) {
4460 User *U = Worklist.pop_back_val();
4461 // Deleting the Old value will cause this to dangle. Postpone
4462 // that until everything else is done.
4463 if (U == Old) {
4464 DeleteOld = true;
4465 continue;
4466 }
4467 if (PHINode *PN = dyn_cast<PHINode>(U))
4468 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004469 if (Instruction *I = dyn_cast<Instruction>(U))
4470 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004471 if (SE->Scalars.erase(U))
4472 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4473 UI != UE; ++UI)
4474 Worklist.push_back(*UI);
4475 }
4476 if (DeleteOld) {
4477 if (PHINode *PN = dyn_cast<PHINode>(Old))
4478 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004479 if (Instruction *I = dyn_cast<Instruction>(Old))
4480 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004481 SE->Scalars.erase(Old);
4482 // this now dangles!
4483 }
4484 // this may dangle!
4485}
4486
Dan Gohman1959b752009-05-19 19:22:47 +00004487ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004488 : CallbackVH(V), SE(se) {}
4489
4490//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004491// ScalarEvolution Class Implementation
4492//===----------------------------------------------------------------------===//
4493
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004494ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00004495 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004496}
4497
Chris Lattner53e677a2004-04-02 20:23:17 +00004498bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004499 this->F = &F;
4500 LI = &getAnalysis<LoopInfo>();
4501 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004502 return false;
4503}
4504
4505void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004506 Scalars.clear();
4507 BackedgeTakenCounts.clear();
4508 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004509 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00004510 UniqueSCEVs.clear();
4511 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00004512}
4513
4514void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4515 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004516 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004517}
4518
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004519bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004520 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004521}
4522
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004523static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004524 const Loop *L) {
4525 // Print all inner loops first
4526 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4527 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004528
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004529 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004530
Devang Patelb7211a22007-08-21 00:31:24 +00004531 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004532 L->getExitBlocks(ExitBlocks);
4533 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004534 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004535
Dan Gohman46bdfb02009-02-24 18:55:53 +00004536 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4537 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004538 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004539 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004540 }
4541
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004542 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00004543 OS << "Loop " << L->getHeader()->getName() << ": ";
4544
4545 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4546 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4547 } else {
4548 OS << "Unpredictable max backedge-taken count. ";
4549 }
4550
4551 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004552}
4553
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004554void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004555 // ScalarEvolution's implementaiton of the print method is to print
4556 // out SCEV values of all instructions that are interesting. Doing
4557 // this potentially causes it to create new SCEV objects though,
4558 // which technically conflicts with the const qualifier. This isn't
4559 // observable from outside the class though (the hasSCEV function
4560 // notwithstanding), so casting away the const isn't dangerous.
4561 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004562
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004563 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004564 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004565 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004566 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004567 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004568 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004569 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004570
Dan Gohman0c689c52009-06-19 17:49:54 +00004571 const Loop *L = LI->getLoopFor((*I).getParent());
4572
Dan Gohman0bba49c2009-07-07 17:06:11 +00004573 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004574 if (AtUse != SV) {
4575 OS << " --> ";
4576 AtUse->print(OS);
4577 }
4578
4579 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004580 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004581 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004582 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004583 OS << "<<Unknown>>";
4584 } else {
4585 OS << *ExitValue;
4586 }
4587 }
4588
Chris Lattner53e677a2004-04-02 20:23:17 +00004589 OS << "\n";
4590 }
4591
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004592 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4593 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4594 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004595}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004596
4597void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4598 raw_os_ostream OS(o);
4599 print(OS, M);
4600}