blob: 7fb2e5e7539b111765cc3019521c0e370984af61 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000181 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000182 UniqueSCEVs.InsertNode(S, IP);
183 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman0bba49c2009-07-07 17:06:11 +0000186const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000187 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Dan Gohman0bba49c2009-07-07 17:06:11 +0000190const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000192 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohman6e70e312009-09-27 15:26:03 +0000210bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
212}
213
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000217 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
218 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000229 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
230 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000234void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000241 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
242 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000243 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
Dan Gohmanecb403a2009-05-07 14:00:19 +0000259bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
262 return false;
263 }
264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
270 return false;
271 }
272 return true;
273}
274
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000275bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
277}
278
Dan Gohman6e70e312009-09-27 15:26:03 +0000279bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
281}
282
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000283void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000284 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000285}
286
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294}
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000297 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000298 if (!QueryLoop)
299 return false;
300
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000302 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000303 return false;
304
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
306 // are variant.
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
309 return false;
310
311 // Otherwise it's loop-invariant.
312 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000313}
314
Dan Gohman39125d82010-02-13 00:19:39 +0000315bool
316SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
317 return DT->dominates(L->getHeader(), BB) &&
318 SCEVNAryExpr::dominates(BB, DT);
319}
320
321bool
322SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
323 // This uses a "dominates" query instead of "properly dominates" query because
324 // the instruction which produces the addrec's value is a PHI, and a PHI
325 // effectively properly dominates its entire containing block.
326 return DT->dominates(L->getHeader(), BB) &&
327 SCEVNAryExpr::properlyDominates(BB, DT);
328}
329
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000330void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331 OS << "{" << *Operands[0];
332 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
333 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000334 OS << "}<";
335 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
336 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
Chris Lattner53e677a2004-04-02 20:23:17 +0000338
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000339bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
340 // All non-instruction values are loop invariant. All instructions are loop
341 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000342 // Instructions are never considered invariant in the function body
343 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000344 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000345 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000346 return true;
347}
Chris Lattner53e677a2004-04-02 20:23:17 +0000348
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000349bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
350 if (Instruction *I = dyn_cast<Instruction>(getValue()))
351 return DT->dominates(I->getParent(), BB);
352 return true;
353}
354
Dan Gohman6e70e312009-09-27 15:26:03 +0000355bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
356 if (Instruction *I = dyn_cast<Instruction>(getValue()))
357 return DT->properlyDominates(I->getParent(), BB);
358 return true;
359}
360
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361const Type *SCEVUnknown::getType() const {
362 return V->getType();
363}
Chris Lattner53e677a2004-04-02 20:23:17 +0000364
Dan Gohman0f5efe52010-01-28 02:15:55 +0000365bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
366 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
367 if (VCE->getOpcode() == Instruction::PtrToInt)
368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000369 if (CE->getOpcode() == Instruction::GetElementPtr &&
370 CE->getOperand(0)->isNullValue() &&
371 CE->getNumOperands() == 2)
372 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
373 if (CI->isOne()) {
374 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
375 ->getElementType();
376 return true;
377 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000378
379 return false;
380}
381
382bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
384 if (VCE->getOpcode() == Instruction::PtrToInt)
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000386 if (CE->getOpcode() == Instruction::GetElementPtr &&
387 CE->getOperand(0)->isNullValue()) {
388 const Type *Ty =
389 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
390 if (const StructType *STy = dyn_cast<StructType>(Ty))
391 if (!STy->isPacked() &&
392 CE->getNumOperands() == 3 &&
393 CE->getOperand(1)->isNullValue()) {
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
395 if (CI->isOne() &&
396 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000397 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000398 AllocTy = STy->getElementType(1);
399 return true;
400 }
401 }
402 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000403
404 return false;
405}
406
Dan Gohman4f8eea82010-02-01 18:27:38 +0000407bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getNumOperands() == 3 &&
413 CE->getOperand(0)->isNullValue() &&
414 CE->getOperand(1)->isNullValue()) {
415 const Type *Ty =
416 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
417 // Ignore vector types here so that ScalarEvolutionExpander doesn't
418 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000419 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000420 CTy = Ty;
421 FieldNo = CE->getOperand(2);
422 return true;
423 }
424 }
425
426 return false;
427}
428
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000429void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000430 const Type *AllocTy;
431 if (isSizeOf(AllocTy)) {
432 OS << "sizeof(" << *AllocTy << ")";
433 return;
434 }
435 if (isAlignOf(AllocTy)) {
436 OS << "alignof(" << *AllocTy << ")";
437 return;
438 }
439
Dan Gohman4f8eea82010-02-01 18:27:38 +0000440 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000441 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000442 if (isOffsetOf(CTy, FieldNo)) {
443 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000444 WriteAsOperand(OS, FieldNo, false);
445 OS << ")";
446 return;
447 }
448
449 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000450 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000451}
452
Chris Lattner8d741b82004-06-20 06:23:15 +0000453//===----------------------------------------------------------------------===//
454// SCEV Utilities
455//===----------------------------------------------------------------------===//
456
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000457static bool CompareTypes(const Type *A, const Type *B) {
458 if (A->getTypeID() != B->getTypeID())
459 return A->getTypeID() < B->getTypeID();
460 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
461 const IntegerType *BI = cast<IntegerType>(B);
462 return AI->getBitWidth() < BI->getBitWidth();
463 }
464 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
465 const PointerType *BI = cast<PointerType>(B);
466 return CompareTypes(AI->getElementType(), BI->getElementType());
467 }
468 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
469 const ArrayType *BI = cast<ArrayType>(B);
470 if (AI->getNumElements() != BI->getNumElements())
471 return AI->getNumElements() < BI->getNumElements();
472 return CompareTypes(AI->getElementType(), BI->getElementType());
473 }
474 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
475 const VectorType *BI = cast<VectorType>(B);
476 if (AI->getNumElements() != BI->getNumElements())
477 return AI->getNumElements() < BI->getNumElements();
478 return CompareTypes(AI->getElementType(), BI->getElementType());
479 }
480 if (const StructType *AI = dyn_cast<StructType>(A)) {
481 const StructType *BI = cast<StructType>(B);
482 if (AI->getNumElements() != BI->getNumElements())
483 return AI->getNumElements() < BI->getNumElements();
484 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
485 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
486 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
487 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
488 }
489 return false;
490}
491
Chris Lattner8d741b82004-06-20 06:23:15 +0000492namespace {
493 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
494 /// than the complexity of the RHS. This comparator is used to canonicalize
495 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000496 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000497 LoopInfo *LI;
498 public:
499 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
500
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000501 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000502 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
503 if (LHS == RHS)
504 return false;
505
Dan Gohman72861302009-05-07 14:39:04 +0000506 // Primarily, sort the SCEVs by their getSCEVType().
507 if (LHS->getSCEVType() != RHS->getSCEVType())
508 return LHS->getSCEVType() < RHS->getSCEVType();
509
510 // Aside from the getSCEVType() ordering, the particular ordering
511 // isn't very important except that it's beneficial to be consistent,
512 // so that (a + b) and (b + a) don't end up as different expressions.
513
514 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
515 // not as complete as it could be.
516 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
517 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
518
Dan Gohman5be18e82009-05-19 02:15:55 +0000519 // Order pointer values after integer values. This helps SCEVExpander
520 // form GEPs.
Duncan Sands1df98592010-02-16 11:11:14 +0000521 if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
Dan Gohman5be18e82009-05-19 02:15:55 +0000522 return false;
Duncan Sands1df98592010-02-16 11:11:14 +0000523 if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
Dan Gohman5be18e82009-05-19 02:15:55 +0000524 return true;
525
Dan Gohman72861302009-05-07 14:39:04 +0000526 // Compare getValueID values.
527 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
528 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
529
530 // Sort arguments by their position.
531 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
532 const Argument *RA = cast<Argument>(RU->getValue());
533 return LA->getArgNo() < RA->getArgNo();
534 }
535
536 // For instructions, compare their loop depth, and their opcode.
537 // This is pretty loose.
538 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
539 Instruction *RV = cast<Instruction>(RU->getValue());
540
541 // Compare loop depths.
542 if (LI->getLoopDepth(LV->getParent()) !=
543 LI->getLoopDepth(RV->getParent()))
544 return LI->getLoopDepth(LV->getParent()) <
545 LI->getLoopDepth(RV->getParent());
546
547 // Compare opcodes.
548 if (LV->getOpcode() != RV->getOpcode())
549 return LV->getOpcode() < RV->getOpcode();
550
551 // Compare the number of operands.
552 if (LV->getNumOperands() != RV->getNumOperands())
553 return LV->getNumOperands() < RV->getNumOperands();
554 }
555
556 return false;
557 }
558
Dan Gohman4dfad292009-06-14 22:51:25 +0000559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000562 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
563 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000564 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
565 }
566
567 // Compare addrec loop depths.
568 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
569 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
570 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
571 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
572 }
Dan Gohman72861302009-05-07 14:39:04 +0000573
574 // Lexicographically compare n-ary expressions.
575 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
576 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
577 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
578 if (i >= RC->getNumOperands())
579 return false;
580 if (operator()(LC->getOperand(i), RC->getOperand(i)))
581 return true;
582 if (operator()(RC->getOperand(i), LC->getOperand(i)))
583 return false;
584 }
585 return LC->getNumOperands() < RC->getNumOperands();
586 }
587
Dan Gohmana6b35e22009-05-07 19:23:21 +0000588 // Lexicographically compare udiv expressions.
589 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
590 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
591 if (operator()(LC->getLHS(), RC->getLHS()))
592 return true;
593 if (operator()(RC->getLHS(), LC->getLHS()))
594 return false;
595 if (operator()(LC->getRHS(), RC->getRHS()))
596 return true;
597 if (operator()(RC->getRHS(), LC->getRHS()))
598 return false;
599 return false;
600 }
601
Dan Gohman72861302009-05-07 14:39:04 +0000602 // Compare cast expressions by operand.
603 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
604 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
605 return operator()(LC->getOperand(), RC->getOperand());
606 }
607
Torok Edwinc23197a2009-07-14 16:55:14 +0000608 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000609 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000610 }
611 };
612}
613
614/// GroupByComplexity - Given a list of SCEV objects, order them by their
615/// complexity, and group objects of the same complexity together by value.
616/// When this routine is finished, we know that any duplicates in the vector are
617/// consecutive and that complexity is monotonically increasing.
618///
619/// Note that we go take special precautions to ensure that we get determinstic
620/// results from this routine. In other words, we don't want the results of
621/// this to depend on where the addresses of various SCEV objects happened to
622/// land in memory.
623///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000624static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000625 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000626 if (Ops.size() < 2) return; // Noop
627 if (Ops.size() == 2) {
628 // This is the common case, which also happens to be trivially simple.
629 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000630 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000631 std::swap(Ops[0], Ops[1]);
632 return;
633 }
634
635 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000636 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000637
638 // Now that we are sorted by complexity, group elements of the same
639 // complexity. Note that this is, at worst, N^2, but the vector is likely to
640 // be extremely short in practice. Note that we take this approach because we
641 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000642 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000643 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000644 unsigned Complexity = S->getSCEVType();
645
646 // If there are any objects of the same complexity and same value as this
647 // one, group them.
648 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
649 if (Ops[j] == S) { // Found a duplicate.
650 // Move it to immediately after i'th element.
651 std::swap(Ops[i+1], Ops[j]);
652 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000653 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000654 }
655 }
656 }
657}
658
Chris Lattner53e677a2004-04-02 20:23:17 +0000659
Chris Lattner53e677a2004-04-02 20:23:17 +0000660
661//===----------------------------------------------------------------------===//
662// Simple SCEV method implementations
663//===----------------------------------------------------------------------===//
664
Eli Friedmanb42a6262008-08-04 23:49:06 +0000665/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000666/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000667static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000668 ScalarEvolution &SE,
669 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000670 // Handle the simplest case efficiently.
671 if (K == 1)
672 return SE.getTruncateOrZeroExtend(It, ResultTy);
673
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674 // We are using the following formula for BC(It, K):
675 //
676 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
677 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000678 // Suppose, W is the bitwidth of the return value. We must be prepared for
679 // overflow. Hence, we must assure that the result of our computation is
680 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
681 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000682 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000683 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000684 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000685 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
686 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000687 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000689 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000690 // This formula is trivially equivalent to the previous formula. However,
691 // this formula can be implemented much more efficiently. The trick is that
692 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
693 // arithmetic. To do exact division in modular arithmetic, all we have
694 // to do is multiply by the inverse. Therefore, this step can be done at
695 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000696 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000697 // The next issue is how to safely do the division by 2^T. The way this
698 // is done is by doing the multiplication step at a width of at least W + T
699 // bits. This way, the bottom W+T bits of the product are accurate. Then,
700 // when we perform the division by 2^T (which is equivalent to a right shift
701 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
702 // truncated out after the division by 2^T.
703 //
704 // In comparison to just directly using the first formula, this technique
705 // is much more efficient; using the first formula requires W * K bits,
706 // but this formula less than W + K bits. Also, the first formula requires
707 // a division step, whereas this formula only requires multiplies and shifts.
708 //
709 // It doesn't matter whether the subtraction step is done in the calculation
710 // width or the input iteration count's width; if the subtraction overflows,
711 // the result must be zero anyway. We prefer here to do it in the width of
712 // the induction variable because it helps a lot for certain cases; CodeGen
713 // isn't smart enough to ignore the overflow, which leads to much less
714 // efficient code if the width of the subtraction is wider than the native
715 // register width.
716 //
717 // (It's possible to not widen at all by pulling out factors of 2 before
718 // the multiplication; for example, K=2 can be calculated as
719 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
720 // extra arithmetic, so it's not an obvious win, and it gets
721 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000722
Eli Friedmanb42a6262008-08-04 23:49:06 +0000723 // Protection from insane SCEVs; this bound is conservative,
724 // but it probably doesn't matter.
725 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000726 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000727
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000728 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000729
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730 // Calculate K! / 2^T and T; we divide out the factors of two before
731 // multiplying for calculating K! / 2^T to avoid overflow.
732 // Other overflow doesn't matter because we only care about the bottom
733 // W bits of the result.
734 APInt OddFactorial(W, 1);
735 unsigned T = 1;
736 for (unsigned i = 3; i <= K; ++i) {
737 APInt Mult(W, i);
738 unsigned TwoFactors = Mult.countTrailingZeros();
739 T += TwoFactors;
740 Mult = Mult.lshr(TwoFactors);
741 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000742 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000743
Eli Friedmanb42a6262008-08-04 23:49:06 +0000744 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000745 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000746
747 // Calcuate 2^T, at width T+W.
748 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
749
750 // Calculate the multiplicative inverse of K! / 2^T;
751 // this multiplication factor will perform the exact division by
752 // K! / 2^T.
753 APInt Mod = APInt::getSignedMinValue(W+1);
754 APInt MultiplyFactor = OddFactorial.zext(W+1);
755 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
756 MultiplyFactor = MultiplyFactor.trunc(W);
757
758 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000759 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
760 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000761 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000762 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000763 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000764 Dividend = SE.getMulExpr(Dividend,
765 SE.getTruncateOrZeroExtend(S, CalculationTy));
766 }
767
768 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000769 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000770
771 // Truncate the result, and divide by K! / 2^T.
772
773 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
774 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000775}
776
Chris Lattner53e677a2004-04-02 20:23:17 +0000777/// evaluateAtIteration - Return the value of this chain of recurrences at
778/// the specified iteration number. We can evaluate this recurrence by
779/// multiplying each element in the chain by the binomial coefficient
780/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
781///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000782/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000783///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000784/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000785///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000786const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000787 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000788 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000790 // The computation is correct in the face of overflow provided that the
791 // multiplication is performed _after_ the evaluation of the binomial
792 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000793 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000794 if (isa<SCEVCouldNotCompute>(Coeff))
795 return Coeff;
796
797 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000798 }
799 return Result;
800}
801
Chris Lattner53e677a2004-04-02 20:23:17 +0000802//===----------------------------------------------------------------------===//
803// SCEV Expression folder implementations
804//===----------------------------------------------------------------------===//
805
Dan Gohman0bba49c2009-07-07 17:06:11 +0000806const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000807 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000808 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000809 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000810 assert(isSCEVable(Ty) &&
811 "This is not a conversion to a SCEVable type!");
812 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000813
Dan Gohmanc050fd92009-07-13 20:50:19 +0000814 FoldingSetNodeID ID;
815 ID.AddInteger(scTruncate);
816 ID.AddPointer(Op);
817 ID.AddPointer(Ty);
818 void *IP = 0;
819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
820
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000821 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000822 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000823 return getConstant(
824 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000825
Dan Gohman20900ca2009-04-22 16:20:48 +0000826 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000827 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000828 return getTruncateExpr(ST->getOperand(), Ty);
829
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000830 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000831 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000832 return getTruncateOrSignExtend(SS->getOperand(), Ty);
833
834 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000835 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000836 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
837
Dan Gohman6864db62009-06-18 16:24:47 +0000838 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000839 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000841 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000842 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
843 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000844 }
845
Dan Gohmanc050fd92009-07-13 20:50:19 +0000846 // The cast wasn't folded; create an explicit cast node.
847 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000848 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
849 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000850 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000851 UniqueSCEVs.InsertNode(S, IP);
852 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000853}
854
Dan Gohman0bba49c2009-07-07 17:06:11 +0000855const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000856 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000857 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000858 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000859 assert(isSCEVable(Ty) &&
860 "This is not a conversion to a SCEVable type!");
861 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000862
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000863 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000864 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000865 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000866 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
867 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000868 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000869 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000870
Dan Gohman20900ca2009-04-22 16:20:48 +0000871 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000872 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000873 return getZeroExtendExpr(SZ->getOperand(), Ty);
874
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000875 // Before doing any expensive analysis, check to see if we've already
876 // computed a SCEV for this Op and Ty.
877 FoldingSetNodeID ID;
878 ID.AddInteger(scZeroExtend);
879 ID.AddPointer(Op);
880 ID.AddPointer(Ty);
881 void *IP = 0;
882 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
883
Dan Gohman01ecca22009-04-27 20:16:15 +0000884 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000885 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000886 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000887 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000888 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000889 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000890 const SCEV *Start = AR->getStart();
891 const SCEV *Step = AR->getStepRecurrence(*this);
892 unsigned BitWidth = getTypeSizeInBits(AR->getType());
893 const Loop *L = AR->getLoop();
894
Dan Gohmaneb490a72009-07-25 01:22:26 +0000895 // If we have special knowledge that this addrec won't overflow,
896 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000897 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000898 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
899 getZeroExtendExpr(Step, Ty),
900 L);
901
Dan Gohman01ecca22009-04-27 20:16:15 +0000902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000910 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000912 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000913 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000914
915 // Check whether the backedge-taken count can be losslessly casted to
916 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000917 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000918 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000919 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000920 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
921 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000922 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000923 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000924 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000925 const SCEV *Add = getAddExpr(Start, ZMul);
926 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000927 getAddExpr(getZeroExtendExpr(Start, WideTy),
928 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
929 getZeroExtendExpr(Step, WideTy)));
930 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000931 // Return the expression with the addrec on the outside.
932 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
933 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000934 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000935
936 // Similar to above, only this time treat the step value as signed.
937 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000938 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000939 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000940 OperandExtendedAdd =
941 getAddExpr(getZeroExtendExpr(Start, WideTy),
942 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
943 getSignExtendExpr(Step, WideTy)));
944 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000945 // Return the expression with the addrec on the outside.
946 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
947 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000948 L);
949 }
950
951 // If the backedge is guarded by a comparison with the pre-inc value
952 // the addrec is safe. Also, if the entry is guarded by a comparison
953 // with the start value and the backedge is guarded by a comparison
954 // with the post-inc value, the addrec is safe.
955 if (isKnownPositive(Step)) {
956 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
957 getUnsignedRange(Step).getUnsignedMax());
958 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
959 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
960 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
961 AR->getPostIncExpr(*this), N)))
962 // Return the expression with the addrec on the outside.
963 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
964 getZeroExtendExpr(Step, Ty),
965 L);
966 } else if (isKnownNegative(Step)) {
967 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
968 getSignedRange(Step).getSignedMin());
969 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
970 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
971 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
972 AR->getPostIncExpr(*this), N)))
973 // Return the expression with the addrec on the outside.
974 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
975 getSignExtendExpr(Step, Ty),
976 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000977 }
978 }
979 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000980
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000981 // The cast wasn't folded; create an explicit cast node.
982 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000983 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
984 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000985 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000986 UniqueSCEVs.InsertNode(S, IP);
987 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000988}
989
Dan Gohman0bba49c2009-07-07 17:06:11 +0000990const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000991 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000993 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000994 assert(isSCEVable(Ty) &&
995 "This is not a conversion to a SCEVable type!");
996 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000997
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000998 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001000 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001001 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1002 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001003 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +00001004 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001005
Dan Gohman20900ca2009-04-22 16:20:48 +00001006 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001007 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001008 return getSignExtendExpr(SS->getOperand(), Ty);
1009
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001010 // Before doing any expensive analysis, check to see if we've already
1011 // computed a SCEV for this Op and Ty.
1012 FoldingSetNodeID ID;
1013 ID.AddInteger(scSignExtend);
1014 ID.AddPointer(Op);
1015 ID.AddPointer(Ty);
1016 void *IP = 0;
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1018
Dan Gohman01ecca22009-04-27 20:16:15 +00001019 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001020 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001021 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001022 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001023 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001024 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001025 const SCEV *Start = AR->getStart();
1026 const SCEV *Step = AR->getStepRecurrence(*this);
1027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1028 const Loop *L = AR->getLoop();
1029
Dan Gohmaneb490a72009-07-25 01:22:26 +00001030 // If we have special knowledge that this addrec won't overflow,
1031 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001032 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001033 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1034 getSignExtendExpr(Step, Ty),
1035 L);
1036
Dan Gohman01ecca22009-04-27 20:16:15 +00001037 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1038 // Note that this serves two purposes: It filters out loops that are
1039 // simply not analyzable, and it covers the case where this code is
1040 // being called from within backedge-taken count analysis, such that
1041 // attempting to ask for the backedge-taken count would likely result
1042 // in infinite recursion. In the later case, the analysis code will
1043 // cope with a conservative value, and it will take care to purge
1044 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001045 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001046 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001047 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001048 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001049
1050 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001051 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001052 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001053 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001054 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001055 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1056 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001057 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001058 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001059 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001060 const SCEV *Add = getAddExpr(Start, SMul);
1061 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001062 getAddExpr(getSignExtendExpr(Start, WideTy),
1063 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1064 getSignExtendExpr(Step, WideTy)));
1065 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001066 // Return the expression with the addrec on the outside.
1067 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1068 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001069 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001070
1071 // Similar to above, only this time treat the step value as unsigned.
1072 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001073 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001074 Add = getAddExpr(Start, UMul);
1075 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001076 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001077 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1078 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001079 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getZeroExtendExpr(Step, Ty),
1083 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001084 }
1085
1086 // If the backedge is guarded by a comparison with the pre-inc value
1087 // the addrec is safe. Also, if the entry is guarded by a comparison
1088 // with the start value and the backedge is guarded by a comparison
1089 // with the post-inc value, the addrec is safe.
1090 if (isKnownPositive(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1092 getSignedRange(Step).getSignedMax());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1094 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1096 AR->getPostIncExpr(*this), N)))
1097 // Return the expression with the addrec on the outside.
1098 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1099 getSignExtendExpr(Step, Ty),
1100 L);
1101 } else if (isKnownNegative(Step)) {
1102 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1103 getSignedRange(Step).getSignedMin());
1104 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1105 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1106 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1107 AR->getPostIncExpr(*this), N)))
1108 // Return the expression with the addrec on the outside.
1109 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1110 getSignExtendExpr(Step, Ty),
1111 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001112 }
1113 }
1114 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001115
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001116 // The cast wasn't folded; create an explicit cast node.
1117 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1119 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001120 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001121 UniqueSCEVs.InsertNode(S, IP);
1122 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001123}
1124
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001125/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1126/// unspecified bits out to the given type.
1127///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001128const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001129 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001130 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1131 "This is not an extending conversion!");
1132 assert(isSCEVable(Ty) &&
1133 "This is not a conversion to a SCEVable type!");
1134 Ty = getEffectiveSCEVType(Ty);
1135
1136 // Sign-extend negative constants.
1137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1138 if (SC->getValue()->getValue().isNegative())
1139 return getSignExtendExpr(Op, Ty);
1140
1141 // Peel off a truncate cast.
1142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001143 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001144 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1145 return getAnyExtendExpr(NewOp, Ty);
1146 return getTruncateOrNoop(NewOp, Ty);
1147 }
1148
1149 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001150 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001151 if (!isa<SCEVZeroExtendExpr>(ZExt))
1152 return ZExt;
1153
1154 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001155 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001156 if (!isa<SCEVSignExtendExpr>(SExt))
1157 return SExt;
1158
Dan Gohmana10756e2010-01-21 02:09:26 +00001159 // Force the cast to be folded into the operands of an addrec.
1160 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1161 SmallVector<const SCEV *, 4> Ops;
1162 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1163 I != E; ++I)
1164 Ops.push_back(getAnyExtendExpr(*I, Ty));
1165 return getAddRecExpr(Ops, AR->getLoop());
1166 }
1167
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001168 // If the expression is obviously signed, use the sext cast value.
1169 if (isa<SCEVSMaxExpr>(Op))
1170 return SExt;
1171
1172 // Absent any other information, use the zext cast value.
1173 return ZExt;
1174}
1175
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001176/// CollectAddOperandsWithScales - Process the given Ops list, which is
1177/// a list of operands to be added under the given scale, update the given
1178/// map. This is a helper function for getAddRecExpr. As an example of
1179/// what it does, given a sequence of operands that would form an add
1180/// expression like this:
1181///
1182/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1183///
1184/// where A and B are constants, update the map with these values:
1185///
1186/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1187///
1188/// and add 13 + A*B*29 to AccumulatedConstant.
1189/// This will allow getAddRecExpr to produce this:
1190///
1191/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1192///
1193/// This form often exposes folding opportunities that are hidden in
1194/// the original operand list.
1195///
1196/// Return true iff it appears that any interesting folding opportunities
1197/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1198/// the common case where no interesting opportunities are present, and
1199/// is also used as a check to avoid infinite recursion.
1200///
1201static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001202CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1203 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001204 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001205 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001206 const APInt &Scale,
1207 ScalarEvolution &SE) {
1208 bool Interesting = false;
1209
1210 // Iterate over the add operands.
1211 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1212 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1213 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1214 APInt NewScale =
1215 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1216 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1217 // A multiplication of a constant with another add; recurse.
1218 Interesting |=
1219 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1220 cast<SCEVAddExpr>(Mul->getOperand(1))
1221 ->getOperands(),
1222 NewScale, SE);
1223 } else {
1224 // A multiplication of a constant with some other value. Update
1225 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001226 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1227 const SCEV *Key = SE.getMulExpr(MulOps);
1228 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001229 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001230 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001231 NewOps.push_back(Pair.first->first);
1232 } else {
1233 Pair.first->second += NewScale;
1234 // The map already had an entry for this value, which may indicate
1235 // a folding opportunity.
1236 Interesting = true;
1237 }
1238 }
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // Pull a buried constant out to the outside.
1241 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1242 Interesting = true;
1243 AccumulatedConstant += Scale * C->getValue()->getValue();
1244 } else {
1245 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001246 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001247 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001248 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001249 NewOps.push_back(Pair.first->first);
1250 } else {
1251 Pair.first->second += Scale;
1252 // The map already had an entry for this value, which may indicate
1253 // a folding opportunity.
1254 Interesting = true;
1255 }
1256 }
1257 }
1258
1259 return Interesting;
1260}
1261
1262namespace {
1263 struct APIntCompare {
1264 bool operator()(const APInt &LHS, const APInt &RHS) const {
1265 return LHS.ult(RHS);
1266 }
1267 };
1268}
1269
Dan Gohman6c0866c2009-05-24 23:45:28 +00001270/// getAddExpr - Get a canonical add expression, or something simpler if
1271/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001272const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1273 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001274 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001275 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001276#ifndef NDEBUG
1277 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1278 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1279 getEffectiveSCEVType(Ops[0]->getType()) &&
1280 "SCEVAddExpr operand types don't match!");
1281#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001282
Dan Gohmana10756e2010-01-21 02:09:26 +00001283 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1284 if (!HasNUW && HasNSW) {
1285 bool All = true;
1286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1287 if (!isKnownNonNegative(Ops[i])) {
1288 All = false;
1289 break;
1290 }
1291 if (All) HasNUW = true;
1292 }
1293
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001295 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001296
1297 // If there are any constants, fold them together.
1298 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001301 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001304 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1305 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001306 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001307 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001308 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001309 }
1310
1311 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001312 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001313 Ops.erase(Ops.begin());
1314 --Idx;
1315 }
1316 }
1317
Chris Lattner627018b2004-04-07 16:16:11 +00001318 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001319
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 // Okay, check to see if the same value occurs in the operand list twice. If
1321 // so, merge them together into an multiply expression. Since we sorted the
1322 // list, these values are required to be adjacent.
1323 const Type *Ty = Ops[0]->getType();
1324 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1325 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1326 // Found a match, merge the two values into a multiply, and add any
1327 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001328 const SCEV *Two = getIntegerSCEV(2, Ty);
1329 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 if (Ops.size() == 2)
1331 return Mul;
1332 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1333 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001334 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 }
1336
Dan Gohman728c7f32009-05-08 21:03:19 +00001337 // Check for truncates. If all the operands are truncated from the same
1338 // type, see if factoring out the truncate would permit the result to be
1339 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1340 // if the contents of the resulting outer trunc fold to something simple.
1341 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1342 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1343 const Type *DstType = Trunc->getType();
1344 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001345 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001346 bool Ok = true;
1347 // Check all the operands to see if they can be represented in the
1348 // source type of the truncate.
1349 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1350 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1351 if (T->getOperand()->getType() != SrcType) {
1352 Ok = false;
1353 break;
1354 }
1355 LargeOps.push_back(T->getOperand());
1356 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1357 // This could be either sign or zero extension, but sign extension
1358 // is much more likely to be foldable here.
1359 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1360 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001361 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001362 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1363 if (const SCEVTruncateExpr *T =
1364 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1365 if (T->getOperand()->getType() != SrcType) {
1366 Ok = false;
1367 break;
1368 }
1369 LargeMulOps.push_back(T->getOperand());
1370 } else if (const SCEVConstant *C =
1371 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1372 // This could be either sign or zero extension, but sign extension
1373 // is much more likely to be foldable here.
1374 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1375 } else {
1376 Ok = false;
1377 break;
1378 }
1379 }
1380 if (Ok)
1381 LargeOps.push_back(getMulExpr(LargeMulOps));
1382 } else {
1383 Ok = false;
1384 break;
1385 }
1386 }
1387 if (Ok) {
1388 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001389 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001390 // If it folds to something simple, use it. Otherwise, don't.
1391 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1392 return getTruncateExpr(Fold, DstType);
1393 }
1394 }
1395
1396 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001397 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1398 ++Idx;
1399
1400 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 if (Idx < Ops.size()) {
1402 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001403 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // If we have an add, expand the add operands onto the end of the operands
1405 // list.
1406 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1407 Ops.erase(Ops.begin()+Idx);
1408 DeletedAdd = true;
1409 }
1410
1411 // If we deleted at least one add, we added operands to the end of the list,
1412 // and they are not necessarily sorted. Recurse to resort and resimplify
1413 // any operands we just aquired.
1414 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001415 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001416 }
1417
1418 // Skip over the add expression until we get to a multiply.
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1420 ++Idx;
1421
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001422 // Check to see if there are any folding opportunities present with
1423 // operands multiplied by constant values.
1424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1425 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001426 DenseMap<const SCEV *, APInt> M;
1427 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001428 APInt AccumulatedConstant(BitWidth, 0);
1429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1430 Ops, APInt(BitWidth, 1), *this)) {
1431 // Some interesting folding opportunity is present, so its worthwhile to
1432 // re-generate the operands list. Group the operands by constant scale,
1433 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001434 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1435 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001436 E = NewOps.end(); I != E; ++I)
1437 MulOpLists[M.find(*I)->second].push_back(*I);
1438 // Re-generate the operands list.
1439 Ops.clear();
1440 if (AccumulatedConstant != 0)
1441 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001442 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1443 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001444 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001445 Ops.push_back(getMulExpr(getConstant(I->first),
1446 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001447 if (Ops.empty())
1448 return getIntegerSCEV(0, Ty);
1449 if (Ops.size() == 1)
1450 return Ops[0];
1451 return getAddExpr(Ops);
1452 }
1453 }
1454
Chris Lattner53e677a2004-04-02 20:23:17 +00001455 // If we are adding something to a multiply expression, make sure the
1456 // something is not already an operand of the multiply. If so, merge it into
1457 // the multiply.
1458 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001459 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001461 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001463 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001464 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001465 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 if (Mul->getNumOperands() != 2) {
1467 // If the multiply has more than two operands, we must get the
1468 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001469 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001471 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001472 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001473 const SCEV *One = getIntegerSCEV(1, Ty);
1474 const SCEV *AddOne = getAddExpr(InnerMul, One);
1475 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 if (Ops.size() == 2) return OuterMul;
1477 if (AddOp < Idx) {
1478 Ops.erase(Ops.begin()+AddOp);
1479 Ops.erase(Ops.begin()+Idx-1);
1480 } else {
1481 Ops.erase(Ops.begin()+Idx);
1482 Ops.erase(Ops.begin()+AddOp-1);
1483 }
1484 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001485 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001487
Chris Lattner53e677a2004-04-02 20:23:17 +00001488 // Check this multiply against other multiplies being added together.
1489 for (unsigned OtherMulIdx = Idx+1;
1490 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1491 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001492 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 // If MulOp occurs in OtherMul, we can fold the two multiplies
1494 // together.
1495 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1496 OMulOp != e; ++OMulOp)
1497 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1498 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001499 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001500 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001501 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1502 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001504 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001506 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001507 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001508 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1509 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001511 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001512 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001513 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1514 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 if (Ops.size() == 2) return OuterMul;
1516 Ops.erase(Ops.begin()+Idx);
1517 Ops.erase(Ops.begin()+OtherMulIdx-1);
1518 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001519 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 }
1521 }
1522 }
1523 }
1524
1525 // If there are any add recurrences in the operands list, see if any other
1526 // added values are loop invariant. If so, we can fold them into the
1527 // recurrence.
1528 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1529 ++Idx;
1530
1531 // Scan over all recurrences, trying to fold loop invariants into them.
1532 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1533 // Scan all of the other operands to this add and add them to the vector if
1534 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001535 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001536 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1538 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1539 LIOps.push_back(Ops[i]);
1540 Ops.erase(Ops.begin()+i);
1541 --i; --e;
1542 }
1543
1544 // If we found some loop invariants, fold them into the recurrence.
1545 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001546 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001547 LIOps.push_back(AddRec->getStart());
1548
Dan Gohman0bba49c2009-07-07 17:06:11 +00001549 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001550 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001551 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001552
Dan Gohman355b4f32009-12-19 01:46:34 +00001553 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001554 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001555 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001556
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 // If all of the other operands were loop invariant, we are done.
1558 if (Ops.size() == 1) return NewRec;
1559
1560 // Otherwise, add the folded AddRec by the non-liv parts.
1561 for (unsigned i = 0;; ++i)
1562 if (Ops[i] == AddRec) {
1563 Ops[i] = NewRec;
1564 break;
1565 }
Dan Gohman246b2562007-10-22 18:31:58 +00001566 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 }
1568
1569 // Okay, if there weren't any loop invariants to be folded, check to see if
1570 // there are multiple AddRec's with the same loop induction variable being
1571 // added together. If so, we can fold them.
1572 for (unsigned OtherIdx = Idx+1;
1573 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1574 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001575 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001576 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1577 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001578 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1579 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1581 if (i >= NewOps.size()) {
1582 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1583 OtherAddRec->op_end());
1584 break;
1585 }
Dan Gohman246b2562007-10-22 18:31:58 +00001586 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001588 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001589
1590 if (Ops.size() == 2) return NewAddRec;
1591
1592 Ops.erase(Ops.begin()+Idx);
1593 Ops.erase(Ops.begin()+OtherIdx-1);
1594 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001595 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 }
1597 }
1598
1599 // Otherwise couldn't fold anything into this recurrence. Move onto the
1600 // next one.
1601 }
1602
1603 // Okay, it looks like we really DO need an add expr. Check to see if we
1604 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001605 FoldingSetNodeID ID;
1606 ID.AddInteger(scAddExpr);
1607 ID.AddInteger(Ops.size());
1608 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1609 ID.AddPointer(Ops[i]);
1610 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001611 SCEVAddExpr *S =
1612 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1613 if (!S) {
1614 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1615 new (S) SCEVAddExpr(ID, Ops);
1616 UniqueSCEVs.InsertNode(S, IP);
1617 }
Dan Gohman3645b012009-10-09 00:10:36 +00001618 if (HasNUW) S->setHasNoUnsignedWrap(true);
1619 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001620 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001621}
1622
Dan Gohman6c0866c2009-05-24 23:45:28 +00001623/// getMulExpr - Get a canonical multiply expression, or something simpler if
1624/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001625const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1626 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001628 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001629#ifndef NDEBUG
1630 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1631 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1632 getEffectiveSCEVType(Ops[0]->getType()) &&
1633 "SCEVMulExpr operand types don't match!");
1634#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001635
Dan Gohmana10756e2010-01-21 02:09:26 +00001636 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1637 if (!HasNUW && HasNSW) {
1638 bool All = true;
1639 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1640 if (!isKnownNonNegative(Ops[i])) {
1641 All = false;
1642 break;
1643 }
1644 if (All) HasNUW = true;
1645 }
1646
Chris Lattner53e677a2004-04-02 20:23:17 +00001647 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001648 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001649
1650 // If there are any constants, fold them together.
1651 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001652 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001653
1654 // C1*(C2+V) -> C1*C2 + C1*V
1655 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001656 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001657 if (Add->getNumOperands() == 2 &&
1658 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001659 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1660 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001661
Chris Lattner53e677a2004-04-02 20:23:17 +00001662 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001663 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001664 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001665 ConstantInt *Fold = ConstantInt::get(getContext(),
1666 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001667 RHSC->getValue()->getValue());
1668 Ops[0] = getConstant(Fold);
1669 Ops.erase(Ops.begin()+1); // Erase the folded element
1670 if (Ops.size() == 1) return Ops[0];
1671 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 }
1673
1674 // If we are left with a constant one being multiplied, strip it off.
1675 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1676 Ops.erase(Ops.begin());
1677 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001678 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001679 // If we have a multiply of zero, it will always be zero.
1680 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001681 } else if (Ops[0]->isAllOnesValue()) {
1682 // If we have a mul by -1 of an add, try distributing the -1 among the
1683 // add operands.
1684 if (Ops.size() == 2)
1685 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1686 SmallVector<const SCEV *, 4> NewOps;
1687 bool AnyFolded = false;
1688 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1689 I != E; ++I) {
1690 const SCEV *Mul = getMulExpr(Ops[0], *I);
1691 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1692 NewOps.push_back(Mul);
1693 }
1694 if (AnyFolded)
1695 return getAddExpr(NewOps);
1696 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001697 }
1698 }
1699
1700 // Skip over the add expression until we get to a multiply.
1701 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1702 ++Idx;
1703
1704 if (Ops.size() == 1)
1705 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001706
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 // If there are mul operands inline them all into this expression.
1708 if (Idx < Ops.size()) {
1709 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001710 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001711 // If we have an mul, expand the mul operands onto the end of the operands
1712 // list.
1713 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1714 Ops.erase(Ops.begin()+Idx);
1715 DeletedMul = true;
1716 }
1717
1718 // If we deleted at least one mul, we added operands to the end of the list,
1719 // and they are not necessarily sorted. Recurse to resort and resimplify
1720 // any operands we just aquired.
1721 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001722 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 }
1724
1725 // If there are any add recurrences in the operands list, see if any other
1726 // added values are loop invariant. If so, we can fold them into the
1727 // recurrence.
1728 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1729 ++Idx;
1730
1731 // Scan over all recurrences, trying to fold loop invariants into them.
1732 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1733 // Scan all of the other operands to this mul and add them to the vector if
1734 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001735 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001736 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1738 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1739 LIOps.push_back(Ops[i]);
1740 Ops.erase(Ops.begin()+i);
1741 --i; --e;
1742 }
1743
1744 // If we found some loop invariants, fold them into the recurrence.
1745 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001746 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001747 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 NewOps.reserve(AddRec->getNumOperands());
1749 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001750 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001752 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001753 } else {
1754 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001755 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001756 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001757 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001758 }
1759 }
1760
Dan Gohman355b4f32009-12-19 01:46:34 +00001761 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001762 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001763 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1764 HasNUW && AddRec->hasNoUnsignedWrap(),
1765 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001766
1767 // If all of the other operands were loop invariant, we are done.
1768 if (Ops.size() == 1) return NewRec;
1769
1770 // Otherwise, multiply the folded AddRec by the non-liv parts.
1771 for (unsigned i = 0;; ++i)
1772 if (Ops[i] == AddRec) {
1773 Ops[i] = NewRec;
1774 break;
1775 }
Dan Gohman246b2562007-10-22 18:31:58 +00001776 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 }
1778
1779 // Okay, if there weren't any loop invariants to be folded, check to see if
1780 // there are multiple AddRec's with the same loop induction variable being
1781 // multiplied together. If so, we can fold them.
1782 for (unsigned OtherIdx = Idx+1;
1783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1784 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001785 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1787 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001788 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001789 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001790 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001791 const SCEV *B = F->getStepRecurrence(*this);
1792 const SCEV *D = G->getStepRecurrence(*this);
1793 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001794 getMulExpr(G, B),
1795 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001796 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001797 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001798 if (Ops.size() == 2) return NewAddRec;
1799
1800 Ops.erase(Ops.begin()+Idx);
1801 Ops.erase(Ops.begin()+OtherIdx-1);
1802 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001803 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001804 }
1805 }
1806
1807 // Otherwise couldn't fold anything into this recurrence. Move onto the
1808 // next one.
1809 }
1810
1811 // Okay, it looks like we really DO need an mul expr. Check to see if we
1812 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001813 FoldingSetNodeID ID;
1814 ID.AddInteger(scMulExpr);
1815 ID.AddInteger(Ops.size());
1816 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1817 ID.AddPointer(Ops[i]);
1818 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001819 SCEVMulExpr *S =
1820 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1821 if (!S) {
1822 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1823 new (S) SCEVMulExpr(ID, Ops);
1824 UniqueSCEVs.InsertNode(S, IP);
1825 }
Dan Gohman3645b012009-10-09 00:10:36 +00001826 if (HasNUW) S->setHasNoUnsignedWrap(true);
1827 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001828 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001829}
1830
Andreas Bolka8a11c982009-08-07 22:55:26 +00001831/// getUDivExpr - Get a canonical unsigned division expression, or something
1832/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001833const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1834 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001835 assert(getEffectiveSCEVType(LHS->getType()) ==
1836 getEffectiveSCEVType(RHS->getType()) &&
1837 "SCEVUDivExpr operand types don't match!");
1838
Dan Gohman622ed672009-05-04 22:02:23 +00001839 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001840 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001841 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001842 if (RHSC->isZero())
1843 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001844
Dan Gohman185cf032009-05-08 20:18:49 +00001845 // Determine if the division can be folded into the operands of
1846 // its operands.
1847 // TODO: Generalize this to non-constants by using known-bits information.
1848 const Type *Ty = LHS->getType();
1849 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1850 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1851 // For non-power-of-two values, effectively round the value up to the
1852 // nearest power of two.
1853 if (!RHSC->getValue()->getValue().isPowerOf2())
1854 ++MaxShiftAmt;
1855 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001856 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001857 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1858 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1859 if (const SCEVConstant *Step =
1860 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1861 if (!Step->getValue()->getValue()
1862 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001863 getZeroExtendExpr(AR, ExtTy) ==
1864 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1865 getZeroExtendExpr(Step, ExtTy),
1866 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001867 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001868 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1869 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1870 return getAddRecExpr(Operands, AR->getLoop());
1871 }
1872 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001873 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001874 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001875 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1876 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1877 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001878 // Find an operand that's safely divisible.
1879 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001880 const SCEV *Op = M->getOperand(i);
1881 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001882 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001883 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1884 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001885 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001886 Operands[i] = Div;
1887 return getMulExpr(Operands);
1888 }
1889 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001890 }
Dan Gohman185cf032009-05-08 20:18:49 +00001891 // (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 +00001892 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001893 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001894 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1895 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1896 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1897 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001898 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001899 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001900 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1901 break;
1902 Operands.push_back(Op);
1903 }
1904 if (Operands.size() == A->getNumOperands())
1905 return getAddExpr(Operands);
1906 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001907 }
Dan Gohman185cf032009-05-08 20:18:49 +00001908
1909 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001910 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001911 Constant *LHSCV = LHSC->getValue();
1912 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001913 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001914 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001915 }
1916 }
1917
Dan Gohman1c343752009-06-27 21:21:31 +00001918 FoldingSetNodeID ID;
1919 ID.AddInteger(scUDivExpr);
1920 ID.AddPointer(LHS);
1921 ID.AddPointer(RHS);
1922 void *IP = 0;
1923 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1924 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001925 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001926 UniqueSCEVs.InsertNode(S, IP);
1927 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001928}
1929
1930
Dan Gohman6c0866c2009-05-24 23:45:28 +00001931/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1932/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001933const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001934 const SCEV *Step, const Loop *L,
1935 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001936 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001937 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001938 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001939 if (StepChrec->getLoop() == L) {
1940 Operands.insert(Operands.end(), StepChrec->op_begin(),
1941 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001942 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001943 }
1944
1945 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001946 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001947}
1948
Dan Gohman6c0866c2009-05-24 23:45:28 +00001949/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1950/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001951const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001952ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001953 const Loop *L,
1954 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001955 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001956#ifndef NDEBUG
1957 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1958 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1959 getEffectiveSCEVType(Operands[0]->getType()) &&
1960 "SCEVAddRecExpr operand types don't match!");
1961#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001962
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001963 if (Operands.back()->isZero()) {
1964 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001965 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001966 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001967
Dan Gohmanbc028532010-02-19 18:49:22 +00001968 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1969 // use that information to infer NUW and NSW flags. However, computing a
1970 // BE count requires calling getAddRecExpr, so we may not yet have a
1971 // meaningful BE count at this point (and if we don't, we'd be stuck
1972 // with a SCEVCouldNotCompute as the cached BE count).
1973
Dan Gohmana10756e2010-01-21 02:09:26 +00001974 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1975 if (!HasNUW && HasNSW) {
1976 bool All = true;
1977 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1978 if (!isKnownNonNegative(Operands[i])) {
1979 All = false;
1980 break;
1981 }
1982 if (All) HasNUW = true;
1983 }
1984
Dan Gohmand9cc7492008-08-08 18:33:12 +00001985 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001986 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001987 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001988 if (L->contains(NestedLoop->getHeader()) ?
1989 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1990 (!NestedLoop->contains(L->getHeader()) &&
1991 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001992 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001993 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001994 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001995 // AddRecs require their operands be loop-invariant with respect to their
1996 // loops. Don't perform this transformation if it would break this
1997 // requirement.
1998 bool AllInvariant = true;
1999 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2000 if (!Operands[i]->isLoopInvariant(L)) {
2001 AllInvariant = false;
2002 break;
2003 }
2004 if (AllInvariant) {
2005 NestedOperands[0] = getAddRecExpr(Operands, L);
2006 AllInvariant = true;
2007 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2008 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2009 AllInvariant = false;
2010 break;
2011 }
2012 if (AllInvariant)
2013 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002014 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002015 }
2016 // Reset Operands to its original state.
2017 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002018 }
2019 }
2020
Dan Gohman67847532010-01-19 22:27:22 +00002021 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2022 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002023 FoldingSetNodeID ID;
2024 ID.AddInteger(scAddRecExpr);
2025 ID.AddInteger(Operands.size());
2026 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2027 ID.AddPointer(Operands[i]);
2028 ID.AddPointer(L);
2029 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002030 SCEVAddRecExpr *S =
2031 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2032 if (!S) {
2033 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2034 new (S) SCEVAddRecExpr(ID, Operands, L);
2035 UniqueSCEVs.InsertNode(S, IP);
2036 }
Dan Gohman3645b012009-10-09 00:10:36 +00002037 if (HasNUW) S->setHasNoUnsignedWrap(true);
2038 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002039 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002040}
2041
Dan Gohman9311ef62009-06-24 14:49:00 +00002042const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2043 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002044 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002045 Ops.push_back(LHS);
2046 Ops.push_back(RHS);
2047 return getSMaxExpr(Ops);
2048}
2049
Dan Gohman0bba49c2009-07-07 17:06:11 +00002050const SCEV *
2051ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002052 assert(!Ops.empty() && "Cannot get empty smax!");
2053 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002054#ifndef NDEBUG
2055 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2056 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2057 getEffectiveSCEVType(Ops[0]->getType()) &&
2058 "SCEVSMaxExpr operand types don't match!");
2059#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002060
2061 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002062 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002063
2064 // If there are any constants, fold them together.
2065 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002066 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002067 ++Idx;
2068 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002069 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002070 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002071 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002072 APIntOps::smax(LHSC->getValue()->getValue(),
2073 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002074 Ops[0] = getConstant(Fold);
2075 Ops.erase(Ops.begin()+1); // Erase the folded element
2076 if (Ops.size() == 1) return Ops[0];
2077 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002078 }
2079
Dan Gohmane5aceed2009-06-24 14:46:22 +00002080 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002081 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2082 Ops.erase(Ops.begin());
2083 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002084 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2085 // If we have an smax with a constant maximum-int, it will always be
2086 // maximum-int.
2087 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002088 }
2089 }
2090
2091 if (Ops.size() == 1) return Ops[0];
2092
2093 // Find the first SMax
2094 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2095 ++Idx;
2096
2097 // Check to see if one of the operands is an SMax. If so, expand its operands
2098 // onto our operand list, and recurse to simplify.
2099 if (Idx < Ops.size()) {
2100 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002101 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002102 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2103 Ops.erase(Ops.begin()+Idx);
2104 DeletedSMax = true;
2105 }
2106
2107 if (DeletedSMax)
2108 return getSMaxExpr(Ops);
2109 }
2110
2111 // Okay, check to see if the same value occurs in the operand list twice. If
2112 // so, delete one. Since we sorted the list, these values are required to
2113 // be adjacent.
2114 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2115 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2116 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2117 --i; --e;
2118 }
2119
2120 if (Ops.size() == 1) return Ops[0];
2121
2122 assert(!Ops.empty() && "Reduced smax down to nothing!");
2123
Nick Lewycky3e630762008-02-20 06:48:22 +00002124 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002125 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002126 FoldingSetNodeID ID;
2127 ID.AddInteger(scSMaxExpr);
2128 ID.AddInteger(Ops.size());
2129 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2130 ID.AddPointer(Ops[i]);
2131 void *IP = 0;
2132 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2133 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002134 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002135 UniqueSCEVs.InsertNode(S, IP);
2136 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002137}
2138
Dan Gohman9311ef62009-06-24 14:49:00 +00002139const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2140 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002141 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002142 Ops.push_back(LHS);
2143 Ops.push_back(RHS);
2144 return getUMaxExpr(Ops);
2145}
2146
Dan Gohman0bba49c2009-07-07 17:06:11 +00002147const SCEV *
2148ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002149 assert(!Ops.empty() && "Cannot get empty umax!");
2150 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002151#ifndef NDEBUG
2152 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2153 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2154 getEffectiveSCEVType(Ops[0]->getType()) &&
2155 "SCEVUMaxExpr operand types don't match!");
2156#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002157
2158 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002159 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002160
2161 // If there are any constants, fold them together.
2162 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002163 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002164 ++Idx;
2165 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002166 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002167 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002168 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002169 APIntOps::umax(LHSC->getValue()->getValue(),
2170 RHSC->getValue()->getValue()));
2171 Ops[0] = getConstant(Fold);
2172 Ops.erase(Ops.begin()+1); // Erase the folded element
2173 if (Ops.size() == 1) return Ops[0];
2174 LHSC = cast<SCEVConstant>(Ops[0]);
2175 }
2176
Dan Gohmane5aceed2009-06-24 14:46:22 +00002177 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002178 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2179 Ops.erase(Ops.begin());
2180 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002181 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2182 // If we have an umax with a constant maximum-int, it will always be
2183 // maximum-int.
2184 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002185 }
2186 }
2187
2188 if (Ops.size() == 1) return Ops[0];
2189
2190 // Find the first UMax
2191 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2192 ++Idx;
2193
2194 // Check to see if one of the operands is a UMax. If so, expand its operands
2195 // onto our operand list, and recurse to simplify.
2196 if (Idx < Ops.size()) {
2197 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002198 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002199 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2200 Ops.erase(Ops.begin()+Idx);
2201 DeletedUMax = true;
2202 }
2203
2204 if (DeletedUMax)
2205 return getUMaxExpr(Ops);
2206 }
2207
2208 // Okay, check to see if the same value occurs in the operand list twice. If
2209 // so, delete one. Since we sorted the list, these values are required to
2210 // be adjacent.
2211 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2212 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2213 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2214 --i; --e;
2215 }
2216
2217 if (Ops.size() == 1) return Ops[0];
2218
2219 assert(!Ops.empty() && "Reduced umax down to nothing!");
2220
2221 // Okay, it looks like we really DO need a umax expr. Check to see if we
2222 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002223 FoldingSetNodeID ID;
2224 ID.AddInteger(scUMaxExpr);
2225 ID.AddInteger(Ops.size());
2226 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2227 ID.AddPointer(Ops[i]);
2228 void *IP = 0;
2229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2230 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002231 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002232 UniqueSCEVs.InsertNode(S, IP);
2233 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002234}
2235
Dan Gohman9311ef62009-06-24 14:49:00 +00002236const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2237 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002238 // ~smax(~x, ~y) == smin(x, y).
2239 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2240}
2241
Dan Gohman9311ef62009-06-24 14:49:00 +00002242const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2243 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002244 // ~umax(~x, ~y) == umin(x, y)
2245 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2246}
2247
Dan Gohman4f8eea82010-02-01 18:27:38 +00002248const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2249 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2250 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2251 C = ConstantFoldConstantExpression(CE, TD);
2252 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2253 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2254}
2255
2256const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2257 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2258 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2259 C = ConstantFoldConstantExpression(CE, TD);
2260 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2261 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2262}
2263
2264const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2265 unsigned FieldNo) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002266 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2268 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002269 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002270 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002271}
2272
Dan Gohman4f8eea82010-02-01 18:27:38 +00002273const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2274 Constant *FieldNo) {
2275 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002276 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2277 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohman4f8eea82010-02-01 18:27:38 +00002278 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002279 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002280}
2281
Dan Gohman0bba49c2009-07-07 17:06:11 +00002282const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002283 // Don't attempt to do anything other than create a SCEVUnknown object
2284 // here. createSCEV only calls getUnknown after checking for all other
2285 // interesting possibilities, and any other code that calls getUnknown
2286 // is doing so in order to hide a value from SCEV canonicalization.
2287
Dan Gohman1c343752009-06-27 21:21:31 +00002288 FoldingSetNodeID ID;
2289 ID.AddInteger(scUnknown);
2290 ID.AddPointer(V);
2291 void *IP = 0;
2292 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2293 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002294 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002295 UniqueSCEVs.InsertNode(S, IP);
2296 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002297}
2298
Chris Lattner53e677a2004-04-02 20:23:17 +00002299//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002300// Basic SCEV Analysis and PHI Idiom Recognition Code
2301//
2302
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002303/// isSCEVable - Test if values of the given type are analyzable within
2304/// the SCEV framework. This primarily includes integer types, and it
2305/// can optionally include pointer types if the ScalarEvolution class
2306/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002307bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002308 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002309 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002310}
2311
2312/// getTypeSizeInBits - Return the size in bits of the specified type,
2313/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002314uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002315 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2316
2317 // If we have a TargetData, use it!
2318 if (TD)
2319 return TD->getTypeSizeInBits(Ty);
2320
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002321 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002322 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002323 return Ty->getPrimitiveSizeInBits();
2324
2325 // The only other support type is pointer. Without TargetData, conservatively
2326 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002327 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002328 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002329}
2330
2331/// getEffectiveSCEVType - Return a type with the same bitwidth as
2332/// the given type and which represents how SCEV will treat the given
2333/// type, for which isSCEVable must return true. For pointer types,
2334/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002335const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002336 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2337
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002338 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002339 return Ty;
2340
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002341 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002342 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002343 if (TD) return TD->getIntPtrType(getContext());
2344
2345 // Without TargetData, conservatively assume pointers are 64-bit.
2346 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002347}
Chris Lattner53e677a2004-04-02 20:23:17 +00002348
Dan Gohman0bba49c2009-07-07 17:06:11 +00002349const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002350 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002351}
2352
Chris Lattner53e677a2004-04-02 20:23:17 +00002353/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2354/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002355const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002356 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002357
Dan Gohman0bba49c2009-07-07 17:06:11 +00002358 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002359 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002360 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002361 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002362 return S;
2363}
2364
Dan Gohman6bbcba12009-06-24 00:54:57 +00002365/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002366/// specified signed integer value and return a SCEV for the constant.
Dan Gohman32efba62010-02-04 02:43:51 +00002367const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002368 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002369 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002370}
2371
2372/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2373///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002374const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002375 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002376 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002378
2379 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002380 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002381 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002382 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002383}
2384
2385/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002386const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002387 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002388 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002389 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002390
2391 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002392 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002393 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002394 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002395 return getMinusSCEV(AllOnes, V);
2396}
2397
2398/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2399///
Dan Gohman9311ef62009-06-24 14:49:00 +00002400const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2401 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002402 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002403 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002404}
2405
2406/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2407/// input value to the specified type. If the type must be extended, it is zero
2408/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002409const SCEV *
2410ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002411 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002412 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002413 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2414 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002415 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002416 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002417 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002418 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002419 return getTruncateExpr(V, Ty);
2420 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002421}
2422
2423/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2424/// input value to the specified type. If the type must be extended, it is sign
2425/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002426const SCEV *
2427ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002428 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002429 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002430 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2431 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002432 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002433 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002434 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002435 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002436 return getTruncateExpr(V, Ty);
2437 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002438}
2439
Dan Gohman467c4302009-05-13 03:46:30 +00002440/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2441/// input value to the specified type. If the type must be extended, it is zero
2442/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002443const SCEV *
2444ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002445 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002446 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2447 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002448 "Cannot noop or zero extend with non-integer arguments!");
2449 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2450 "getNoopOrZeroExtend cannot truncate!");
2451 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2452 return V; // No conversion
2453 return getZeroExtendExpr(V, Ty);
2454}
2455
2456/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2457/// input value to the specified type. If the type must be extended, it is sign
2458/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002459const SCEV *
2460ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002461 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002462 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2463 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002464 "Cannot noop or sign extend with non-integer arguments!");
2465 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2466 "getNoopOrSignExtend cannot truncate!");
2467 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2468 return V; // No conversion
2469 return getSignExtendExpr(V, Ty);
2470}
2471
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002472/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2473/// the input value to the specified type. If the type must be extended,
2474/// it is extended with unspecified bits. The conversion must not be
2475/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002476const SCEV *
2477ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002478 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002479 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2480 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002481 "Cannot noop or any extend with non-integer arguments!");
2482 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2483 "getNoopOrAnyExtend cannot truncate!");
2484 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2485 return V; // No conversion
2486 return getAnyExtendExpr(V, Ty);
2487}
2488
Dan Gohman467c4302009-05-13 03:46:30 +00002489/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2490/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002491const SCEV *
2492ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002493 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002494 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2495 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002496 "Cannot truncate or noop with non-integer arguments!");
2497 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2498 "getTruncateOrNoop cannot extend!");
2499 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2500 return V; // No conversion
2501 return getTruncateExpr(V, Ty);
2502}
2503
Dan Gohmana334aa72009-06-22 00:31:57 +00002504/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2505/// the types using zero-extension, and then perform a umax operation
2506/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002507const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2508 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002509 const SCEV *PromotedLHS = LHS;
2510 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002511
2512 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2513 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2514 else
2515 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2516
2517 return getUMaxExpr(PromotedLHS, PromotedRHS);
2518}
2519
Dan Gohmanc9759e82009-06-22 15:03:27 +00002520/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2521/// the types using zero-extension, and then perform a umin operation
2522/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002523const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2524 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002525 const SCEV *PromotedLHS = LHS;
2526 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002527
2528 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2529 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2530 else
2531 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2532
2533 return getUMinExpr(PromotedLHS, PromotedRHS);
2534}
2535
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002536/// PushDefUseChildren - Push users of the given Instruction
2537/// onto the given Worklist.
2538static void
2539PushDefUseChildren(Instruction *I,
2540 SmallVectorImpl<Instruction *> &Worklist) {
2541 // Push the def-use children onto the Worklist stack.
2542 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2543 UI != UE; ++UI)
2544 Worklist.push_back(cast<Instruction>(UI));
2545}
2546
2547/// ForgetSymbolicValue - This looks up computed SCEV values for all
2548/// instructions that depend on the given instruction and removes them from
2549/// the Scalars map if they reference SymName. This is used during PHI
2550/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002551void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002552ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2553 SmallVector<Instruction *, 16> Worklist;
2554 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002555
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002556 SmallPtrSet<Instruction *, 8> Visited;
2557 Visited.insert(I);
2558 while (!Worklist.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002559 I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002560 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002561
Dan Gohman5d984912009-12-18 01:14:11 +00002562 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002563 Scalars.find(static_cast<Value *>(I));
2564 if (It != Scalars.end()) {
2565 // Short-circuit the def-use traversal if the symbolic name
2566 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002567 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002568 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002569
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002570 // SCEVUnknown for a PHI either means that it has an unrecognized
2571 // structure, or it's a PHI that's in the progress of being computed
2572 // by createNodeForPHI. In the former case, additional loop trip
2573 // count information isn't going to change anything. In the later
2574 // case, createNodeForPHI will perform the necessary updates on its
2575 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002576 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2577 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002578 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002579 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002580 }
2581
2582 PushDefUseChildren(I, Worklist);
2583 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002584}
Chris Lattner53e677a2004-04-02 20:23:17 +00002585
2586/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2587/// a loop header, making it a potential recurrence, or it doesn't.
2588///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002589const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002590 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002591 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002592 if (L->getHeader() == PN->getParent()) {
2593 // If it lives in the loop header, it has two incoming values, one
2594 // from outside the loop, and one from inside.
2595 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2596 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002597
Chris Lattner53e677a2004-04-02 20:23:17 +00002598 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002599 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002600 assert(Scalars.find(PN) == Scalars.end() &&
2601 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002602 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002603
2604 // Using this symbolic name for the PHI, analyze the value coming around
2605 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002606 Value *BEValueV = PN->getIncomingValue(BackEdge);
2607 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002608
2609 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2610 // has a special value for the first iteration of the loop.
2611
2612 // If the value coming around the backedge is an add with the symbolic
2613 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002614 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002615 // If there is a single occurrence of the symbolic value, replace it
2616 // with a recurrence.
2617 unsigned FoundIndex = Add->getNumOperands();
2618 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2619 if (Add->getOperand(i) == SymbolicName)
2620 if (FoundIndex == e) {
2621 FoundIndex = i;
2622 break;
2623 }
2624
2625 if (FoundIndex != Add->getNumOperands()) {
2626 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002627 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002628 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2629 if (i != FoundIndex)
2630 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002631 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002632
2633 // This is not a valid addrec if the step amount is varying each
2634 // loop iteration, but is not itself an addrec in this loop.
2635 if (Accum->isLoopInvariant(L) ||
2636 (isa<SCEVAddRecExpr>(Accum) &&
2637 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002638 bool HasNUW = false;
2639 bool HasNSW = false;
2640
2641 // If the increment doesn't overflow, then neither the addrec nor
2642 // the post-increment will overflow.
2643 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2644 if (OBO->hasNoUnsignedWrap())
2645 HasNUW = true;
2646 if (OBO->hasNoSignedWrap())
2647 HasNSW = true;
2648 }
2649
Dan Gohman64a845e2009-06-24 04:48:43 +00002650 const SCEV *StartVal =
2651 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002652 const SCEV *PHISCEV =
2653 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002654
Dan Gohmana10756e2010-01-21 02:09:26 +00002655 // Since the no-wrap flags are on the increment, they apply to the
2656 // post-incremented value as well.
2657 if (Accum->isLoopInvariant(L))
2658 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2659 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002660
2661 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002662 // to be symbolic. We now need to go back and purge all of the
2663 // entries for the scalars that use the symbolic expression.
2664 ForgetSymbolicName(PN, SymbolicName);
2665 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002666 return PHISCEV;
2667 }
2668 }
Dan Gohman622ed672009-05-04 22:02:23 +00002669 } else if (const SCEVAddRecExpr *AddRec =
2670 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002671 // Otherwise, this could be a loop like this:
2672 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2673 // In this case, j = {1,+,1} and BEValue is j.
2674 // Because the other in-value of i (0) fits the evolution of BEValue
2675 // i really is an addrec evolution.
2676 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002677 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002678
2679 // If StartVal = j.start - j.stride, we can use StartVal as the
2680 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002681 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002682 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002683 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002684 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002685
2686 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002687 // to be symbolic. We now need to go back and purge all of the
2688 // entries for the scalars that use the symbolic expression.
2689 ForgetSymbolicName(PN, SymbolicName);
2690 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002691 return PHISCEV;
2692 }
2693 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002694 }
2695
2696 return SymbolicName;
2697 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002698
Dan Gohmana653fc52009-07-14 14:06:25 +00002699 // It's tempting to recognize PHIs with a unique incoming value, however
2700 // this leads passes like indvars to break LCSSA form. Fortunately, such
2701 // PHIs are rare, as instcombine zaps them.
2702
Chris Lattner53e677a2004-04-02 20:23:17 +00002703 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002704 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002705}
2706
Dan Gohman26466c02009-05-08 20:26:55 +00002707/// createNodeForGEP - Expand GEP instructions into add and multiply
2708/// operations. This allows them to be analyzed by regular SCEV code.
2709///
Dan Gohmand281ed22009-12-18 02:09:29 +00002710const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002711
Dan Gohmand281ed22009-12-18 02:09:29 +00002712 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002713 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002714 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002715 // Don't attempt to analyze GEPs over unsized objects.
2716 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2717 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002718 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002719 gep_type_iterator GTI = gep_type_begin(GEP);
2720 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2721 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002722 I != E; ++I) {
2723 Value *Index = *I;
2724 // Compute the (potentially symbolic) offset in bytes for this index.
2725 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2726 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002727 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002728 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002729 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002730 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002731 } else {
2732 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002733 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman8db08df2010-02-02 01:38:49 +00002734 // Getelementptr indicies are signed.
2735 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002736 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002737 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002738 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2739 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2740 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002741 }
2742 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002743 return getAddExpr(getSCEV(Base), TotalOffset,
2744 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002745}
2746
Nick Lewycky83bb0052007-11-22 07:59:40 +00002747/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2748/// guaranteed to end in (at every loop iteration). It is, at the same time,
2749/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2750/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002751uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002752ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002753 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002754 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002755
Dan Gohman622ed672009-05-04 22:02:23 +00002756 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002757 return std::min(GetMinTrailingZeros(T->getOperand()),
2758 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002759
Dan Gohman622ed672009-05-04 22:02:23 +00002760 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002761 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2762 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2763 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002764 }
2765
Dan Gohman622ed672009-05-04 22:02:23 +00002766 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002767 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2768 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2769 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002770 }
2771
Dan Gohman622ed672009-05-04 22:02:23 +00002772 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002773 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002774 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002775 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002776 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002777 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002778 }
2779
Dan Gohman622ed672009-05-04 22:02:23 +00002780 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002781 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002782 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2783 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002784 for (unsigned i = 1, e = M->getNumOperands();
2785 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002786 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002787 BitWidth);
2788 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002789 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002790
Dan Gohman622ed672009-05-04 22:02:23 +00002791 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002792 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002793 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002794 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002795 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002796 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002797 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002798
Dan Gohman622ed672009-05-04 22:02:23 +00002799 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002800 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002801 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002802 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002803 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002804 return MinOpRes;
2805 }
2806
Dan Gohman622ed672009-05-04 22:02:23 +00002807 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002808 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002809 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002810 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002811 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002812 return MinOpRes;
2813 }
2814
Dan Gohman2c364ad2009-06-19 23:29:04 +00002815 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2816 // For a SCEVUnknown, ask ValueTracking.
2817 unsigned BitWidth = getTypeSizeInBits(U->getType());
2818 APInt Mask = APInt::getAllOnesValue(BitWidth);
2819 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2820 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2821 return Zeros.countTrailingOnes();
2822 }
2823
2824 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002825 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002826}
Chris Lattner53e677a2004-04-02 20:23:17 +00002827
Dan Gohman85b05a22009-07-13 21:35:55 +00002828/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2829///
2830ConstantRange
2831ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002832
2833 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002834 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002835
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002836 unsigned BitWidth = getTypeSizeInBits(S->getType());
2837 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2838
2839 // If the value has known zeros, the maximum unsigned value will have those
2840 // known zeros as well.
2841 uint32_t TZ = GetMinTrailingZeros(S);
2842 if (TZ != 0)
2843 ConservativeResult =
2844 ConstantRange(APInt::getMinValue(BitWidth),
2845 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2846
Dan Gohman85b05a22009-07-13 21:35:55 +00002847 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2848 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2849 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2850 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002851 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002852 }
2853
2854 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2855 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2856 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2857 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002858 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002859 }
2860
2861 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2862 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2863 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2864 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002865 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002866 }
2867
2868 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2869 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2870 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2871 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002872 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002873 }
2874
2875 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2876 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2877 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002878 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002879 }
2880
2881 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2882 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002883 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002884 }
2885
2886 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2887 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002888 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002889 }
2890
2891 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2892 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002893 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002894 }
2895
Dan Gohman85b05a22009-07-13 21:35:55 +00002896 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002897 // If there's no unsigned wrap, the value will never be less than its
2898 // initial value.
2899 if (AddRec->hasNoUnsignedWrap())
2900 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2901 ConservativeResult =
2902 ConstantRange(C->getValue()->getValue(),
2903 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002904
2905 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002906 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002907 const Type *Ty = AddRec->getType();
2908 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002909 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2910 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002911 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2912
2913 const SCEV *Start = AddRec->getStart();
2914 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2915
2916 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002917 if (!AddRec->hasNoUnsignedWrap())
2918 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002919
2920 ConstantRange StartRange = getUnsignedRange(Start);
2921 ConstantRange EndRange = getUnsignedRange(End);
2922 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2923 EndRange.getUnsignedMin());
2924 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2925 EndRange.getUnsignedMax());
2926 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002927 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002928 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002929 }
2930 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002931
2932 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002933 }
2934
2935 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2936 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002937 APInt Mask = APInt::getAllOnesValue(BitWidth);
2938 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2939 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002940 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002941 return ConservativeResult;
2942 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002943 }
2944
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002945 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946}
2947
Dan Gohman85b05a22009-07-13 21:35:55 +00002948/// getSignedRange - Determine the signed range for a particular SCEV.
2949///
2950ConstantRange
2951ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002952
Dan Gohman85b05a22009-07-13 21:35:55 +00002953 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2954 return ConstantRange(C->getValue()->getValue());
2955
Dan Gohman52fddd32010-01-26 04:40:18 +00002956 unsigned BitWidth = getTypeSizeInBits(S->getType());
2957 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2958
2959 // If the value has known zeros, the maximum signed value will have those
2960 // known zeros as well.
2961 uint32_t TZ = GetMinTrailingZeros(S);
2962 if (TZ != 0)
2963 ConservativeResult =
2964 ConstantRange(APInt::getSignedMinValue(BitWidth),
2965 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2966
Dan Gohman85b05a22009-07-13 21:35:55 +00002967 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2968 ConstantRange X = getSignedRange(Add->getOperand(0));
2969 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2970 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002971 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002972 }
2973
Dan Gohman85b05a22009-07-13 21:35:55 +00002974 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2975 ConstantRange X = getSignedRange(Mul->getOperand(0));
2976 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2977 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002978 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002979 }
2980
Dan Gohman85b05a22009-07-13 21:35:55 +00002981 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2982 ConstantRange X = getSignedRange(SMax->getOperand(0));
2983 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2984 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002985 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002986 }
Dan Gohman62849c02009-06-24 01:05:09 +00002987
Dan Gohman85b05a22009-07-13 21:35:55 +00002988 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2989 ConstantRange X = getSignedRange(UMax->getOperand(0));
2990 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2991 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002992 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002993 }
Dan Gohman62849c02009-06-24 01:05:09 +00002994
Dan Gohman85b05a22009-07-13 21:35:55 +00002995 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2996 ConstantRange X = getSignedRange(UDiv->getLHS());
2997 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00002998 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002999 }
Dan Gohman62849c02009-06-24 01:05:09 +00003000
Dan Gohman85b05a22009-07-13 21:35:55 +00003001 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3002 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003003 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003004 }
3005
3006 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3007 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003008 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003009 }
3010
3011 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3012 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003013 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003014 }
3015
Dan Gohman85b05a22009-07-13 21:35:55 +00003016 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003017 // If there's no signed wrap, and all the operands have the same sign or
3018 // zero, the value won't ever change sign.
3019 if (AddRec->hasNoSignedWrap()) {
3020 bool AllNonNeg = true;
3021 bool AllNonPos = true;
3022 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3023 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3024 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3025 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003026 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003027 ConservativeResult = ConservativeResult.intersectWith(
3028 ConstantRange(APInt(BitWidth, 0),
3029 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003030 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003031 ConservativeResult = ConservativeResult.intersectWith(
3032 ConstantRange(APInt::getSignedMinValue(BitWidth),
3033 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003034 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003035
3036 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003037 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003038 const Type *Ty = AddRec->getType();
3039 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003040 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3041 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003042 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3043
3044 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003045 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3046
3047 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003048 if (!AddRec->hasNoSignedWrap())
3049 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003050
3051 ConstantRange StartRange = getSignedRange(Start);
3052 ConstantRange EndRange = getSignedRange(End);
3053 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3054 EndRange.getSignedMin());
3055 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3056 EndRange.getSignedMax());
3057 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003058 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003059 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003060 }
Dan Gohman62849c02009-06-24 01:05:09 +00003061 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003062
3063 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003064 }
3065
Dan Gohman2c364ad2009-06-19 23:29:04 +00003066 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3067 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003068 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003069 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003070 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3071 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003072 return ConservativeResult;
3073 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003074 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003075 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003076 }
3077
Dan Gohman52fddd32010-01-26 04:40:18 +00003078 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003079}
3080
Chris Lattner53e677a2004-04-02 20:23:17 +00003081/// createSCEV - We know that there is no SCEV for the specified value.
3082/// Analyze the expression.
3083///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003084const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003085 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003086 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003087
Dan Gohman6c459a22008-06-22 19:56:46 +00003088 unsigned Opcode = Instruction::UserOp1;
3089 if (Instruction *I = dyn_cast<Instruction>(V))
3090 Opcode = I->getOpcode();
3091 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3092 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003093 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3094 return getConstant(CI);
3095 else if (isa<ConstantPointerNull>(V))
3096 return getIntegerSCEV(0, V->getType());
3097 else if (isa<UndefValue>(V))
3098 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003099 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3100 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003101 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003102 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003103
Dan Gohmanca178902009-07-17 20:47:02 +00003104 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003105 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003106 case Instruction::Add:
3107 // Don't transfer the NSW and NUW bits from the Add instruction to the
3108 // Add expression, because the Instruction may be guarded by control
3109 // flow and the no-overflow bits may not be valid for the expression in
3110 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003111 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003112 getSCEV(U->getOperand(1)));
3113 case Instruction::Mul:
3114 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3115 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003116 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003117 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003118 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003119 return getUDivExpr(getSCEV(U->getOperand(0)),
3120 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003121 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003122 return getMinusSCEV(getSCEV(U->getOperand(0)),
3123 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003124 case Instruction::And:
3125 // For an expression like x&255 that merely masks off the high bits,
3126 // use zext(trunc(x)) as the SCEV expression.
3127 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003128 if (CI->isNullValue())
3129 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003130 if (CI->isAllOnesValue())
3131 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003132 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003133
3134 // Instcombine's ShrinkDemandedConstant may strip bits out of
3135 // constants, obscuring what would otherwise be a low-bits mask.
3136 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3137 // knew about to reconstruct a low-bits mask value.
3138 unsigned LZ = A.countLeadingZeros();
3139 unsigned BitWidth = A.getBitWidth();
3140 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3141 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3142 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3143
3144 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3145
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003146 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003147 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003148 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003149 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003150 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003151 }
3152 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003153
Dan Gohman6c459a22008-06-22 19:56:46 +00003154 case Instruction::Or:
3155 // If the RHS of the Or is a constant, we may have something like:
3156 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3157 // optimizations will transparently handle this case.
3158 //
3159 // In order for this transformation to be safe, the LHS must be of the
3160 // form X*(2^n) and the Or constant must be less than 2^n.
3161 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003162 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003163 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003164 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003165 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3166 // Build a plain add SCEV.
3167 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3168 // If the LHS of the add was an addrec and it has no-wrap flags,
3169 // transfer the no-wrap flags, since an or won't introduce a wrap.
3170 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3171 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3172 if (OldAR->hasNoUnsignedWrap())
3173 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3174 if (OldAR->hasNoSignedWrap())
3175 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3176 }
3177 return S;
3178 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003179 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003180 break;
3181 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003182 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003183 // If the RHS of the xor is a signbit, then this is just an add.
3184 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003185 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003186 return getAddExpr(getSCEV(U->getOperand(0)),
3187 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003188
3189 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003190 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003191 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003192
3193 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3194 // This is a variant of the check for xor with -1, and it handles
3195 // the case where instcombine has trimmed non-demanded bits out
3196 // of an xor with -1.
3197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3198 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3199 if (BO->getOpcode() == Instruction::And &&
3200 LCI->getValue() == CI->getValue())
3201 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003202 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003203 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003204 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003205 const Type *Z0Ty = Z0->getType();
3206 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3207
3208 // If C is a low-bits mask, the zero extend is zerving to
3209 // mask off the high bits. Complement the operand and
3210 // re-apply the zext.
3211 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3212 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3213
3214 // If C is a single bit, it may be in the sign-bit position
3215 // before the zero-extend. In this case, represent the xor
3216 // using an add, which is equivalent, and re-apply the zext.
3217 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3218 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3219 Trunc.isSignBit())
3220 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3221 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003222 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003223 }
3224 break;
3225
3226 case Instruction::Shl:
3227 // Turn shift left of a constant amount into a multiply.
3228 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003229 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003230 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003231 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003232 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003233 }
3234 break;
3235
Nick Lewycky01eaf802008-07-07 06:15:49 +00003236 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003237 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003238 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003239 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003240 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003241 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003242 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003243 }
3244 break;
3245
Dan Gohman4ee29af2009-04-21 02:26:00 +00003246 case Instruction::AShr:
3247 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3248 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3249 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3250 if (L->getOpcode() == Instruction::Shl &&
3251 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003252 unsigned BitWidth = getTypeSizeInBits(U->getType());
3253 uint64_t Amt = BitWidth - CI->getZExtValue();
3254 if (Amt == BitWidth)
3255 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3256 if (Amt > BitWidth)
3257 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003258 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003259 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003260 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003261 U->getType());
3262 }
3263 break;
3264
Dan Gohman6c459a22008-06-22 19:56:46 +00003265 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003266 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003267
3268 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003269 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003270
3271 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003272 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003273
3274 case Instruction::BitCast:
3275 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003276 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003277 return getSCEV(U->getOperand(0));
3278 break;
3279
Dan Gohman4f8eea82010-02-01 18:27:38 +00003280 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3281 // lead to pointer expressions which cannot safely be expanded to GEPs,
3282 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3283 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003284
Dan Gohman26466c02009-05-08 20:26:55 +00003285 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003286 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003287
Dan Gohman6c459a22008-06-22 19:56:46 +00003288 case Instruction::PHI:
3289 return createNodeForPHI(cast<PHINode>(U));
3290
3291 case Instruction::Select:
3292 // This could be a smax or umax that was lowered earlier.
3293 // Try to recover it.
3294 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3295 Value *LHS = ICI->getOperand(0);
3296 Value *RHS = ICI->getOperand(1);
3297 switch (ICI->getPredicate()) {
3298 case ICmpInst::ICMP_SLT:
3299 case ICmpInst::ICMP_SLE:
3300 std::swap(LHS, RHS);
3301 // fall through
3302 case ICmpInst::ICMP_SGT:
3303 case ICmpInst::ICMP_SGE:
3304 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003305 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003306 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003307 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003308 break;
3309 case ICmpInst::ICMP_ULT:
3310 case ICmpInst::ICMP_ULE:
3311 std::swap(LHS, RHS);
3312 // fall through
3313 case ICmpInst::ICMP_UGT:
3314 case ICmpInst::ICMP_UGE:
3315 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003316 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003317 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003318 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003319 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003320 case ICmpInst::ICMP_NE:
3321 // n != 0 ? n : 1 -> umax(n, 1)
3322 if (LHS == U->getOperand(1) &&
3323 isa<ConstantInt>(U->getOperand(2)) &&
3324 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3325 isa<ConstantInt>(RHS) &&
3326 cast<ConstantInt>(RHS)->isZero())
3327 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3328 break;
3329 case ICmpInst::ICMP_EQ:
3330 // n == 0 ? 1 : n -> umax(n, 1)
3331 if (LHS == U->getOperand(2) &&
3332 isa<ConstantInt>(U->getOperand(1)) &&
3333 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3334 isa<ConstantInt>(RHS) &&
3335 cast<ConstantInt>(RHS)->isZero())
3336 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3337 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003338 default:
3339 break;
3340 }
3341 }
3342
3343 default: // We cannot analyze this expression.
3344 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003345 }
3346
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003347 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003348}
3349
3350
3351
3352//===----------------------------------------------------------------------===//
3353// Iteration Count Computation Code
3354//
3355
Dan Gohman46bdfb02009-02-24 18:55:53 +00003356/// getBackedgeTakenCount - If the specified loop has a predictable
3357/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3358/// object. The backedge-taken count is the number of times the loop header
3359/// will be branched to from within the loop. This is one less than the
3360/// trip count of the loop, since it doesn't count the first iteration,
3361/// when the header is branched to from outside the loop.
3362///
3363/// Note that it is not valid to call this method on a loop without a
3364/// loop-invariant backedge-taken count (see
3365/// hasLoopInvariantBackedgeTakenCount).
3366///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003367const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003368 return getBackedgeTakenInfo(L).Exact;
3369}
3370
3371/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3372/// return the least SCEV value that is known never to be less than the
3373/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003374const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003375 return getBackedgeTakenInfo(L).Max;
3376}
3377
Dan Gohman59ae6b92009-07-08 19:23:34 +00003378/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3379/// onto the given Worklist.
3380static void
3381PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3382 BasicBlock *Header = L->getHeader();
3383
3384 // Push all Loop-header PHIs onto the Worklist stack.
3385 for (BasicBlock::iterator I = Header->begin();
3386 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3387 Worklist.push_back(PN);
3388}
3389
Dan Gohmana1af7572009-04-30 20:47:05 +00003390const ScalarEvolution::BackedgeTakenInfo &
3391ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003392 // Initially insert a CouldNotCompute for this loop. If the insertion
3393 // succeeds, procede to actually compute a backedge-taken count and
3394 // update the value. The temporary CouldNotCompute value tells SCEV
3395 // code elsewhere that it shouldn't attempt to request a new
3396 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003397 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003398 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3399 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003400 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3401 if (BECount.Exact != getCouldNotCompute()) {
3402 assert(BECount.Exact->isLoopInvariant(L) &&
3403 BECount.Max->isLoopInvariant(L) &&
3404 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003405 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003406
Dan Gohman01ecca22009-04-27 20:16:15 +00003407 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003408 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003409 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003410 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003411 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003412 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003413 if (isa<PHINode>(L->getHeader()->begin()))
3414 // Only count loops that have phi nodes as not being computable.
3415 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003416 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003417
3418 // Now that we know more about the trip count for this loop, forget any
3419 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003420 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003421 // information. This is similar to the code in forgetLoop, except that
3422 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003423 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003424 SmallVector<Instruction *, 16> Worklist;
3425 PushLoopPHIs(L, Worklist);
3426
3427 SmallPtrSet<Instruction *, 8> Visited;
3428 while (!Worklist.empty()) {
3429 Instruction *I = Worklist.pop_back_val();
3430 if (!Visited.insert(I)) continue;
3431
Dan Gohman5d984912009-12-18 01:14:11 +00003432 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003433 Scalars.find(static_cast<Value *>(I));
3434 if (It != Scalars.end()) {
3435 // SCEVUnknown for a PHI either means that it has an unrecognized
3436 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003437 // by createNodeForPHI. In the former case, additional loop trip
3438 // count information isn't going to change anything. In the later
3439 // case, createNodeForPHI will perform the necessary updates on its
3440 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003441 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3442 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003443 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003444 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003445 if (PHINode *PN = dyn_cast<PHINode>(I))
3446 ConstantEvolutionLoopExitValue.erase(PN);
3447 }
3448
3449 PushDefUseChildren(I, Worklist);
3450 }
3451 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003452 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003453 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003454}
3455
Dan Gohman4c7279a2009-10-31 15:04:55 +00003456/// forgetLoop - This method should be called by the client when it has
3457/// changed a loop in a way that may effect ScalarEvolution's ability to
3458/// compute a trip count, or if the loop is deleted.
3459void ScalarEvolution::forgetLoop(const Loop *L) {
3460 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003461 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003462
Dan Gohman4c7279a2009-10-31 15:04:55 +00003463 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003464 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003465 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003466
Dan Gohman59ae6b92009-07-08 19:23:34 +00003467 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003468 while (!Worklist.empty()) {
3469 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003470 if (!Visited.insert(I)) continue;
3471
Dan Gohman5d984912009-12-18 01:14:11 +00003472 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003473 Scalars.find(static_cast<Value *>(I));
3474 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003475 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003476 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003477 if (PHINode *PN = dyn_cast<PHINode>(I))
3478 ConstantEvolutionLoopExitValue.erase(PN);
3479 }
3480
3481 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003482 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003483}
3484
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003485/// forgetValue - This method should be called by the client when it has
3486/// changed a value in a way that may effect its value, or which may
3487/// disconnect it from a def-use chain linking it to a loop.
3488void ScalarEvolution::forgetValue(Value *V) {
3489 Instruction *I = dyn_cast<Instruction>(V);
3490 if (!I) return;
3491
3492 // Drop information about expressions based on loop-header PHIs.
3493 SmallVector<Instruction *, 16> Worklist;
3494 Worklist.push_back(I);
3495
3496 SmallPtrSet<Instruction *, 8> Visited;
3497 while (!Worklist.empty()) {
3498 I = Worklist.pop_back_val();
3499 if (!Visited.insert(I)) continue;
3500
3501 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3502 Scalars.find(static_cast<Value *>(I));
3503 if (It != Scalars.end()) {
3504 ValuesAtScopes.erase(It->second);
3505 Scalars.erase(It);
3506 if (PHINode *PN = dyn_cast<PHINode>(I))
3507 ConstantEvolutionLoopExitValue.erase(PN);
3508 }
3509
3510 PushDefUseChildren(I, Worklist);
3511 }
3512}
3513
Dan Gohman46bdfb02009-02-24 18:55:53 +00003514/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3515/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003516ScalarEvolution::BackedgeTakenInfo
3517ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003518 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003519 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003520
Dan Gohmana334aa72009-06-22 00:31:57 +00003521 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003522 const SCEV *BECount = getCouldNotCompute();
3523 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003524 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003525 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3526 BackedgeTakenInfo NewBTI =
3527 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003528
Dan Gohman1c343752009-06-27 21:21:31 +00003529 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003530 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003531 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003532 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003533 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003534 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003535 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003536 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003537 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003538 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003539 }
Dan Gohman1c343752009-06-27 21:21:31 +00003540 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003541 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003542 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003543 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003544 }
3545
3546 return BackedgeTakenInfo(BECount, MaxBECount);
3547}
3548
3549/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3550/// of the specified loop will execute if it exits via the specified block.
3551ScalarEvolution::BackedgeTakenInfo
3552ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3553 BasicBlock *ExitingBlock) {
3554
3555 // Okay, we've chosen an exiting block. See what condition causes us to
3556 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003557 //
3558 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003559 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003560 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003561 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003562
Chris Lattner8b0e3602007-01-07 02:24:26 +00003563 // At this point, we know we have a conditional branch that determines whether
3564 // the loop is exited. However, we don't know if the branch is executed each
3565 // time through the loop. If not, then the execution count of the branch will
3566 // not be equal to the trip count of the loop.
3567 //
3568 // Currently we check for this by checking to see if the Exit branch goes to
3569 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003570 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003571 // loop header. This is common for un-rotated loops.
3572 //
3573 // If both of those tests fail, walk up the unique predecessor chain to the
3574 // header, stopping if there is an edge that doesn't exit the loop. If the
3575 // header is reached, the execution count of the branch will be equal to the
3576 // trip count of the loop.
3577 //
3578 // More extensive analysis could be done to handle more cases here.
3579 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003580 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003581 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003582 ExitBr->getParent() != L->getHeader()) {
3583 // The simple checks failed, try climbing the unique predecessor chain
3584 // up to the header.
3585 bool Ok = false;
3586 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3587 BasicBlock *Pred = BB->getUniquePredecessor();
3588 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003589 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003590 TerminatorInst *PredTerm = Pred->getTerminator();
3591 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3592 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3593 if (PredSucc == BB)
3594 continue;
3595 // If the predecessor has a successor that isn't BB and isn't
3596 // outside the loop, assume the worst.
3597 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003598 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003599 }
3600 if (Pred == L->getHeader()) {
3601 Ok = true;
3602 break;
3603 }
3604 BB = Pred;
3605 }
3606 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003607 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003608 }
3609
3610 // Procede to the next level to examine the exit condition expression.
3611 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3612 ExitBr->getSuccessor(0),
3613 ExitBr->getSuccessor(1));
3614}
3615
3616/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3617/// backedge of the specified loop will execute if its exit condition
3618/// were a conditional branch of ExitCond, TBB, and FBB.
3619ScalarEvolution::BackedgeTakenInfo
3620ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3621 Value *ExitCond,
3622 BasicBlock *TBB,
3623 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003624 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003625 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3626 if (BO->getOpcode() == Instruction::And) {
3627 // Recurse on the operands of the and.
3628 BackedgeTakenInfo BTI0 =
3629 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3630 BackedgeTakenInfo BTI1 =
3631 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003632 const SCEV *BECount = getCouldNotCompute();
3633 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003634 if (L->contains(TBB)) {
3635 // Both conditions must be true for the loop to continue executing.
3636 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003637 if (BTI0.Exact == getCouldNotCompute() ||
3638 BTI1.Exact == getCouldNotCompute())
3639 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003640 else
3641 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003642 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003643 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003644 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003645 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003646 else
3647 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003648 } else {
3649 // Both conditions must be true for the loop to exit.
3650 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003651 if (BTI0.Exact != getCouldNotCompute() &&
3652 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003653 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003654 if (BTI0.Max != getCouldNotCompute() &&
3655 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003656 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3657 }
3658
3659 return BackedgeTakenInfo(BECount, MaxBECount);
3660 }
3661 if (BO->getOpcode() == Instruction::Or) {
3662 // Recurse on the operands of the or.
3663 BackedgeTakenInfo BTI0 =
3664 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3665 BackedgeTakenInfo BTI1 =
3666 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003667 const SCEV *BECount = getCouldNotCompute();
3668 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003669 if (L->contains(FBB)) {
3670 // Both conditions must be false for the loop to continue executing.
3671 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003672 if (BTI0.Exact == getCouldNotCompute() ||
3673 BTI1.Exact == getCouldNotCompute())
3674 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003675 else
3676 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003677 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003678 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003679 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003680 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003681 else
3682 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003683 } else {
3684 // Both conditions must be false for the loop to exit.
3685 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003686 if (BTI0.Exact != getCouldNotCompute() &&
3687 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003688 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003689 if (BTI0.Max != getCouldNotCompute() &&
3690 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003691 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3692 }
3693
3694 return BackedgeTakenInfo(BECount, MaxBECount);
3695 }
3696 }
3697
3698 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3699 // Procede to the next level to examine the icmp.
3700 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3701 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702
Dan Gohman00cb5b72010-02-19 18:12:07 +00003703 // Check for a constant condition. These are normally stripped out by
3704 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3705 // preserve the CFG and is temporarily leaving constant conditions
3706 // in place.
3707 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3708 if (L->contains(FBB) == !CI->getZExtValue())
3709 // The backedge is always taken.
3710 return getCouldNotCompute();
3711 else
3712 // The backedge is never taken.
3713 return getIntegerSCEV(0, CI->getType());
3714 }
3715
Eli Friedman361e54d2009-05-09 12:32:42 +00003716 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003717 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3718}
3719
3720/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3721/// backedge of the specified loop will execute if its exit condition
3722/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3723ScalarEvolution::BackedgeTakenInfo
3724ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3725 ICmpInst *ExitCond,
3726 BasicBlock *TBB,
3727 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003728
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 // If the condition was exit on true, convert the condition to exit on false
3730 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003731 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003732 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003733 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003734 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003735
3736 // Handle common loops like: for (X = "string"; *X; ++X)
3737 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3738 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003739 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003740 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003741 if (ItCnt.hasAnyInfo())
3742 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003743 }
3744
Dan Gohman0bba49c2009-07-07 17:06:11 +00003745 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3746 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003747
3748 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003749 LHS = getSCEVAtScope(LHS, L);
3750 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003751
Dan Gohman64a845e2009-06-24 04:48:43 +00003752 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003753 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003754 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3755 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003756 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003757 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003758 }
3759
Chris Lattner53e677a2004-04-02 20:23:17 +00003760 // If we have a comparison of a chrec against a constant, try to use value
3761 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003762 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3763 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003764 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003765 // Form the constant range.
3766 ConstantRange CompRange(
3767 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003768
Dan Gohman0bba49c2009-07-07 17:06:11 +00003769 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003770 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003771 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003772
Chris Lattner53e677a2004-04-02 20:23:17 +00003773 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003774 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003775 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003776 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3777 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003778 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003779 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003780 case ICmpInst::ICMP_EQ: { // while (X == Y)
3781 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003782 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3783 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003784 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 }
3786 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003787 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3788 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003789 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 }
3791 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003792 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3793 getNotSCEV(RHS), L, true);
3794 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003795 break;
3796 }
3797 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003798 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3799 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003800 break;
3801 }
3802 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003803 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3804 getNotSCEV(RHS), L, false);
3805 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003806 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003807 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003808 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003809#if 0
David Greene25e0e872009-12-23 22:18:14 +00003810 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003811 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003812 dbgs() << "[unsigned] ";
3813 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003814 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003815 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003816#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003817 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003818 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003819 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003820 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003821}
3822
Chris Lattner673e02b2004-10-12 01:49:27 +00003823static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003824EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3825 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003826 const SCEV *InVal = SE.getConstant(C);
3827 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003828 assert(isa<SCEVConstant>(Val) &&
3829 "Evaluation of SCEV at constant didn't fold correctly?");
3830 return cast<SCEVConstant>(Val)->getValue();
3831}
3832
3833/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3834/// and a GEP expression (missing the pointer index) indexing into it, return
3835/// the addressed element of the initializer or null if the index expression is
3836/// invalid.
3837static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003838GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003839 const std::vector<ConstantInt*> &Indices) {
3840 Constant *Init = GV->getInitializer();
3841 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003842 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003843 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3844 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3845 Init = cast<Constant>(CS->getOperand(Idx));
3846 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3847 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3848 Init = cast<Constant>(CA->getOperand(Idx));
3849 } else if (isa<ConstantAggregateZero>(Init)) {
3850 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3851 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003852 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003853 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3854 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003855 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003856 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003857 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003858 }
3859 return 0;
3860 } else {
3861 return 0; // Unknown initializer type
3862 }
3863 }
3864 return Init;
3865}
3866
Dan Gohman46bdfb02009-02-24 18:55:53 +00003867/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3868/// 'icmp op load X, cst', try to see if we can compute the backedge
3869/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003870ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00003871ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3872 LoadInst *LI,
3873 Constant *RHS,
3874 const Loop *L,
3875 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003876 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003877
3878 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003879 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00003880 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003881 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003882
3883 // Make sure that it is really a constant global we are gepping, with an
3884 // initializer, and make sure the first IDX is really 0.
3885 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003886 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003887 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3888 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003889 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003890
3891 // Okay, we allow one non-constant index into the GEP instruction.
3892 Value *VarIdx = 0;
3893 std::vector<ConstantInt*> Indexes;
3894 unsigned VarIdxNum = 0;
3895 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3896 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3897 Indexes.push_back(CI);
3898 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003899 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003900 VarIdx = GEP->getOperand(i);
3901 VarIdxNum = i-2;
3902 Indexes.push_back(0);
3903 }
3904
3905 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3906 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003907 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003908 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003909
3910 // We can only recognize very limited forms of loop index expressions, in
3911 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003912 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003913 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3914 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3915 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003916 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003917
3918 unsigned MaxSteps = MaxBruteForceIterations;
3919 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003920 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003921 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003922 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003923
3924 // Form the GEP offset.
3925 Indexes[VarIdxNum] = Val;
3926
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003927 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003928 if (Result == 0) break; // Cannot compute!
3929
3930 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003931 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003932 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003933 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003934#if 0
David Greene25e0e872009-12-23 22:18:14 +00003935 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003936 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3937 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003938#endif
3939 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003940 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003941 }
3942 }
Dan Gohman1c343752009-06-27 21:21:31 +00003943 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003944}
3945
3946
Chris Lattner3221ad02004-04-17 22:58:41 +00003947/// CanConstantFold - Return true if we can constant fold an instruction of the
3948/// specified type, assuming that all operands were constants.
3949static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003950 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003951 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3952 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003953
Chris Lattner3221ad02004-04-17 22:58:41 +00003954 if (const CallInst *CI = dyn_cast<CallInst>(I))
3955 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003956 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003957 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003958}
3959
Chris Lattner3221ad02004-04-17 22:58:41 +00003960/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3961/// in the loop that V is derived from. We allow arbitrary operations along the
3962/// way, but the operands of an operation must either be constants or a value
3963/// derived from a constant PHI. If this expression does not fit with these
3964/// constraints, return null.
3965static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3966 // If this is not an instruction, or if this is an instruction outside of the
3967 // loop, it can't be derived from a loop PHI.
3968 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003969 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003970
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003971 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003972 if (L->getHeader() == I->getParent())
3973 return PN;
3974 else
3975 // We don't currently keep track of the control flow needed to evaluate
3976 // PHIs, so we cannot handle PHIs inside of loops.
3977 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003978 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003979
3980 // If we won't be able to constant fold this expression even if the operands
3981 // are constants, return early.
3982 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003983
Chris Lattner3221ad02004-04-17 22:58:41 +00003984 // Otherwise, we can evaluate this instruction if all of its operands are
3985 // constant or derived from a PHI node themselves.
3986 PHINode *PHI = 0;
3987 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3988 if (!(isa<Constant>(I->getOperand(Op)) ||
3989 isa<GlobalValue>(I->getOperand(Op)))) {
3990 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3991 if (P == 0) return 0; // Not evolving from PHI
3992 if (PHI == 0)
3993 PHI = P;
3994 else if (PHI != P)
3995 return 0; // Evolving from multiple different PHIs.
3996 }
3997
3998 // This is a expression evolving from a constant PHI!
3999 return PHI;
4000}
4001
4002/// EvaluateExpression - Given an expression that passes the
4003/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4004/// in the loop has the value PHIVal. If we can't fold this expression for some
4005/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004006static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4007 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004008 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004009 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00004010 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00004011 Instruction *I = cast<Instruction>(V);
4012
4013 std::vector<Constant*> Operands;
4014 Operands.resize(I->getNumOperands());
4015
4016 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004017 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004018 if (Operands[i] == 0) return 0;
4019 }
4020
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004021 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004022 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004023 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004024 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004025 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004026}
4027
4028/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4029/// in the header of its containing loop, we know the loop executes a
4030/// constant number of times, and the PHI node is just a recurrence
4031/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004032Constant *
4033ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004034 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004035 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004036 std::map<PHINode*, Constant*>::iterator I =
4037 ConstantEvolutionLoopExitValue.find(PN);
4038 if (I != ConstantEvolutionLoopExitValue.end())
4039 return I->second;
4040
Dan Gohman46bdfb02009-02-24 18:55:53 +00004041 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00004042 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4043
4044 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4045
4046 // Since the loop is canonicalized, the PHI node must have two entries. One
4047 // entry must be a constant (coming in from outside of the loop), and the
4048 // second must be derived from the same PHI.
4049 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4050 Constant *StartCST =
4051 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4052 if (StartCST == 0)
4053 return RetVal = 0; // Must be a constant.
4054
4055 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4056 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4057 if (PN2 != PN)
4058 return RetVal = 0; // Not derived from same PHI.
4059
4060 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004061 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004062 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004063
Dan Gohman46bdfb02009-02-24 18:55:53 +00004064 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004065 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004066 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4067 if (IterationNum == NumIterations)
4068 return RetVal = PHIVal; // Got exit value!
4069
4070 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004071 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004072 if (NextPHI == PHIVal)
4073 return RetVal = NextPHI; // Stopped evolving!
4074 if (NextPHI == 0)
4075 return 0; // Couldn't evaluate!
4076 PHIVal = NextPHI;
4077 }
4078}
4079
Dan Gohman07ad19b2009-07-27 16:09:48 +00004080/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004081/// constant number of times (the condition evolves only from constants),
4082/// try to evaluate a few iterations of the loop until we get the exit
4083/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004084/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004085const SCEV *
4086ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4087 Value *Cond,
4088 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004089 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004090 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004091
4092 // Since the loop is canonicalized, the PHI node must have two entries. One
4093 // entry must be a constant (coming in from outside of the loop), and the
4094 // second must be derived from the same PHI.
4095 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4096 Constant *StartCST =
4097 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004098 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004099
4100 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4101 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004102 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004103
4104 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4105 // the loop symbolically to determine when the condition gets a value of
4106 // "ExitWhen".
4107 unsigned IterationNum = 0;
4108 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4109 for (Constant *PHIVal = StartCST;
4110 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004111 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004112 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004113
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004114 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004115 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004116
Reid Spencere8019bb2007-03-01 07:25:48 +00004117 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004118 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004119 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004120 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004121
Chris Lattner3221ad02004-04-17 22:58:41 +00004122 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004123 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004124 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004125 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004126 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004127 }
4128
4129 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004130 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004131}
4132
Dan Gohmane7125f42009-09-03 15:00:26 +00004133/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004134/// at the specified scope in the program. The L value specifies a loop
4135/// nest to evaluate the expression at, where null is the top-level or a
4136/// specified loop is immediately inside of the loop.
4137///
4138/// This method can be used to compute the exit value for a variable defined
4139/// in a loop by querying what the value will hold in the parent loop.
4140///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004141/// In the case that a relevant loop exit value cannot be computed, the
4142/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004143const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004144 // Check to see if we've folded this expression at this loop before.
4145 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4146 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4147 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4148 if (!Pair.second)
4149 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004150
Dan Gohman42214892009-08-31 21:15:23 +00004151 // Otherwise compute it.
4152 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004153 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004154 return C;
4155}
4156
4157const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004158 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004159
Nick Lewycky3e630762008-02-20 06:48:22 +00004160 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004161 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004162 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004163 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004164 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004165 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4166 if (PHINode *PN = dyn_cast<PHINode>(I))
4167 if (PN->getParent() == LI->getHeader()) {
4168 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004169 // to see if the loop that contains it has a known backedge-taken
4170 // count. If so, we may be able to force computation of the exit
4171 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004172 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004173 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004174 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004175 // Okay, we know how many times the containing loop executes. If
4176 // this is a constant evolving PHI node, get the final value at
4177 // the specified iteration number.
4178 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004179 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004180 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004181 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004182 }
4183 }
4184
Reid Spencer09906f32006-12-04 21:33:23 +00004185 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004186 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004187 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004188 // result. This is particularly useful for computing loop exit values.
4189 if (CanConstantFold(I)) {
4190 std::vector<Constant*> Operands;
4191 Operands.reserve(I->getNumOperands());
4192 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4193 Value *Op = I->getOperand(i);
4194 if (Constant *C = dyn_cast<Constant>(Op)) {
4195 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004196 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004197 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004198 // non-integer and non-pointer, don't even try to analyze them
4199 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004200 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004201 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004202
Dan Gohman5d984912009-12-18 01:14:11 +00004203 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004204 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004205 Constant *C = SC->getValue();
4206 if (C->getType() != Op->getType())
4207 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4208 Op->getType(),
4209 false),
4210 C, Op->getType());
4211 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004212 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004213 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4214 if (C->getType() != Op->getType())
4215 C =
4216 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4217 Op->getType(),
4218 false),
4219 C, Op->getType());
4220 Operands.push_back(C);
4221 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004222 return V;
4223 } else {
4224 return V;
4225 }
4226 }
4227 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004228
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004229 Constant *C;
4230 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4231 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004232 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004233 else
4234 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004235 &Operands[0], Operands.size(), TD);
Dan Gohman09987962009-06-29 21:31:18 +00004236 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004237 }
4238 }
4239
4240 // This is some other type of SCEVUnknown, just return it.
4241 return V;
4242 }
4243
Dan Gohman622ed672009-05-04 22:02:23 +00004244 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004245 // Avoid performing the look-up in the common case where the specified
4246 // expression has no loop-variant portions.
4247 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004248 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004249 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004250 // Okay, at least one of these operands is loop variant but might be
4251 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004252 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4253 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004254 NewOps.push_back(OpAtScope);
4255
4256 for (++i; i != e; ++i) {
4257 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004258 NewOps.push_back(OpAtScope);
4259 }
4260 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004261 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004262 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004263 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004264 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004265 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004266 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004267 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004268 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004269 }
4270 }
4271 // If we got here, all operands are loop invariant.
4272 return Comm;
4273 }
4274
Dan Gohman622ed672009-05-04 22:02:23 +00004275 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004276 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4277 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004278 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4279 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004280 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004281 }
4282
4283 // If this is a loop recurrence for a loop that does not contain L, then we
4284 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004285 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004286 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004287 // To evaluate this recurrence, we need to know how many times the AddRec
4288 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004289 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004290 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004291
Eli Friedmanb42a6262008-08-04 23:49:06 +00004292 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004293 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004294 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004295 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004296 }
4297
Dan Gohman622ed672009-05-04 22:02:23 +00004298 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004299 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004300 if (Op == Cast->getOperand())
4301 return Cast; // must be loop invariant
4302 return getZeroExtendExpr(Op, Cast->getType());
4303 }
4304
Dan Gohman622ed672009-05-04 22:02:23 +00004305 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004306 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004307 if (Op == Cast->getOperand())
4308 return Cast; // must be loop invariant
4309 return getSignExtendExpr(Op, Cast->getType());
4310 }
4311
Dan Gohman622ed672009-05-04 22:02:23 +00004312 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004313 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004314 if (Op == Cast->getOperand())
4315 return Cast; // must be loop invariant
4316 return getTruncateExpr(Op, Cast->getType());
4317 }
4318
Torok Edwinc23197a2009-07-14 16:55:14 +00004319 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004320 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004321}
4322
Dan Gohman66a7e852009-05-08 20:38:54 +00004323/// getSCEVAtScope - This is a convenience function which does
4324/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004325const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004326 return getSCEVAtScope(getSCEV(V), L);
4327}
4328
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004329/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4330/// following equation:
4331///
4332/// A * X = B (mod N)
4333///
4334/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4335/// A and B isn't important.
4336///
4337/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004338static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004339 ScalarEvolution &SE) {
4340 uint32_t BW = A.getBitWidth();
4341 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4342 assert(A != 0 && "A must be non-zero.");
4343
4344 // 1. D = gcd(A, N)
4345 //
4346 // The gcd of A and N may have only one prime factor: 2. The number of
4347 // trailing zeros in A is its multiplicity
4348 uint32_t Mult2 = A.countTrailingZeros();
4349 // D = 2^Mult2
4350
4351 // 2. Check if B is divisible by D.
4352 //
4353 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4354 // is not less than multiplicity of this prime factor for D.
4355 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004356 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004357
4358 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4359 // modulo (N / D).
4360 //
4361 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4362 // bit width during computations.
4363 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4364 APInt Mod(BW + 1, 0);
4365 Mod.set(BW - Mult2); // Mod = N / D
4366 APInt I = AD.multiplicativeInverse(Mod);
4367
4368 // 4. Compute the minimum unsigned root of the equation:
4369 // I * (B / D) mod (N / D)
4370 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4371
4372 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4373 // bits.
4374 return SE.getConstant(Result.trunc(BW));
4375}
Chris Lattner53e677a2004-04-02 20:23:17 +00004376
4377/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4378/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4379/// might be the same) or two SCEVCouldNotCompute objects.
4380///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004381static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004382SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004383 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004384 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4385 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4386 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004387
Chris Lattner53e677a2004-04-02 20:23:17 +00004388 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004389 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004390 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004391 return std::make_pair(CNC, CNC);
4392 }
4393
Reid Spencere8019bb2007-03-01 07:25:48 +00004394 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004395 const APInt &L = LC->getValue()->getValue();
4396 const APInt &M = MC->getValue()->getValue();
4397 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004398 APInt Two(BitWidth, 2);
4399 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004400
Dan Gohman64a845e2009-06-24 04:48:43 +00004401 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004402 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004403 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004404 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4405 // The B coefficient is M-N/2
4406 APInt B(M);
4407 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004408
Reid Spencere8019bb2007-03-01 07:25:48 +00004409 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004410 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004411
Reid Spencere8019bb2007-03-01 07:25:48 +00004412 // Compute the B^2-4ac term.
4413 APInt SqrtTerm(B);
4414 SqrtTerm *= B;
4415 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004416
Reid Spencere8019bb2007-03-01 07:25:48 +00004417 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4418 // integer value or else APInt::sqrt() will assert.
4419 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004420
Dan Gohman64a845e2009-06-24 04:48:43 +00004421 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004422 // The divisions must be performed as signed divisions.
4423 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004424 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004425 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004426 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004427 return std::make_pair(CNC, CNC);
4428 }
4429
Owen Andersone922c022009-07-22 00:24:57 +00004430 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004431
4432 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004433 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004434 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004435 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004436
Dan Gohman64a845e2009-06-24 04:48:43 +00004437 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004438 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004439 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004440}
4441
4442/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004443/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004444ScalarEvolution::BackedgeTakenInfo
4445ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004446 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004447 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004448 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004449 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004450 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004451 }
4452
Dan Gohman35738ac2009-05-04 22:30:44 +00004453 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004454 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004455 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004456
4457 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004458 // If this is an affine expression, the execution count of this branch is
4459 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004460 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004461 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004462 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004463 // equivalent to:
4464 //
4465 // Step*N = -Start (mod 2^BW)
4466 //
4467 // where BW is the common bit width of Start and Step.
4468
Chris Lattner53e677a2004-04-02 20:23:17 +00004469 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004470 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4471 L->getParentLoop());
4472 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4473 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004474
Dan Gohman622ed672009-05-04 22:02:23 +00004475 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004476 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004477
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004478 // First, handle unitary steps.
4479 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004480 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004481 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4482 return Start; // N = Start (as unsigned)
4483
4484 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004485 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004486 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004487 -StartC->getValue()->getValue(),
4488 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004489 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004490 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004491 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4492 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004493 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004494 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004495 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4496 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004497 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004498#if 0
David Greene25e0e872009-12-23 22:18:14 +00004499 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004500 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004501#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004502 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004503 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004504 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004505 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004506 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004507 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004508
Chris Lattner53e677a2004-04-02 20:23:17 +00004509 // We can only use this value if the chrec ends up with an exact zero
4510 // value at this index. When solving for "X*X != 5", for example, we
4511 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004512 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004513 if (Val->isZero())
4514 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004515 }
4516 }
4517 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004518
Dan Gohman1c343752009-06-27 21:21:31 +00004519 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004520}
4521
4522/// HowFarToNonZero - Return the number of times a backedge checking the
4523/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004524/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004525ScalarEvolution::BackedgeTakenInfo
4526ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004527 // Loops that look like: while (X == 0) are very strange indeed. We don't
4528 // handle them yet except for the trivial case. This could be expanded in the
4529 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004530
Chris Lattner53e677a2004-04-02 20:23:17 +00004531 // If the value is a constant, check to see if it is known to be non-zero
4532 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004533 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004534 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004535 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004536 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004537 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004538
Chris Lattner53e677a2004-04-02 20:23:17 +00004539 // We could implement others, but I really doubt anyone writes loops like
4540 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004541 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004542}
4543
Dan Gohman859b4822009-05-18 15:36:09 +00004544/// getLoopPredecessor - If the given loop's header has exactly one unique
4545/// predecessor outside the loop, return it. Otherwise return null.
4546///
4547BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4548 BasicBlock *Header = L->getHeader();
4549 BasicBlock *Pred = 0;
4550 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4551 PI != E; ++PI)
4552 if (!L->contains(*PI)) {
4553 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4554 Pred = *PI;
4555 }
4556 return Pred;
4557}
4558
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004559/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4560/// (which may not be an immediate predecessor) which has exactly one
4561/// successor from which BB is reachable, or null if no such block is
4562/// found.
4563///
4564BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004565ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004566 // If the block has a unique predecessor, then there is no path from the
4567 // predecessor to the block that does not go through the direct edge
4568 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004569 if (BasicBlock *Pred = BB->getSinglePredecessor())
4570 return Pred;
4571
4572 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004573 // If the header has a unique predecessor outside the loop, it must be
4574 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004575 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004576 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004577
4578 return 0;
4579}
4580
Dan Gohman763bad12009-06-20 00:35:32 +00004581/// HasSameValue - SCEV structural equivalence is usually sufficient for
4582/// testing whether two expressions are equal, however for the purposes of
4583/// looking for a condition guarding a loop, it can be useful to be a little
4584/// more general, since a front-end may have replicated the controlling
4585/// expression.
4586///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004587static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004588 // Quick check to see if they are the same SCEV.
4589 if (A == B) return true;
4590
4591 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4592 // two different instructions with the same value. Check for this case.
4593 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4594 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4595 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4596 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004597 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004598 return true;
4599
4600 // Otherwise assume they may have a different value.
4601 return false;
4602}
4603
Dan Gohman85b05a22009-07-13 21:35:55 +00004604bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4605 return getSignedRange(S).getSignedMax().isNegative();
4606}
4607
4608bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4609 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4610}
4611
4612bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4613 return !getSignedRange(S).getSignedMin().isNegative();
4614}
4615
4616bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4617 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4618}
4619
4620bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4621 return isKnownNegative(S) || isKnownPositive(S);
4622}
4623
4624bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4625 const SCEV *LHS, const SCEV *RHS) {
4626
4627 if (HasSameValue(LHS, RHS))
4628 return ICmpInst::isTrueWhenEqual(Pred);
4629
4630 switch (Pred) {
4631 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004632 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004633 break;
4634 case ICmpInst::ICMP_SGT:
4635 Pred = ICmpInst::ICMP_SLT;
4636 std::swap(LHS, RHS);
4637 case ICmpInst::ICMP_SLT: {
4638 ConstantRange LHSRange = getSignedRange(LHS);
4639 ConstantRange RHSRange = getSignedRange(RHS);
4640 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4641 return true;
4642 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4643 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004644 break;
4645 }
4646 case ICmpInst::ICMP_SGE:
4647 Pred = ICmpInst::ICMP_SLE;
4648 std::swap(LHS, RHS);
4649 case ICmpInst::ICMP_SLE: {
4650 ConstantRange LHSRange = getSignedRange(LHS);
4651 ConstantRange RHSRange = getSignedRange(RHS);
4652 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4653 return true;
4654 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4655 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004656 break;
4657 }
4658 case ICmpInst::ICMP_UGT:
4659 Pred = ICmpInst::ICMP_ULT;
4660 std::swap(LHS, RHS);
4661 case ICmpInst::ICMP_ULT: {
4662 ConstantRange LHSRange = getUnsignedRange(LHS);
4663 ConstantRange RHSRange = getUnsignedRange(RHS);
4664 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4665 return true;
4666 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4667 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004668 break;
4669 }
4670 case ICmpInst::ICMP_UGE:
4671 Pred = ICmpInst::ICMP_ULE;
4672 std::swap(LHS, RHS);
4673 case ICmpInst::ICMP_ULE: {
4674 ConstantRange LHSRange = getUnsignedRange(LHS);
4675 ConstantRange RHSRange = getUnsignedRange(RHS);
4676 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4677 return true;
4678 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4679 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004680 break;
4681 }
4682 case ICmpInst::ICMP_NE: {
4683 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4684 return true;
4685 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4686 return true;
4687
4688 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4689 if (isKnownNonZero(Diff))
4690 return true;
4691 break;
4692 }
4693 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004694 // The check at the top of the function catches the case where
4695 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004696 break;
4697 }
4698 return false;
4699}
4700
4701/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4702/// protected by a conditional between LHS and RHS. This is used to
4703/// to eliminate casts.
4704bool
4705ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4706 ICmpInst::Predicate Pred,
4707 const SCEV *LHS, const SCEV *RHS) {
4708 // Interpret a null as meaning no loop, where there is obviously no guard
4709 // (interprocedural conditions notwithstanding).
4710 if (!L) return true;
4711
4712 BasicBlock *Latch = L->getLoopLatch();
4713 if (!Latch)
4714 return false;
4715
4716 BranchInst *LoopContinuePredicate =
4717 dyn_cast<BranchInst>(Latch->getTerminator());
4718 if (!LoopContinuePredicate ||
4719 LoopContinuePredicate->isUnconditional())
4720 return false;
4721
Dan Gohman0f4b2852009-07-21 23:03:19 +00004722 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4723 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004724}
4725
4726/// isLoopGuardedByCond - Test whether entry to the loop is protected
4727/// by a conditional between LHS and RHS. This is used to help avoid max
4728/// expressions in loop trip counts, and to eliminate casts.
4729bool
4730ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4731 ICmpInst::Predicate Pred,
4732 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004733 // Interpret a null as meaning no loop, where there is obviously no guard
4734 // (interprocedural conditions notwithstanding).
4735 if (!L) return false;
4736
Dan Gohman859b4822009-05-18 15:36:09 +00004737 BasicBlock *Predecessor = getLoopPredecessor(L);
4738 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004739
Dan Gohman859b4822009-05-18 15:36:09 +00004740 // Starting at the loop predecessor, climb up the predecessor chain, as long
4741 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004742 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004743 for (; Predecessor;
4744 PredecessorDest = Predecessor,
4745 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004746
4747 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004748 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004749 if (!LoopEntryPredicate ||
4750 LoopEntryPredicate->isUnconditional())
4751 continue;
4752
Dan Gohman0f4b2852009-07-21 23:03:19 +00004753 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4754 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004755 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004756 }
4757
Dan Gohman38372182008-08-12 20:17:31 +00004758 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004759}
4760
Dan Gohman0f4b2852009-07-21 23:03:19 +00004761/// isImpliedCond - Test whether the condition described by Pred, LHS,
4762/// and RHS is true whenever the given Cond value evaluates to true.
4763bool ScalarEvolution::isImpliedCond(Value *CondValue,
4764 ICmpInst::Predicate Pred,
4765 const SCEV *LHS, const SCEV *RHS,
4766 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004767 // Recursivly handle And and Or conditions.
4768 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4769 if (BO->getOpcode() == Instruction::And) {
4770 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004771 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4772 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004773 } else if (BO->getOpcode() == Instruction::Or) {
4774 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004775 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4776 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004777 }
4778 }
4779
4780 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4781 if (!ICI) return false;
4782
Dan Gohman85b05a22009-07-13 21:35:55 +00004783 // Bail if the ICmp's operands' types are wider than the needed type
4784 // before attempting to call getSCEV on them. This avoids infinite
4785 // recursion, since the analysis of widening casts can require loop
4786 // exit condition information for overflow checking, which would
4787 // lead back here.
4788 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004789 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004790 return false;
4791
Dan Gohman0f4b2852009-07-21 23:03:19 +00004792 // Now that we found a conditional branch that dominates the loop, check to
4793 // see if it is the comparison we are looking for.
4794 ICmpInst::Predicate FoundPred;
4795 if (Inverse)
4796 FoundPred = ICI->getInversePredicate();
4797 else
4798 FoundPred = ICI->getPredicate();
4799
4800 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4801 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004802
4803 // Balance the types. The case where FoundLHS' type is wider than
4804 // LHS' type is checked for above.
4805 if (getTypeSizeInBits(LHS->getType()) >
4806 getTypeSizeInBits(FoundLHS->getType())) {
4807 if (CmpInst::isSigned(Pred)) {
4808 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4809 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4810 } else {
4811 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4812 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4813 }
4814 }
4815
Dan Gohman0f4b2852009-07-21 23:03:19 +00004816 // Canonicalize the query to match the way instcombine will have
4817 // canonicalized the comparison.
4818 // First, put a constant operand on the right.
4819 if (isa<SCEVConstant>(LHS)) {
4820 std::swap(LHS, RHS);
4821 Pred = ICmpInst::getSwappedPredicate(Pred);
4822 }
4823 // Then, canonicalize comparisons with boundary cases.
4824 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4825 const APInt &RA = RC->getValue()->getValue();
4826 switch (Pred) {
4827 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4828 case ICmpInst::ICMP_EQ:
4829 case ICmpInst::ICMP_NE:
4830 break;
4831 case ICmpInst::ICMP_UGE:
4832 if ((RA - 1).isMinValue()) {
4833 Pred = ICmpInst::ICMP_NE;
4834 RHS = getConstant(RA - 1);
4835 break;
4836 }
4837 if (RA.isMaxValue()) {
4838 Pred = ICmpInst::ICMP_EQ;
4839 break;
4840 }
4841 if (RA.isMinValue()) return true;
4842 break;
4843 case ICmpInst::ICMP_ULE:
4844 if ((RA + 1).isMaxValue()) {
4845 Pred = ICmpInst::ICMP_NE;
4846 RHS = getConstant(RA + 1);
4847 break;
4848 }
4849 if (RA.isMinValue()) {
4850 Pred = ICmpInst::ICMP_EQ;
4851 break;
4852 }
4853 if (RA.isMaxValue()) return true;
4854 break;
4855 case ICmpInst::ICMP_SGE:
4856 if ((RA - 1).isMinSignedValue()) {
4857 Pred = ICmpInst::ICMP_NE;
4858 RHS = getConstant(RA - 1);
4859 break;
4860 }
4861 if (RA.isMaxSignedValue()) {
4862 Pred = ICmpInst::ICMP_EQ;
4863 break;
4864 }
4865 if (RA.isMinSignedValue()) return true;
4866 break;
4867 case ICmpInst::ICMP_SLE:
4868 if ((RA + 1).isMaxSignedValue()) {
4869 Pred = ICmpInst::ICMP_NE;
4870 RHS = getConstant(RA + 1);
4871 break;
4872 }
4873 if (RA.isMinSignedValue()) {
4874 Pred = ICmpInst::ICMP_EQ;
4875 break;
4876 }
4877 if (RA.isMaxSignedValue()) return true;
4878 break;
4879 case ICmpInst::ICMP_UGT:
4880 if (RA.isMinValue()) {
4881 Pred = ICmpInst::ICMP_NE;
4882 break;
4883 }
4884 if ((RA + 1).isMaxValue()) {
4885 Pred = ICmpInst::ICMP_EQ;
4886 RHS = getConstant(RA + 1);
4887 break;
4888 }
4889 if (RA.isMaxValue()) return false;
4890 break;
4891 case ICmpInst::ICMP_ULT:
4892 if (RA.isMaxValue()) {
4893 Pred = ICmpInst::ICMP_NE;
4894 break;
4895 }
4896 if ((RA - 1).isMinValue()) {
4897 Pred = ICmpInst::ICMP_EQ;
4898 RHS = getConstant(RA - 1);
4899 break;
4900 }
4901 if (RA.isMinValue()) return false;
4902 break;
4903 case ICmpInst::ICMP_SGT:
4904 if (RA.isMinSignedValue()) {
4905 Pred = ICmpInst::ICMP_NE;
4906 break;
4907 }
4908 if ((RA + 1).isMaxSignedValue()) {
4909 Pred = ICmpInst::ICMP_EQ;
4910 RHS = getConstant(RA + 1);
4911 break;
4912 }
4913 if (RA.isMaxSignedValue()) return false;
4914 break;
4915 case ICmpInst::ICMP_SLT:
4916 if (RA.isMaxSignedValue()) {
4917 Pred = ICmpInst::ICMP_NE;
4918 break;
4919 }
4920 if ((RA - 1).isMinSignedValue()) {
4921 Pred = ICmpInst::ICMP_EQ;
4922 RHS = getConstant(RA - 1);
4923 break;
4924 }
4925 if (RA.isMinSignedValue()) return false;
4926 break;
4927 }
4928 }
4929
4930 // Check to see if we can make the LHS or RHS match.
4931 if (LHS == FoundRHS || RHS == FoundLHS) {
4932 if (isa<SCEVConstant>(RHS)) {
4933 std::swap(FoundLHS, FoundRHS);
4934 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4935 } else {
4936 std::swap(LHS, RHS);
4937 Pred = ICmpInst::getSwappedPredicate(Pred);
4938 }
4939 }
4940
4941 // Check whether the found predicate is the same as the desired predicate.
4942 if (FoundPred == Pred)
4943 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4944
4945 // Check whether swapping the found predicate makes it the same as the
4946 // desired predicate.
4947 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4948 if (isa<SCEVConstant>(RHS))
4949 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4950 else
4951 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4952 RHS, LHS, FoundLHS, FoundRHS);
4953 }
4954
4955 // Check whether the actual condition is beyond sufficient.
4956 if (FoundPred == ICmpInst::ICMP_EQ)
4957 if (ICmpInst::isTrueWhenEqual(Pred))
4958 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4959 return true;
4960 if (Pred == ICmpInst::ICMP_NE)
4961 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4962 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4963 return true;
4964
4965 // Otherwise assume the worst.
4966 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004967}
4968
Dan Gohman0f4b2852009-07-21 23:03:19 +00004969/// isImpliedCondOperands - Test whether the condition described by Pred,
4970/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4971/// and FoundRHS is true.
4972bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4973 const SCEV *LHS, const SCEV *RHS,
4974 const SCEV *FoundLHS,
4975 const SCEV *FoundRHS) {
4976 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4977 FoundLHS, FoundRHS) ||
4978 // ~x < ~y --> x > y
4979 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4980 getNotSCEV(FoundRHS),
4981 getNotSCEV(FoundLHS));
4982}
4983
4984/// isImpliedCondOperandsHelper - Test whether the condition described by
4985/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4986/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004987bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004988ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4989 const SCEV *LHS, const SCEV *RHS,
4990 const SCEV *FoundLHS,
4991 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004992 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004993 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4994 case ICmpInst::ICMP_EQ:
4995 case ICmpInst::ICMP_NE:
4996 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4997 return true;
4998 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004999 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005000 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005001 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5002 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5003 return true;
5004 break;
5005 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005006 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005007 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5008 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5009 return true;
5010 break;
5011 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005012 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005013 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5014 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5015 return true;
5016 break;
5017 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005018 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005019 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5020 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5021 return true;
5022 break;
5023 }
5024
5025 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005026}
5027
Dan Gohman51f53b72009-06-21 23:46:38 +00005028/// getBECount - Subtract the end and start values and divide by the step,
5029/// rounding up, to get the number of times the backedge is executed. Return
5030/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005031const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005032 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005033 const SCEV *Step,
5034 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005035 assert(!isKnownNegative(Step) &&
5036 "This code doesn't handle negative strides yet!");
5037
Dan Gohman51f53b72009-06-21 23:46:38 +00005038 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00005039 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
5040 const SCEV *Diff = getMinusSCEV(End, Start);
5041 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005042
5043 // Add an adjustment to the difference between End and Start so that
5044 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005045 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005046
Dan Gohman1f96e672009-09-17 18:05:20 +00005047 if (!NoWrap) {
5048 // Check Add for unsigned overflow.
5049 // TODO: More sophisticated things could be done here.
5050 const Type *WideTy = IntegerType::get(getContext(),
5051 getTypeSizeInBits(Ty) + 1);
5052 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5053 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5054 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5055 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5056 return getCouldNotCompute();
5057 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005058
5059 return getUDivExpr(Add, Step);
5060}
5061
Chris Lattnerdb25de42005-08-15 23:33:51 +00005062/// HowManyLessThans - Return the number of times a backedge containing the
5063/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005064/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005065ScalarEvolution::BackedgeTakenInfo
5066ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5067 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005068 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005069 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005070
Dan Gohman35738ac2009-05-04 22:30:44 +00005071 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005072 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005073 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005074
Dan Gohman1f96e672009-09-17 18:05:20 +00005075 // Check to see if we have a flag which makes analysis easy.
5076 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5077 AddRec->hasNoUnsignedWrap();
5078
Chris Lattnerdb25de42005-08-15 23:33:51 +00005079 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005080 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005081 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005082
Dan Gohman52fddd32010-01-26 04:40:18 +00005083 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005084 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005085 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005086 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005087 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005088 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005089 // value and past the maximum value for its type in a single step.
5090 // Note that it's not sufficient to check NoWrap here, because even
5091 // though the value after a wrap is undefined, it's not undefined
5092 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005093 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005094 // iterate at least until the iteration where the wrapping occurs.
5095 const SCEV *One = getIntegerSCEV(1, Step->getType());
5096 if (isSigned) {
5097 APInt Max = APInt::getSignedMaxValue(BitWidth);
5098 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5099 .slt(getSignedRange(RHS).getSignedMax()))
5100 return getCouldNotCompute();
5101 } else {
5102 APInt Max = APInt::getMaxValue(BitWidth);
5103 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5104 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5105 return getCouldNotCompute();
5106 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005107 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005108 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005109 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005110
Dan Gohmana1af7572009-04-30 20:47:05 +00005111 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5112 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5113 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005114 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005115
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005116 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005117 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005118
Dan Gohmana1af7572009-04-30 20:47:05 +00005119 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005120 const SCEV *MinStart = getConstant(isSigned ?
5121 getSignedRange(Start).getSignedMin() :
5122 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005123
Dan Gohmana1af7572009-04-30 20:47:05 +00005124 // If we know that the condition is true in order to enter the loop,
5125 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005126 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5127 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005128 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005129 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005130 isSigned ? ICmpInst::ICMP_SLT :
5131 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005132 getMinusSCEV(Start, Step), RHS))
5133 End = isSigned ? getSMaxExpr(RHS, Start)
5134 : getUMaxExpr(RHS, Start);
5135
5136 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005137 const SCEV *MaxEnd = getConstant(isSigned ?
5138 getSignedRange(End).getSignedMax() :
5139 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005140
Dan Gohman52fddd32010-01-26 04:40:18 +00005141 // If MaxEnd is within a step of the maximum integer value in its type,
5142 // adjust it down to the minimum value which would produce the same effect.
5143 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5144 // compute the correct value.
5145 const SCEV *StepMinusOne = getMinusSCEV(Step,
5146 getIntegerSCEV(1, Step->getType()));
5147 MaxEnd = isSigned ?
5148 getSMinExpr(MaxEnd,
5149 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5150 StepMinusOne)) :
5151 getUMinExpr(MaxEnd,
5152 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5153 StepMinusOne));
5154
Dan Gohmana1af7572009-04-30 20:47:05 +00005155 // Finally, we subtract these two values and divide, rounding up, to get
5156 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005157 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005158
5159 // The maximum backedge count is similar, except using the minimum start
5160 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005161 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005162
5163 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005164 }
5165
Dan Gohman1c343752009-06-27 21:21:31 +00005166 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005167}
5168
Chris Lattner53e677a2004-04-02 20:23:17 +00005169/// getNumIterationsInRange - Return the number of iterations of this loop that
5170/// produce values in the specified constant range. Another way of looking at
5171/// this is that it returns the first iteration number where the value is not in
5172/// the condition, thus computing the exit count. If the iteration count can't
5173/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005174const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005175 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005176 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005177 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005178
5179 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005180 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005181 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005182 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005183 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005184 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005185 if (const SCEVAddRecExpr *ShiftedAddRec =
5186 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005187 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005188 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005189 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005190 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005191 }
5192
5193 // The only time we can solve this is when we have all constant indices.
5194 // Otherwise, we cannot determine the overflow conditions.
5195 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5196 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005197 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005198
5199
5200 // Okay at this point we know that all elements of the chrec are constants and
5201 // that the start element is zero.
5202
5203 // First check to see if the range contains zero. If not, the first
5204 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005205 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005206 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005207 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005208
Chris Lattner53e677a2004-04-02 20:23:17 +00005209 if (isAffine()) {
5210 // If this is an affine expression then we have this situation:
5211 // Solve {0,+,A} in Range === Ax in Range
5212
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005213 // We know that zero is in the range. If A is positive then we know that
5214 // the upper value of the range must be the first possible exit value.
5215 // If A is negative then the lower of the range is the last possible loop
5216 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005217 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005218 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5219 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005220
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005221 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005222 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005223 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005224
5225 // Evaluate at the exit value. If we really did fall out of the valid
5226 // range, then we computed our trip count, otherwise wrap around or other
5227 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005228 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005229 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005230 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005231
5232 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005233 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005234 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005235 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005236 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005237 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005238 } else if (isQuadratic()) {
5239 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5240 // quadratic equation to solve it. To do this, we must frame our problem in
5241 // terms of figuring out when zero is crossed, instead of when
5242 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005243 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005244 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005245 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005246
5247 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005248 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005249 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005250 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5251 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005252 if (R1) {
5253 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005254 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005255 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005256 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005257 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005258 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005259
Chris Lattner53e677a2004-04-02 20:23:17 +00005260 // Make sure the root is not off by one. The returned iteration should
5261 // not be in the range, but the previous one should be. When solving
5262 // for "X*X < 5", for example, we should not return a root of 2.
5263 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005264 R1->getValue(),
5265 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005266 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005267 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005268 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005269 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005270
Dan Gohman246b2562007-10-22 18:31:58 +00005271 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005272 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005273 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005274 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005275 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005276
Chris Lattner53e677a2004-04-02 20:23:17 +00005277 // If R1 was not in the range, then it is a good return value. Make
5278 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005279 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005280 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005281 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005282 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005283 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005284 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005285 }
5286 }
5287 }
5288
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005289 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005290}
5291
5292
5293
5294//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005295// SCEVCallbackVH Class Implementation
5296//===----------------------------------------------------------------------===//
5297
Dan Gohman1959b752009-05-19 19:22:47 +00005298void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005299 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005300 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5301 SE->ConstantEvolutionLoopExitValue.erase(PN);
5302 SE->Scalars.erase(getValPtr());
5303 // this now dangles!
5304}
5305
Dan Gohman1959b752009-05-19 19:22:47 +00005306void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005307 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005308
5309 // Forget all the expressions associated with users of the old value,
5310 // so that future queries will recompute the expressions using the new
5311 // value.
5312 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005313 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005314 Value *Old = getValPtr();
5315 bool DeleteOld = false;
5316 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5317 UI != UE; ++UI)
5318 Worklist.push_back(*UI);
5319 while (!Worklist.empty()) {
5320 User *U = Worklist.pop_back_val();
5321 // Deleting the Old value will cause this to dangle. Postpone
5322 // that until everything else is done.
5323 if (U == Old) {
5324 DeleteOld = true;
5325 continue;
5326 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005327 if (!Visited.insert(U))
5328 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005329 if (PHINode *PN = dyn_cast<PHINode>(U))
5330 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005331 SE->Scalars.erase(U);
5332 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5333 UI != UE; ++UI)
5334 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005335 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005336 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005337 if (DeleteOld) {
5338 if (PHINode *PN = dyn_cast<PHINode>(Old))
5339 SE->ConstantEvolutionLoopExitValue.erase(PN);
5340 SE->Scalars.erase(Old);
5341 // this now dangles!
5342 }
5343 // this may dangle!
5344}
5345
Dan Gohman1959b752009-05-19 19:22:47 +00005346ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005347 : CallbackVH(V), SE(se) {}
5348
5349//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005350// ScalarEvolution Class Implementation
5351//===----------------------------------------------------------------------===//
5352
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005353ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005354 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005355}
5356
Chris Lattner53e677a2004-04-02 20:23:17 +00005357bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005358 this->F = &F;
5359 LI = &getAnalysis<LoopInfo>();
5360 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005361 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005362 return false;
5363}
5364
5365void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005366 Scalars.clear();
5367 BackedgeTakenCounts.clear();
5368 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005369 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005370 UniqueSCEVs.clear();
5371 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005372}
5373
5374void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5375 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005376 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005377 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005378}
5379
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005380bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005381 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005382}
5383
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005384static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005385 const Loop *L) {
5386 // Print all inner loops first
5387 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5388 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005389
Dan Gohman30733292010-01-09 18:17:45 +00005390 OS << "Loop ";
5391 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5392 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005393
Dan Gohman5d984912009-12-18 01:14:11 +00005394 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005395 L->getExitBlocks(ExitBlocks);
5396 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005397 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005398
Dan Gohman46bdfb02009-02-24 18:55:53 +00005399 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5400 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005401 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005402 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005403 }
5404
Dan Gohman30733292010-01-09 18:17:45 +00005405 OS << "\n"
5406 "Loop ";
5407 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5408 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005409
5410 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5411 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5412 } else {
5413 OS << "Unpredictable max backedge-taken count. ";
5414 }
5415
5416 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005417}
5418
Dan Gohman5d984912009-12-18 01:14:11 +00005419void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005420 // ScalarEvolution's implementaiton of the print method is to print
5421 // out SCEV values of all instructions that are interesting. Doing
5422 // this potentially causes it to create new SCEV objects though,
5423 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005424 // observable from outside the class though, so casting away the
5425 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005426 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005427
Dan Gohman30733292010-01-09 18:17:45 +00005428 OS << "Classifying expressions for: ";
5429 WriteAsOperand(OS, F, /*PrintType=*/false);
5430 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005431 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005432 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005433 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005434 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005435 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005436 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005437
Dan Gohman0c689c52009-06-19 17:49:54 +00005438 const Loop *L = LI->getLoopFor((*I).getParent());
5439
Dan Gohman0bba49c2009-07-07 17:06:11 +00005440 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005441 if (AtUse != SV) {
5442 OS << " --> ";
5443 AtUse->print(OS);
5444 }
5445
5446 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005447 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005448 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005449 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005450 OS << "<<Unknown>>";
5451 } else {
5452 OS << *ExitValue;
5453 }
5454 }
5455
Chris Lattner53e677a2004-04-02 20:23:17 +00005456 OS << "\n";
5457 }
5458
Dan Gohman30733292010-01-09 18:17:45 +00005459 OS << "Determining loop execution counts for: ";
5460 WriteAsOperand(OS, F, /*PrintType=*/false);
5461 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005462 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5463 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005464}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005465