blob: a0700ba4218d42b80c683acac69915c27d5815e8 [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 Gohman0bba49c2009-07-07 17:06:11 +0000924 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000925 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000926 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000927 const SCEV *Add = getAddExpr(Start, ZMul);
928 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000929 getAddExpr(getZeroExtendExpr(Start, WideTy),
930 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
931 getZeroExtendExpr(Step, WideTy)));
932 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000933 // Return the expression with the addrec on the outside.
934 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
935 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000936 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000937
938 // Similar to above, only this time treat the step value as signed.
939 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000940 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000941 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000942 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000943 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000944 OperandExtendedAdd =
945 getAddExpr(getZeroExtendExpr(Start, WideTy),
946 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
947 getSignExtendExpr(Step, WideTy)));
948 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000949 // Return the expression with the addrec on the outside.
950 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
951 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000952 L);
953 }
954
955 // If the backedge is guarded by a comparison with the pre-inc value
956 // the addrec is safe. Also, if the entry is guarded by a comparison
957 // with the start value and the backedge is guarded by a comparison
958 // with the post-inc value, the addrec is safe.
959 if (isKnownPositive(Step)) {
960 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
961 getUnsignedRange(Step).getUnsignedMax());
962 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
963 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
964 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
965 AR->getPostIncExpr(*this), N)))
966 // Return the expression with the addrec on the outside.
967 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
968 getZeroExtendExpr(Step, Ty),
969 L);
970 } else if (isKnownNegative(Step)) {
971 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
972 getSignedRange(Step).getSignedMin());
973 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
974 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
975 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
976 AR->getPostIncExpr(*this), N)))
977 // Return the expression with the addrec on the outside.
978 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
979 getSignExtendExpr(Step, Ty),
980 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000981 }
982 }
983 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000984
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000985 // The cast wasn't folded; create an explicit cast node.
986 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000987 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
988 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000989 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000990 UniqueSCEVs.InsertNode(S, IP);
991 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000992}
993
Dan Gohman0bba49c2009-07-07 17:06:11 +0000994const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000995 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000996 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000997 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000998 assert(isSCEVable(Ty) &&
999 "This is not a conversion to a SCEVable type!");
1000 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001001
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001002 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001003 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001004 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001005 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1006 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001007 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +00001008 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001009
Dan Gohman20900ca2009-04-22 16:20:48 +00001010 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001011 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001012 return getSignExtendExpr(SS->getOperand(), Ty);
1013
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001014 // Before doing any expensive analysis, check to see if we've already
1015 // computed a SCEV for this Op and Ty.
1016 FoldingSetNodeID ID;
1017 ID.AddInteger(scSignExtend);
1018 ID.AddPointer(Op);
1019 ID.AddPointer(Ty);
1020 void *IP = 0;
1021 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1022
Dan Gohman01ecca22009-04-27 20:16:15 +00001023 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001024 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001025 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001026 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001027 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001028 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001029 const SCEV *Start = AR->getStart();
1030 const SCEV *Step = AR->getStepRecurrence(*this);
1031 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1032 const Loop *L = AR->getLoop();
1033
Dan Gohmaneb490a72009-07-25 01:22:26 +00001034 // If we have special knowledge that this addrec won't overflow,
1035 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001036 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001037 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1038 getSignExtendExpr(Step, Ty),
1039 L);
1040
Dan Gohman01ecca22009-04-27 20:16:15 +00001041 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1042 // Note that this serves two purposes: It filters out loops that are
1043 // simply not analyzable, and it covers the case where this code is
1044 // being called from within backedge-taken count analysis, such that
1045 // attempting to ask for the backedge-taken count would likely result
1046 // in infinite recursion. In the later case, the analysis code will
1047 // cope with a conservative value, and it will take care to purge
1048 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001049 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001050 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001051 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001052 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001053
1054 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001055 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001056 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001057 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001058 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001059 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1060 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001061 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001062 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001063 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +00001064 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +00001065 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001066 const SCEV *Add = getAddExpr(Start, SMul);
1067 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001068 getAddExpr(getSignExtendExpr(Start, WideTy),
1069 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1070 getSignExtendExpr(Step, WideTy)));
1071 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001072 // Return the expression with the addrec on the outside.
1073 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1074 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001075 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001076
1077 // Similar to above, only this time treat the step value as unsigned.
1078 // This covers loops that count up with an unsigned step.
1079 const SCEV *UMul =
1080 getMulExpr(CastedMaxBECount,
1081 getTruncateOrZeroExtend(Step, Start->getType()));
1082 Add = getAddExpr(Start, UMul);
1083 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001084 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001085 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1086 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001087 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001088 // Return the expression with the addrec on the outside.
1089 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1090 getZeroExtendExpr(Step, Ty),
1091 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001092 }
1093
1094 // If the backedge is guarded by a comparison with the pre-inc value
1095 // the addrec is safe. Also, if the entry is guarded by a comparison
1096 // with the start value and the backedge is guarded by a comparison
1097 // with the post-inc value, the addrec is safe.
1098 if (isKnownPositive(Step)) {
1099 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1100 getSignedRange(Step).getSignedMax());
1101 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1102 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1103 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1104 AR->getPostIncExpr(*this), N)))
1105 // Return the expression with the addrec on the outside.
1106 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1107 getSignExtendExpr(Step, Ty),
1108 L);
1109 } else if (isKnownNegative(Step)) {
1110 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1111 getSignedRange(Step).getSignedMin());
1112 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1113 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1114 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1115 AR->getPostIncExpr(*this), N)))
1116 // Return the expression with the addrec on the outside.
1117 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1118 getSignExtendExpr(Step, Ty),
1119 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001120 }
1121 }
1122 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001123
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001124 // The cast wasn't folded; create an explicit cast node.
1125 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001126 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1127 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001128 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001129 UniqueSCEVs.InsertNode(S, IP);
1130 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001131}
1132
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001133/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1134/// unspecified bits out to the given type.
1135///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001136const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001137 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001138 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1139 "This is not an extending conversion!");
1140 assert(isSCEVable(Ty) &&
1141 "This is not a conversion to a SCEVable type!");
1142 Ty = getEffectiveSCEVType(Ty);
1143
1144 // Sign-extend negative constants.
1145 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1146 if (SC->getValue()->getValue().isNegative())
1147 return getSignExtendExpr(Op, Ty);
1148
1149 // Peel off a truncate cast.
1150 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001151 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001152 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1153 return getAnyExtendExpr(NewOp, Ty);
1154 return getTruncateOrNoop(NewOp, Ty);
1155 }
1156
1157 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001158 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001159 if (!isa<SCEVZeroExtendExpr>(ZExt))
1160 return ZExt;
1161
1162 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001163 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001164 if (!isa<SCEVSignExtendExpr>(SExt))
1165 return SExt;
1166
Dan Gohmana10756e2010-01-21 02:09:26 +00001167 // Force the cast to be folded into the operands of an addrec.
1168 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1169 SmallVector<const SCEV *, 4> Ops;
1170 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1171 I != E; ++I)
1172 Ops.push_back(getAnyExtendExpr(*I, Ty));
1173 return getAddRecExpr(Ops, AR->getLoop());
1174 }
1175
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001176 // If the expression is obviously signed, use the sext cast value.
1177 if (isa<SCEVSMaxExpr>(Op))
1178 return SExt;
1179
1180 // Absent any other information, use the zext cast value.
1181 return ZExt;
1182}
1183
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001184/// CollectAddOperandsWithScales - Process the given Ops list, which is
1185/// a list of operands to be added under the given scale, update the given
1186/// map. This is a helper function for getAddRecExpr. As an example of
1187/// what it does, given a sequence of operands that would form an add
1188/// expression like this:
1189///
1190/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1191///
1192/// where A and B are constants, update the map with these values:
1193///
1194/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1195///
1196/// and add 13 + A*B*29 to AccumulatedConstant.
1197/// This will allow getAddRecExpr to produce this:
1198///
1199/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1200///
1201/// This form often exposes folding opportunities that are hidden in
1202/// the original operand list.
1203///
1204/// Return true iff it appears that any interesting folding opportunities
1205/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1206/// the common case where no interesting opportunities are present, and
1207/// is also used as a check to avoid infinite recursion.
1208///
1209static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001210CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1211 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001212 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001213 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001214 const APInt &Scale,
1215 ScalarEvolution &SE) {
1216 bool Interesting = false;
1217
1218 // Iterate over the add operands.
1219 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1220 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1221 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1222 APInt NewScale =
1223 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1224 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1225 // A multiplication of a constant with another add; recurse.
1226 Interesting |=
1227 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1228 cast<SCEVAddExpr>(Mul->getOperand(1))
1229 ->getOperands(),
1230 NewScale, SE);
1231 } else {
1232 // A multiplication of a constant with some other value. Update
1233 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001234 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1235 const SCEV *Key = SE.getMulExpr(MulOps);
1236 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001237 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001238 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001239 NewOps.push_back(Pair.first->first);
1240 } else {
1241 Pair.first->second += NewScale;
1242 // The map already had an entry for this value, which may indicate
1243 // a folding opportunity.
1244 Interesting = true;
1245 }
1246 }
1247 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1248 // Pull a buried constant out to the outside.
1249 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1250 Interesting = true;
1251 AccumulatedConstant += Scale * C->getValue()->getValue();
1252 } else {
1253 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001254 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001255 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001256 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001257 NewOps.push_back(Pair.first->first);
1258 } else {
1259 Pair.first->second += Scale;
1260 // The map already had an entry for this value, which may indicate
1261 // a folding opportunity.
1262 Interesting = true;
1263 }
1264 }
1265 }
1266
1267 return Interesting;
1268}
1269
1270namespace {
1271 struct APIntCompare {
1272 bool operator()(const APInt &LHS, const APInt &RHS) const {
1273 return LHS.ult(RHS);
1274 }
1275 };
1276}
1277
Dan Gohman6c0866c2009-05-24 23:45:28 +00001278/// getAddExpr - Get a canonical add expression, or something simpler if
1279/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001280const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1281 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001282 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001283 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001284#ifndef NDEBUG
1285 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1286 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1287 getEffectiveSCEVType(Ops[0]->getType()) &&
1288 "SCEVAddExpr operand types don't match!");
1289#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001290
Dan Gohmana10756e2010-01-21 02:09:26 +00001291 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1292 if (!HasNUW && HasNSW) {
1293 bool All = true;
1294 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1295 if (!isKnownNonNegative(Ops[i])) {
1296 All = false;
1297 break;
1298 }
1299 if (All) HasNUW = true;
1300 }
1301
Chris Lattner53e677a2004-04-02 20:23:17 +00001302 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001303 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001304
1305 // If there are any constants, fold them together.
1306 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001307 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001308 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001309 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001310 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001311 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001312 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1313 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001314 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001315 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001316 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001317 }
1318
1319 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001320 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001321 Ops.erase(Ops.begin());
1322 --Idx;
1323 }
1324 }
1325
Chris Lattner627018b2004-04-07 16:16:11 +00001326 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001327
Chris Lattner53e677a2004-04-02 20:23:17 +00001328 // Okay, check to see if the same value occurs in the operand list twice. If
1329 // so, merge them together into an multiply expression. Since we sorted the
1330 // list, these values are required to be adjacent.
1331 const Type *Ty = Ops[0]->getType();
1332 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1333 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1334 // Found a match, merge the two values into a multiply, and add any
1335 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001336 const SCEV *Two = getIntegerSCEV(2, Ty);
1337 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 if (Ops.size() == 2)
1339 return Mul;
1340 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1341 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001342 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001343 }
1344
Dan Gohman728c7f32009-05-08 21:03:19 +00001345 // Check for truncates. If all the operands are truncated from the same
1346 // type, see if factoring out the truncate would permit the result to be
1347 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1348 // if the contents of the resulting outer trunc fold to something simple.
1349 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1350 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1351 const Type *DstType = Trunc->getType();
1352 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001353 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001354 bool Ok = true;
1355 // Check all the operands to see if they can be represented in the
1356 // source type of the truncate.
1357 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1358 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1359 if (T->getOperand()->getType() != SrcType) {
1360 Ok = false;
1361 break;
1362 }
1363 LargeOps.push_back(T->getOperand());
1364 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1365 // This could be either sign or zero extension, but sign extension
1366 // is much more likely to be foldable here.
1367 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1368 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001369 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001370 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1371 if (const SCEVTruncateExpr *T =
1372 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1373 if (T->getOperand()->getType() != SrcType) {
1374 Ok = false;
1375 break;
1376 }
1377 LargeMulOps.push_back(T->getOperand());
1378 } else if (const SCEVConstant *C =
1379 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1380 // This could be either sign or zero extension, but sign extension
1381 // is much more likely to be foldable here.
1382 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1383 } else {
1384 Ok = false;
1385 break;
1386 }
1387 }
1388 if (Ok)
1389 LargeOps.push_back(getMulExpr(LargeMulOps));
1390 } else {
1391 Ok = false;
1392 break;
1393 }
1394 }
1395 if (Ok) {
1396 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001397 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001398 // If it folds to something simple, use it. Otherwise, don't.
1399 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1400 return getTruncateExpr(Fold, DstType);
1401 }
1402 }
1403
1404 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001405 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1406 ++Idx;
1407
1408 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001409 if (Idx < Ops.size()) {
1410 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001411 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001412 // If we have an add, expand the add operands onto the end of the operands
1413 // list.
1414 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1415 Ops.erase(Ops.begin()+Idx);
1416 DeletedAdd = true;
1417 }
1418
1419 // If we deleted at least one add, we added operands to the end of the list,
1420 // and they are not necessarily sorted. Recurse to resort and resimplify
1421 // any operands we just aquired.
1422 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001423 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001424 }
1425
1426 // Skip over the add expression until we get to a multiply.
1427 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1428 ++Idx;
1429
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001430 // Check to see if there are any folding opportunities present with
1431 // operands multiplied by constant values.
1432 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1433 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001434 DenseMap<const SCEV *, APInt> M;
1435 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001436 APInt AccumulatedConstant(BitWidth, 0);
1437 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1438 Ops, APInt(BitWidth, 1), *this)) {
1439 // Some interesting folding opportunity is present, so its worthwhile to
1440 // re-generate the operands list. Group the operands by constant scale,
1441 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001442 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1443 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001444 E = NewOps.end(); I != E; ++I)
1445 MulOpLists[M.find(*I)->second].push_back(*I);
1446 // Re-generate the operands list.
1447 Ops.clear();
1448 if (AccumulatedConstant != 0)
1449 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001450 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1451 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001452 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001453 Ops.push_back(getMulExpr(getConstant(I->first),
1454 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001455 if (Ops.empty())
1456 return getIntegerSCEV(0, Ty);
1457 if (Ops.size() == 1)
1458 return Ops[0];
1459 return getAddExpr(Ops);
1460 }
1461 }
1462
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 // If we are adding something to a multiply expression, make sure the
1464 // something is not already an operand of the multiply. If so, merge it into
1465 // the multiply.
1466 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001467 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001469 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001471 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001472 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001473 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 if (Mul->getNumOperands() != 2) {
1475 // If the multiply has more than two operands, we must get the
1476 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001477 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001478 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001479 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001481 const SCEV *One = getIntegerSCEV(1, Ty);
1482 const SCEV *AddOne = getAddExpr(InnerMul, One);
1483 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001484 if (Ops.size() == 2) return OuterMul;
1485 if (AddOp < Idx) {
1486 Ops.erase(Ops.begin()+AddOp);
1487 Ops.erase(Ops.begin()+Idx-1);
1488 } else {
1489 Ops.erase(Ops.begin()+Idx);
1490 Ops.erase(Ops.begin()+AddOp-1);
1491 }
1492 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001493 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001495
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 // Check this multiply against other multiplies being added together.
1497 for (unsigned OtherMulIdx = Idx+1;
1498 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1499 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001500 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001501 // If MulOp occurs in OtherMul, we can fold the two multiplies
1502 // together.
1503 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1504 OMulOp != e; ++OMulOp)
1505 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1506 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001507 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001509 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1510 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001512 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001514 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001516 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1517 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001519 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001521 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1522 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001523 if (Ops.size() == 2) return OuterMul;
1524 Ops.erase(Ops.begin()+Idx);
1525 Ops.erase(Ops.begin()+OtherMulIdx-1);
1526 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001527 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001528 }
1529 }
1530 }
1531 }
1532
1533 // If there are any add recurrences in the operands list, see if any other
1534 // added values are loop invariant. If so, we can fold them into the
1535 // recurrence.
1536 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1537 ++Idx;
1538
1539 // Scan over all recurrences, trying to fold loop invariants into them.
1540 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1541 // Scan all of the other operands to this add and add them to the vector if
1542 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001543 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001544 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001545 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1546 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1547 LIOps.push_back(Ops[i]);
1548 Ops.erase(Ops.begin()+i);
1549 --i; --e;
1550 }
1551
1552 // If we found some loop invariants, fold them into the recurrence.
1553 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001554 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001555 LIOps.push_back(AddRec->getStart());
1556
Dan Gohman0bba49c2009-07-07 17:06:11 +00001557 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001558 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001559 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001560
Dan Gohman355b4f32009-12-19 01:46:34 +00001561 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001562 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001563 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001564
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 // If all of the other operands were loop invariant, we are done.
1566 if (Ops.size() == 1) return NewRec;
1567
1568 // Otherwise, add the folded AddRec by the non-liv parts.
1569 for (unsigned i = 0;; ++i)
1570 if (Ops[i] == AddRec) {
1571 Ops[i] = NewRec;
1572 break;
1573 }
Dan Gohman246b2562007-10-22 18:31:58 +00001574 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 }
1576
1577 // Okay, if there weren't any loop invariants to be folded, check to see if
1578 // there are multiple AddRec's with the same loop induction variable being
1579 // added together. If so, we can fold them.
1580 for (unsigned OtherIdx = Idx+1;
1581 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1582 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001583 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001584 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1585 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001586 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1587 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001588 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1589 if (i >= NewOps.size()) {
1590 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1591 OtherAddRec->op_end());
1592 break;
1593 }
Dan Gohman246b2562007-10-22 18:31:58 +00001594 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001596 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001597
1598 if (Ops.size() == 2) return NewAddRec;
1599
1600 Ops.erase(Ops.begin()+Idx);
1601 Ops.erase(Ops.begin()+OtherIdx-1);
1602 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001603 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001604 }
1605 }
1606
1607 // Otherwise couldn't fold anything into this recurrence. Move onto the
1608 // next one.
1609 }
1610
1611 // Okay, it looks like we really DO need an add expr. Check to see if we
1612 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001613 FoldingSetNodeID ID;
1614 ID.AddInteger(scAddExpr);
1615 ID.AddInteger(Ops.size());
1616 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1617 ID.AddPointer(Ops[i]);
1618 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001619 SCEVAddExpr *S =
1620 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1621 if (!S) {
1622 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1623 new (S) SCEVAddExpr(ID, Ops);
1624 UniqueSCEVs.InsertNode(S, IP);
1625 }
Dan Gohman3645b012009-10-09 00:10:36 +00001626 if (HasNUW) S->setHasNoUnsignedWrap(true);
1627 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001628 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001629}
1630
Dan Gohman6c0866c2009-05-24 23:45:28 +00001631/// getMulExpr - Get a canonical multiply expression, or something simpler if
1632/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001633const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1634 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001636 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001637#ifndef NDEBUG
1638 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1639 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1640 getEffectiveSCEVType(Ops[0]->getType()) &&
1641 "SCEVMulExpr operand types don't match!");
1642#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001643
Dan Gohmana10756e2010-01-21 02:09:26 +00001644 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1645 if (!HasNUW && HasNSW) {
1646 bool All = true;
1647 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1648 if (!isKnownNonNegative(Ops[i])) {
1649 All = false;
1650 break;
1651 }
1652 if (All) HasNUW = true;
1653 }
1654
Chris Lattner53e677a2004-04-02 20:23:17 +00001655 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001656 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001657
1658 // If there are any constants, fold them together.
1659 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001660 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001661
1662 // C1*(C2+V) -> C1*C2 + C1*V
1663 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001664 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001665 if (Add->getNumOperands() == 2 &&
1666 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001667 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1668 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001669
Chris Lattner53e677a2004-04-02 20:23:17 +00001670 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001671 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001673 ConstantInt *Fold = ConstantInt::get(getContext(),
1674 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001675 RHSC->getValue()->getValue());
1676 Ops[0] = getConstant(Fold);
1677 Ops.erase(Ops.begin()+1); // Erase the folded element
1678 if (Ops.size() == 1) return Ops[0];
1679 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 }
1681
1682 // If we are left with a constant one being multiplied, strip it off.
1683 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1684 Ops.erase(Ops.begin());
1685 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001686 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 // If we have a multiply of zero, it will always be zero.
1688 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001689 } else if (Ops[0]->isAllOnesValue()) {
1690 // If we have a mul by -1 of an add, try distributing the -1 among the
1691 // add operands.
1692 if (Ops.size() == 2)
1693 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1694 SmallVector<const SCEV *, 4> NewOps;
1695 bool AnyFolded = false;
1696 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1697 I != E; ++I) {
1698 const SCEV *Mul = getMulExpr(Ops[0], *I);
1699 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1700 NewOps.push_back(Mul);
1701 }
1702 if (AnyFolded)
1703 return getAddExpr(NewOps);
1704 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001705 }
1706 }
1707
1708 // Skip over the add expression until we get to a multiply.
1709 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1710 ++Idx;
1711
1712 if (Ops.size() == 1)
1713 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001714
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 // If there are mul operands inline them all into this expression.
1716 if (Idx < Ops.size()) {
1717 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001718 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001719 // If we have an mul, expand the mul operands onto the end of the operands
1720 // list.
1721 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1722 Ops.erase(Ops.begin()+Idx);
1723 DeletedMul = true;
1724 }
1725
1726 // If we deleted at least one mul, we added operands to the end of the list,
1727 // and they are not necessarily sorted. Recurse to resort and resimplify
1728 // any operands we just aquired.
1729 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001730 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001731 }
1732
1733 // If there are any add recurrences in the operands list, see if any other
1734 // added values are loop invariant. If so, we can fold them into the
1735 // recurrence.
1736 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1737 ++Idx;
1738
1739 // Scan over all recurrences, trying to fold loop invariants into them.
1740 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1741 // Scan all of the other operands to this mul and add them to the vector if
1742 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001743 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001744 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1746 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1747 LIOps.push_back(Ops[i]);
1748 Ops.erase(Ops.begin()+i);
1749 --i; --e;
1750 }
1751
1752 // If we found some loop invariants, fold them into the recurrence.
1753 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001754 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001755 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001756 NewOps.reserve(AddRec->getNumOperands());
1757 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001758 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001759 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001760 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001761 } else {
1762 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001763 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001764 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001765 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001766 }
1767 }
1768
Dan Gohman355b4f32009-12-19 01:46:34 +00001769 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001770 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001771 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1772 HasNUW && AddRec->hasNoUnsignedWrap(),
1773 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001774
1775 // If all of the other operands were loop invariant, we are done.
1776 if (Ops.size() == 1) return NewRec;
1777
1778 // Otherwise, multiply the folded AddRec by the non-liv parts.
1779 for (unsigned i = 0;; ++i)
1780 if (Ops[i] == AddRec) {
1781 Ops[i] = NewRec;
1782 break;
1783 }
Dan Gohman246b2562007-10-22 18:31:58 +00001784 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001785 }
1786
1787 // Okay, if there weren't any loop invariants to be folded, check to see if
1788 // there are multiple AddRec's with the same loop induction variable being
1789 // multiplied together. If so, we can fold them.
1790 for (unsigned OtherIdx = Idx+1;
1791 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1792 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001793 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001794 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1795 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001796 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001797 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001798 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001799 const SCEV *B = F->getStepRecurrence(*this);
1800 const SCEV *D = G->getStepRecurrence(*this);
1801 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001802 getMulExpr(G, B),
1803 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001804 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001805 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001806 if (Ops.size() == 2) return NewAddRec;
1807
1808 Ops.erase(Ops.begin()+Idx);
1809 Ops.erase(Ops.begin()+OtherIdx-1);
1810 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001811 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001812 }
1813 }
1814
1815 // Otherwise couldn't fold anything into this recurrence. Move onto the
1816 // next one.
1817 }
1818
1819 // Okay, it looks like we really DO need an mul expr. Check to see if we
1820 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001821 FoldingSetNodeID ID;
1822 ID.AddInteger(scMulExpr);
1823 ID.AddInteger(Ops.size());
1824 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1825 ID.AddPointer(Ops[i]);
1826 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001827 SCEVMulExpr *S =
1828 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1829 if (!S) {
1830 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1831 new (S) SCEVMulExpr(ID, Ops);
1832 UniqueSCEVs.InsertNode(S, IP);
1833 }
Dan Gohman3645b012009-10-09 00:10:36 +00001834 if (HasNUW) S->setHasNoUnsignedWrap(true);
1835 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001836 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001837}
1838
Andreas Bolka8a11c982009-08-07 22:55:26 +00001839/// getUDivExpr - Get a canonical unsigned division expression, or something
1840/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001841const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1842 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001843 assert(getEffectiveSCEVType(LHS->getType()) ==
1844 getEffectiveSCEVType(RHS->getType()) &&
1845 "SCEVUDivExpr operand types don't match!");
1846
Dan Gohman622ed672009-05-04 22:02:23 +00001847 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001848 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001849 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001850 if (RHSC->isZero())
1851 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001852
Dan Gohman185cf032009-05-08 20:18:49 +00001853 // Determine if the division can be folded into the operands of
1854 // its operands.
1855 // TODO: Generalize this to non-constants by using known-bits information.
1856 const Type *Ty = LHS->getType();
1857 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1858 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1859 // For non-power-of-two values, effectively round the value up to the
1860 // nearest power of two.
1861 if (!RHSC->getValue()->getValue().isPowerOf2())
1862 ++MaxShiftAmt;
1863 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001864 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001865 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1866 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1867 if (const SCEVConstant *Step =
1868 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1869 if (!Step->getValue()->getValue()
1870 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001871 getZeroExtendExpr(AR, ExtTy) ==
1872 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1873 getZeroExtendExpr(Step, ExtTy),
1874 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001875 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001876 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1877 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1878 return getAddRecExpr(Operands, AR->getLoop());
1879 }
1880 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001881 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001882 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001883 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1884 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1885 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001886 // Find an operand that's safely divisible.
1887 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001888 const SCEV *Op = M->getOperand(i);
1889 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001890 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001891 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1892 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001893 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001894 Operands[i] = Div;
1895 return getMulExpr(Operands);
1896 }
1897 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001898 }
Dan Gohman185cf032009-05-08 20:18:49 +00001899 // (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 +00001900 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001901 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001902 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1903 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1904 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1905 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001906 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001907 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001908 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1909 break;
1910 Operands.push_back(Op);
1911 }
1912 if (Operands.size() == A->getNumOperands())
1913 return getAddExpr(Operands);
1914 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001915 }
Dan Gohman185cf032009-05-08 20:18:49 +00001916
1917 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001918 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001919 Constant *LHSCV = LHSC->getValue();
1920 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001921 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001922 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001923 }
1924 }
1925
Dan Gohman1c343752009-06-27 21:21:31 +00001926 FoldingSetNodeID ID;
1927 ID.AddInteger(scUDivExpr);
1928 ID.AddPointer(LHS);
1929 ID.AddPointer(RHS);
1930 void *IP = 0;
1931 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1932 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001933 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001934 UniqueSCEVs.InsertNode(S, IP);
1935 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001936}
1937
1938
Dan Gohman6c0866c2009-05-24 23:45:28 +00001939/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1940/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001941const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001942 const SCEV *Step, const Loop *L,
1943 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001944 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001945 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001946 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001947 if (StepChrec->getLoop() == L) {
1948 Operands.insert(Operands.end(), StepChrec->op_begin(),
1949 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001950 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001951 }
1952
1953 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001954 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001955}
1956
Dan Gohman6c0866c2009-05-24 23:45:28 +00001957/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1958/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001959const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001960ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001961 const Loop *L,
1962 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001963 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001964#ifndef NDEBUG
1965 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1966 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1967 getEffectiveSCEVType(Operands[0]->getType()) &&
1968 "SCEVAddRecExpr operand types don't match!");
1969#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001970
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001971 if (Operands.back()->isZero()) {
1972 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001973 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001974 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001975
Dan Gohmana10756e2010-01-21 02:09:26 +00001976 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1977 if (!HasNUW && HasNSW) {
1978 bool All = true;
1979 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1980 if (!isKnownNonNegative(Operands[i])) {
1981 All = false;
1982 break;
1983 }
1984 if (All) HasNUW = true;
1985 }
1986
Dan Gohmand9cc7492008-08-08 18:33:12 +00001987 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001988 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001989 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001990 if (L->contains(NestedLoop->getHeader()) ?
1991 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1992 (!NestedLoop->contains(L->getHeader()) &&
1993 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001994 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001995 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001996 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001997 // AddRecs require their operands be loop-invariant with respect to their
1998 // loops. Don't perform this transformation if it would break this
1999 // requirement.
2000 bool AllInvariant = true;
2001 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2002 if (!Operands[i]->isLoopInvariant(L)) {
2003 AllInvariant = false;
2004 break;
2005 }
2006 if (AllInvariant) {
2007 NestedOperands[0] = getAddRecExpr(Operands, L);
2008 AllInvariant = true;
2009 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2010 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2011 AllInvariant = false;
2012 break;
2013 }
2014 if (AllInvariant)
2015 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002016 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002017 }
2018 // Reset Operands to its original state.
2019 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002020 }
2021 }
2022
Dan Gohman67847532010-01-19 22:27:22 +00002023 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2024 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002025 FoldingSetNodeID ID;
2026 ID.AddInteger(scAddRecExpr);
2027 ID.AddInteger(Operands.size());
2028 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2029 ID.AddPointer(Operands[i]);
2030 ID.AddPointer(L);
2031 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002032 SCEVAddRecExpr *S =
2033 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2034 if (!S) {
2035 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2036 new (S) SCEVAddRecExpr(ID, Operands, L);
2037 UniqueSCEVs.InsertNode(S, IP);
2038 }
Dan Gohman3645b012009-10-09 00:10:36 +00002039 if (HasNUW) S->setHasNoUnsignedWrap(true);
2040 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002041 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002042}
2043
Dan Gohman9311ef62009-06-24 14:49:00 +00002044const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2045 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002046 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002047 Ops.push_back(LHS);
2048 Ops.push_back(RHS);
2049 return getSMaxExpr(Ops);
2050}
2051
Dan Gohman0bba49c2009-07-07 17:06:11 +00002052const SCEV *
2053ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002054 assert(!Ops.empty() && "Cannot get empty smax!");
2055 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002056#ifndef NDEBUG
2057 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2058 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2059 getEffectiveSCEVType(Ops[0]->getType()) &&
2060 "SCEVSMaxExpr operand types don't match!");
2061#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002062
2063 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002064 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002065
2066 // If there are any constants, fold them together.
2067 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002068 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002069 ++Idx;
2070 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002071 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002072 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002073 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002074 APIntOps::smax(LHSC->getValue()->getValue(),
2075 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002076 Ops[0] = getConstant(Fold);
2077 Ops.erase(Ops.begin()+1); // Erase the folded element
2078 if (Ops.size() == 1) return Ops[0];
2079 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002080 }
2081
Dan Gohmane5aceed2009-06-24 14:46:22 +00002082 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002083 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2084 Ops.erase(Ops.begin());
2085 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002086 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2087 // If we have an smax with a constant maximum-int, it will always be
2088 // maximum-int.
2089 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002090 }
2091 }
2092
2093 if (Ops.size() == 1) return Ops[0];
2094
2095 // Find the first SMax
2096 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2097 ++Idx;
2098
2099 // Check to see if one of the operands is an SMax. If so, expand its operands
2100 // onto our operand list, and recurse to simplify.
2101 if (Idx < Ops.size()) {
2102 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002103 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002104 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2105 Ops.erase(Ops.begin()+Idx);
2106 DeletedSMax = true;
2107 }
2108
2109 if (DeletedSMax)
2110 return getSMaxExpr(Ops);
2111 }
2112
2113 // Okay, check to see if the same value occurs in the operand list twice. If
2114 // so, delete one. Since we sorted the list, these values are required to
2115 // be adjacent.
2116 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2117 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2118 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2119 --i; --e;
2120 }
2121
2122 if (Ops.size() == 1) return Ops[0];
2123
2124 assert(!Ops.empty() && "Reduced smax down to nothing!");
2125
Nick Lewycky3e630762008-02-20 06:48:22 +00002126 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002127 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002128 FoldingSetNodeID ID;
2129 ID.AddInteger(scSMaxExpr);
2130 ID.AddInteger(Ops.size());
2131 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2132 ID.AddPointer(Ops[i]);
2133 void *IP = 0;
2134 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2135 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002136 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002137 UniqueSCEVs.InsertNode(S, IP);
2138 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002139}
2140
Dan Gohman9311ef62009-06-24 14:49:00 +00002141const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2142 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002143 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002144 Ops.push_back(LHS);
2145 Ops.push_back(RHS);
2146 return getUMaxExpr(Ops);
2147}
2148
Dan Gohman0bba49c2009-07-07 17:06:11 +00002149const SCEV *
2150ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002151 assert(!Ops.empty() && "Cannot get empty umax!");
2152 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002153#ifndef NDEBUG
2154 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2155 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2156 getEffectiveSCEVType(Ops[0]->getType()) &&
2157 "SCEVUMaxExpr operand types don't match!");
2158#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002159
2160 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002161 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002162
2163 // If there are any constants, fold them together.
2164 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002165 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002166 ++Idx;
2167 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002168 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002169 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002170 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002171 APIntOps::umax(LHSC->getValue()->getValue(),
2172 RHSC->getValue()->getValue()));
2173 Ops[0] = getConstant(Fold);
2174 Ops.erase(Ops.begin()+1); // Erase the folded element
2175 if (Ops.size() == 1) return Ops[0];
2176 LHSC = cast<SCEVConstant>(Ops[0]);
2177 }
2178
Dan Gohmane5aceed2009-06-24 14:46:22 +00002179 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002180 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2181 Ops.erase(Ops.begin());
2182 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002183 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2184 // If we have an umax with a constant maximum-int, it will always be
2185 // maximum-int.
2186 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002187 }
2188 }
2189
2190 if (Ops.size() == 1) return Ops[0];
2191
2192 // Find the first UMax
2193 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2194 ++Idx;
2195
2196 // Check to see if one of the operands is a UMax. If so, expand its operands
2197 // onto our operand list, and recurse to simplify.
2198 if (Idx < Ops.size()) {
2199 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002200 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002201 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2202 Ops.erase(Ops.begin()+Idx);
2203 DeletedUMax = true;
2204 }
2205
2206 if (DeletedUMax)
2207 return getUMaxExpr(Ops);
2208 }
2209
2210 // Okay, check to see if the same value occurs in the operand list twice. If
2211 // so, delete one. Since we sorted the list, these values are required to
2212 // be adjacent.
2213 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2214 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2215 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2216 --i; --e;
2217 }
2218
2219 if (Ops.size() == 1) return Ops[0];
2220
2221 assert(!Ops.empty() && "Reduced umax down to nothing!");
2222
2223 // Okay, it looks like we really DO need a umax expr. Check to see if we
2224 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002225 FoldingSetNodeID ID;
2226 ID.AddInteger(scUMaxExpr);
2227 ID.AddInteger(Ops.size());
2228 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2229 ID.AddPointer(Ops[i]);
2230 void *IP = 0;
2231 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2232 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002233 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002234 UniqueSCEVs.InsertNode(S, IP);
2235 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002236}
2237
Dan Gohman9311ef62009-06-24 14:49:00 +00002238const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2239 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002240 // ~smax(~x, ~y) == smin(x, y).
2241 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2242}
2243
Dan Gohman9311ef62009-06-24 14:49:00 +00002244const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2245 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002246 // ~umax(~x, ~y) == umin(x, y)
2247 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2248}
2249
Dan Gohman4f8eea82010-02-01 18:27:38 +00002250const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2251 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2252 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2253 C = ConstantFoldConstantExpression(CE, TD);
2254 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2255 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2256}
2257
2258const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2259 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2261 C = ConstantFoldConstantExpression(CE, TD);
2262 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2263 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2264}
2265
2266const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2267 unsigned FieldNo) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002268 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2269 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2270 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002271 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002272 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002273}
2274
Dan Gohman4f8eea82010-02-01 18:27:38 +00002275const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2276 Constant *FieldNo) {
2277 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002278 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2279 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohman4f8eea82010-02-01 18:27:38 +00002280 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002281 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002282}
2283
Dan Gohman0bba49c2009-07-07 17:06:11 +00002284const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002285 // Don't attempt to do anything other than create a SCEVUnknown object
2286 // here. createSCEV only calls getUnknown after checking for all other
2287 // interesting possibilities, and any other code that calls getUnknown
2288 // is doing so in order to hide a value from SCEV canonicalization.
2289
Dan Gohman1c343752009-06-27 21:21:31 +00002290 FoldingSetNodeID ID;
2291 ID.AddInteger(scUnknown);
2292 ID.AddPointer(V);
2293 void *IP = 0;
2294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2295 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002296 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002297 UniqueSCEVs.InsertNode(S, IP);
2298 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002299}
2300
Chris Lattner53e677a2004-04-02 20:23:17 +00002301//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002302// Basic SCEV Analysis and PHI Idiom Recognition Code
2303//
2304
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002305/// isSCEVable - Test if values of the given type are analyzable within
2306/// the SCEV framework. This primarily includes integer types, and it
2307/// can optionally include pointer types if the ScalarEvolution class
2308/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002309bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002310 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002311 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002312}
2313
2314/// getTypeSizeInBits - Return the size in bits of the specified type,
2315/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002316uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002317 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2318
2319 // If we have a TargetData, use it!
2320 if (TD)
2321 return TD->getTypeSizeInBits(Ty);
2322
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002323 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002324 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002325 return Ty->getPrimitiveSizeInBits();
2326
2327 // The only other support type is pointer. Without TargetData, conservatively
2328 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002329 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002330 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002331}
2332
2333/// getEffectiveSCEVType - Return a type with the same bitwidth as
2334/// the given type and which represents how SCEV will treat the given
2335/// type, for which isSCEVable must return true. For pointer types,
2336/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002337const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002338 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2339
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002340 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002341 return Ty;
2342
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002343 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002344 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002345 if (TD) return TD->getIntPtrType(getContext());
2346
2347 // Without TargetData, conservatively assume pointers are 64-bit.
2348 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002349}
Chris Lattner53e677a2004-04-02 20:23:17 +00002350
Dan Gohman0bba49c2009-07-07 17:06:11 +00002351const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002352 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002353}
2354
Chris Lattner53e677a2004-04-02 20:23:17 +00002355/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2356/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002357const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002358 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002359
Dan Gohman0bba49c2009-07-07 17:06:11 +00002360 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002361 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002362 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002363 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002364 return S;
2365}
2366
Dan Gohman6bbcba12009-06-24 00:54:57 +00002367/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002368/// specified signed integer value and return a SCEV for the constant.
Dan Gohman32efba62010-02-04 02:43:51 +00002369const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002370 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002371 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002372}
2373
2374/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2375///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002376const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002377 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002378 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002379 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002380
2381 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002382 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002383 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002384 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002385}
2386
2387/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002388const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002389 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002390 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002391 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002392
2393 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002394 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002395 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002396 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002397 return getMinusSCEV(AllOnes, V);
2398}
2399
2400/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2401///
Dan Gohman9311ef62009-06-24 14:49:00 +00002402const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2403 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002404 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002405 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002406}
2407
2408/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2409/// input value to the specified type. If the type must be extended, it is zero
2410/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002411const SCEV *
2412ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002413 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002414 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002415 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2416 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002417 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002418 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002419 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002420 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002421 return getTruncateExpr(V, Ty);
2422 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002423}
2424
2425/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2426/// input value to the specified type. If the type must be extended, it is sign
2427/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002428const SCEV *
2429ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002430 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002431 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002432 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2433 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002434 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002435 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002436 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002437 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002438 return getTruncateExpr(V, Ty);
2439 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002440}
2441
Dan Gohman467c4302009-05-13 03:46:30 +00002442/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2443/// input value to the specified type. If the type must be extended, it is zero
2444/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002445const SCEV *
2446ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002447 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002448 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2449 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002450 "Cannot noop or zero extend with non-integer arguments!");
2451 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2452 "getNoopOrZeroExtend cannot truncate!");
2453 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2454 return V; // No conversion
2455 return getZeroExtendExpr(V, Ty);
2456}
2457
2458/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2459/// input value to the specified type. If the type must be extended, it is sign
2460/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002461const SCEV *
2462ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002463 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002464 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2465 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002466 "Cannot noop or sign extend with non-integer arguments!");
2467 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2468 "getNoopOrSignExtend cannot truncate!");
2469 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2470 return V; // No conversion
2471 return getSignExtendExpr(V, Ty);
2472}
2473
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002474/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2475/// the input value to the specified type. If the type must be extended,
2476/// it is extended with unspecified bits. The conversion must not be
2477/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002478const SCEV *
2479ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002480 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002481 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2482 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002483 "Cannot noop or any extend with non-integer arguments!");
2484 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2485 "getNoopOrAnyExtend cannot truncate!");
2486 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2487 return V; // No conversion
2488 return getAnyExtendExpr(V, Ty);
2489}
2490
Dan Gohman467c4302009-05-13 03:46:30 +00002491/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2492/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002493const SCEV *
2494ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002495 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002496 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2497 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002498 "Cannot truncate or noop with non-integer arguments!");
2499 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2500 "getTruncateOrNoop cannot extend!");
2501 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2502 return V; // No conversion
2503 return getTruncateExpr(V, Ty);
2504}
2505
Dan Gohmana334aa72009-06-22 00:31:57 +00002506/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2507/// the types using zero-extension, and then perform a umax operation
2508/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002509const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2510 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002511 const SCEV *PromotedLHS = LHS;
2512 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002513
2514 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2515 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2516 else
2517 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2518
2519 return getUMaxExpr(PromotedLHS, PromotedRHS);
2520}
2521
Dan Gohmanc9759e82009-06-22 15:03:27 +00002522/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2523/// the types using zero-extension, and then perform a umin operation
2524/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002525const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2526 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002527 const SCEV *PromotedLHS = LHS;
2528 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002529
2530 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2531 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2532 else
2533 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2534
2535 return getUMinExpr(PromotedLHS, PromotedRHS);
2536}
2537
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002538/// PushDefUseChildren - Push users of the given Instruction
2539/// onto the given Worklist.
2540static void
2541PushDefUseChildren(Instruction *I,
2542 SmallVectorImpl<Instruction *> &Worklist) {
2543 // Push the def-use children onto the Worklist stack.
2544 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2545 UI != UE; ++UI)
2546 Worklist.push_back(cast<Instruction>(UI));
2547}
2548
2549/// ForgetSymbolicValue - This looks up computed SCEV values for all
2550/// instructions that depend on the given instruction and removes them from
2551/// the Scalars map if they reference SymName. This is used during PHI
2552/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002553void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002554ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2555 SmallVector<Instruction *, 16> Worklist;
2556 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002557
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002558 SmallPtrSet<Instruction *, 8> Visited;
2559 Visited.insert(I);
2560 while (!Worklist.empty()) {
2561 Instruction *I = Worklist.pop_back_val();
2562 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002563
Dan Gohman5d984912009-12-18 01:14:11 +00002564 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002565 Scalars.find(static_cast<Value *>(I));
2566 if (It != Scalars.end()) {
2567 // Short-circuit the def-use traversal if the symbolic name
2568 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002569 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002570 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002571
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002572 // SCEVUnknown for a PHI either means that it has an unrecognized
2573 // structure, or it's a PHI that's in the progress of being computed
2574 // by createNodeForPHI. In the former case, additional loop trip
2575 // count information isn't going to change anything. In the later
2576 // case, createNodeForPHI will perform the necessary updates on its
2577 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002578 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2579 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002580 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002581 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002582 }
2583
2584 PushDefUseChildren(I, Worklist);
2585 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002586}
Chris Lattner53e677a2004-04-02 20:23:17 +00002587
2588/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2589/// a loop header, making it a potential recurrence, or it doesn't.
2590///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002591const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002592 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002593 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002594 if (L->getHeader() == PN->getParent()) {
2595 // If it lives in the loop header, it has two incoming values, one
2596 // from outside the loop, and one from inside.
2597 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2598 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002599
Chris Lattner53e677a2004-04-02 20:23:17 +00002600 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002601 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002602 assert(Scalars.find(PN) == Scalars.end() &&
2603 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002604 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002605
2606 // Using this symbolic name for the PHI, analyze the value coming around
2607 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002608 Value *BEValueV = PN->getIncomingValue(BackEdge);
2609 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002610
2611 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2612 // has a special value for the first iteration of the loop.
2613
2614 // If the value coming around the backedge is an add with the symbolic
2615 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002616 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002617 // If there is a single occurrence of the symbolic value, replace it
2618 // with a recurrence.
2619 unsigned FoundIndex = Add->getNumOperands();
2620 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2621 if (Add->getOperand(i) == SymbolicName)
2622 if (FoundIndex == e) {
2623 FoundIndex = i;
2624 break;
2625 }
2626
2627 if (FoundIndex != Add->getNumOperands()) {
2628 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002629 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002630 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2631 if (i != FoundIndex)
2632 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002633 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002634
2635 // This is not a valid addrec if the step amount is varying each
2636 // loop iteration, but is not itself an addrec in this loop.
2637 if (Accum->isLoopInvariant(L) ||
2638 (isa<SCEVAddRecExpr>(Accum) &&
2639 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002640 bool HasNUW = false;
2641 bool HasNSW = false;
2642
2643 // If the increment doesn't overflow, then neither the addrec nor
2644 // the post-increment will overflow.
2645 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2646 if (OBO->hasNoUnsignedWrap())
2647 HasNUW = true;
2648 if (OBO->hasNoSignedWrap())
2649 HasNSW = true;
2650 }
2651
Dan Gohman64a845e2009-06-24 04:48:43 +00002652 const SCEV *StartVal =
2653 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002654 const SCEV *PHISCEV =
2655 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002656
Dan Gohmana10756e2010-01-21 02:09:26 +00002657 // Since the no-wrap flags are on the increment, they apply to the
2658 // post-incremented value as well.
2659 if (Accum->isLoopInvariant(L))
2660 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2661 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002662
2663 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002664 // to be symbolic. We now need to go back and purge all of the
2665 // entries for the scalars that use the symbolic expression.
2666 ForgetSymbolicName(PN, SymbolicName);
2667 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002668 return PHISCEV;
2669 }
2670 }
Dan Gohman622ed672009-05-04 22:02:23 +00002671 } else if (const SCEVAddRecExpr *AddRec =
2672 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002673 // Otherwise, this could be a loop like this:
2674 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2675 // In this case, j = {1,+,1} and BEValue is j.
2676 // Because the other in-value of i (0) fits the evolution of BEValue
2677 // i really is an addrec evolution.
2678 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002679 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002680
2681 // If StartVal = j.start - j.stride, we can use StartVal as the
2682 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002683 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002684 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002685 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002686 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002687
2688 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002689 // to be symbolic. We now need to go back and purge all of the
2690 // entries for the scalars that use the symbolic expression.
2691 ForgetSymbolicName(PN, SymbolicName);
2692 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002693 return PHISCEV;
2694 }
2695 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002696 }
2697
2698 return SymbolicName;
2699 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002700
Dan Gohmana653fc52009-07-14 14:06:25 +00002701 // It's tempting to recognize PHIs with a unique incoming value, however
2702 // this leads passes like indvars to break LCSSA form. Fortunately, such
2703 // PHIs are rare, as instcombine zaps them.
2704
Chris Lattner53e677a2004-04-02 20:23:17 +00002705 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002706 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002707}
2708
Dan Gohman26466c02009-05-08 20:26:55 +00002709/// createNodeForGEP - Expand GEP instructions into add and multiply
2710/// operations. This allows them to be analyzed by regular SCEV code.
2711///
Dan Gohmand281ed22009-12-18 02:09:29 +00002712const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002713
Dan Gohmand281ed22009-12-18 02:09:29 +00002714 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002715 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002716 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002717 // Don't attempt to analyze GEPs over unsized objects.
2718 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2719 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002720 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002721 gep_type_iterator GTI = gep_type_begin(GEP);
2722 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2723 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002724 I != E; ++I) {
2725 Value *Index = *I;
2726 // Compute the (potentially symbolic) offset in bytes for this index.
2727 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2728 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002729 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002730 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002731 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002732 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002733 } else {
2734 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002735 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman8db08df2010-02-02 01:38:49 +00002736 // Getelementptr indicies are signed.
2737 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002738 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002739 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002740 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2741 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2742 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002743 }
2744 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002745 return getAddExpr(getSCEV(Base), TotalOffset,
2746 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002747}
2748
Nick Lewycky83bb0052007-11-22 07:59:40 +00002749/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2750/// guaranteed to end in (at every loop iteration). It is, at the same time,
2751/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2752/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002753uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002754ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002755 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002756 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002757
Dan Gohman622ed672009-05-04 22:02:23 +00002758 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002759 return std::min(GetMinTrailingZeros(T->getOperand()),
2760 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002761
Dan Gohman622ed672009-05-04 22:02:23 +00002762 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002763 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2764 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2765 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002766 }
2767
Dan Gohman622ed672009-05-04 22:02:23 +00002768 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002769 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2770 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2771 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002772 }
2773
Dan Gohman622ed672009-05-04 22:02:23 +00002774 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002775 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002776 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002777 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002778 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002779 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002780 }
2781
Dan Gohman622ed672009-05-04 22:02:23 +00002782 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002783 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002784 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2785 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002786 for (unsigned i = 1, e = M->getNumOperands();
2787 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002788 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002789 BitWidth);
2790 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002791 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002792
Dan Gohman622ed672009-05-04 22:02:23 +00002793 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002794 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002795 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002796 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002797 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002798 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002799 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002800
Dan Gohman622ed672009-05-04 22:02:23 +00002801 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002802 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002803 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002804 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002805 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002806 return MinOpRes;
2807 }
2808
Dan Gohman622ed672009-05-04 22:02:23 +00002809 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002810 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002811 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002812 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002813 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002814 return MinOpRes;
2815 }
2816
Dan Gohman2c364ad2009-06-19 23:29:04 +00002817 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2818 // For a SCEVUnknown, ask ValueTracking.
2819 unsigned BitWidth = getTypeSizeInBits(U->getType());
2820 APInt Mask = APInt::getAllOnesValue(BitWidth);
2821 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2822 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2823 return Zeros.countTrailingOnes();
2824 }
2825
2826 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002827 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002828}
Chris Lattner53e677a2004-04-02 20:23:17 +00002829
Dan Gohman85b05a22009-07-13 21:35:55 +00002830/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2831///
2832ConstantRange
2833ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002834
2835 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002836 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002837
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002838 unsigned BitWidth = getTypeSizeInBits(S->getType());
2839 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2840
2841 // If the value has known zeros, the maximum unsigned value will have those
2842 // known zeros as well.
2843 uint32_t TZ = GetMinTrailingZeros(S);
2844 if (TZ != 0)
2845 ConservativeResult =
2846 ConstantRange(APInt::getMinValue(BitWidth),
2847 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2848
Dan Gohman85b05a22009-07-13 21:35:55 +00002849 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2850 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2851 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2852 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002853 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002854 }
2855
2856 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2857 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2858 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2859 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002860 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002861 }
2862
2863 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2864 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2865 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2866 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002867 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002868 }
2869
2870 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2871 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2872 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2873 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002874 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002875 }
2876
2877 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2878 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2879 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002880 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002881 }
2882
2883 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2884 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002885 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002886 }
2887
2888 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2889 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002890 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002891 }
2892
2893 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2894 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002895 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002896 }
2897
Dan Gohman85b05a22009-07-13 21:35:55 +00002898 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002899 // If there's no unsigned wrap, the value will never be less than its
2900 // initial value.
2901 if (AddRec->hasNoUnsignedWrap())
2902 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2903 ConservativeResult =
2904 ConstantRange(C->getValue()->getValue(),
2905 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002906
2907 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002908 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002909 const Type *Ty = AddRec->getType();
2910 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002911 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2912 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002913 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2914
2915 const SCEV *Start = AddRec->getStart();
2916 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2917
2918 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002919 if (!AddRec->hasNoUnsignedWrap())
2920 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002921
2922 ConstantRange StartRange = getUnsignedRange(Start);
2923 ConstantRange EndRange = getUnsignedRange(End);
2924 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2925 EndRange.getUnsignedMin());
2926 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2927 EndRange.getUnsignedMax());
2928 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002929 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002930 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002931 }
2932 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002933
2934 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002935 }
2936
2937 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2938 // For a SCEVUnknown, ask ValueTracking.
2939 unsigned BitWidth = getTypeSizeInBits(U->getType());
2940 APInt Mask = APInt::getAllOnesValue(BitWidth);
2941 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2942 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002943 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002944 return ConservativeResult;
2945 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946 }
2947
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002948 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002949}
2950
Dan Gohman85b05a22009-07-13 21:35:55 +00002951/// getSignedRange - Determine the signed range for a particular SCEV.
2952///
2953ConstantRange
2954ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002955
Dan Gohman85b05a22009-07-13 21:35:55 +00002956 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2957 return ConstantRange(C->getValue()->getValue());
2958
Dan Gohman52fddd32010-01-26 04:40:18 +00002959 unsigned BitWidth = getTypeSizeInBits(S->getType());
2960 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2961
2962 // If the value has known zeros, the maximum signed value will have those
2963 // known zeros as well.
2964 uint32_t TZ = GetMinTrailingZeros(S);
2965 if (TZ != 0)
2966 ConservativeResult =
2967 ConstantRange(APInt::getSignedMinValue(BitWidth),
2968 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2969
Dan Gohman85b05a22009-07-13 21:35:55 +00002970 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2971 ConstantRange X = getSignedRange(Add->getOperand(0));
2972 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2973 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002974 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002975 }
2976
Dan Gohman85b05a22009-07-13 21:35:55 +00002977 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2978 ConstantRange X = getSignedRange(Mul->getOperand(0));
2979 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2980 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002981 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002982 }
2983
Dan Gohman85b05a22009-07-13 21:35:55 +00002984 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2985 ConstantRange X = getSignedRange(SMax->getOperand(0));
2986 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2987 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002988 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002989 }
Dan Gohman62849c02009-06-24 01:05:09 +00002990
Dan Gohman85b05a22009-07-13 21:35:55 +00002991 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2992 ConstantRange X = getSignedRange(UMax->getOperand(0));
2993 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2994 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002995 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002996 }
Dan Gohman62849c02009-06-24 01:05:09 +00002997
Dan Gohman85b05a22009-07-13 21:35:55 +00002998 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2999 ConstantRange X = getSignedRange(UDiv->getLHS());
3000 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003001 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003002 }
Dan Gohman62849c02009-06-24 01:05:09 +00003003
Dan Gohman85b05a22009-07-13 21:35:55 +00003004 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3005 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003006 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003007 }
3008
3009 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3010 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003011 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003012 }
3013
3014 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3015 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003016 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003017 }
3018
Dan Gohman85b05a22009-07-13 21:35:55 +00003019 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003020 // If there's no signed wrap, and all the operands have the same sign or
3021 // zero, the value won't ever change sign.
3022 if (AddRec->hasNoSignedWrap()) {
3023 bool AllNonNeg = true;
3024 bool AllNonPos = true;
3025 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3026 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3027 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3028 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003029 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003030 ConservativeResult = ConservativeResult.intersectWith(
3031 ConstantRange(APInt(BitWidth, 0),
3032 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003033 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003034 ConservativeResult = ConservativeResult.intersectWith(
3035 ConstantRange(APInt::getSignedMinValue(BitWidth),
3036 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003037 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003038
3039 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003040 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003041 const Type *Ty = AddRec->getType();
3042 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003043 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3044 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003045 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3046
3047 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003048 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3049
3050 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003051 if (!AddRec->hasNoSignedWrap())
3052 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003053
3054 ConstantRange StartRange = getSignedRange(Start);
3055 ConstantRange EndRange = getSignedRange(End);
3056 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3057 EndRange.getSignedMin());
3058 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3059 EndRange.getSignedMax());
3060 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003061 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003062 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003063 }
Dan Gohman62849c02009-06-24 01:05:09 +00003064 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003065
3066 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003067 }
3068
Dan Gohman2c364ad2009-06-19 23:29:04 +00003069 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3070 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003071 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003072 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003073 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3074 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003075 return ConservativeResult;
3076 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003077 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003078 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003079 }
3080
Dan Gohman52fddd32010-01-26 04:40:18 +00003081 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003082}
3083
Chris Lattner53e677a2004-04-02 20:23:17 +00003084/// createSCEV - We know that there is no SCEV for the specified value.
3085/// Analyze the expression.
3086///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003087const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003088 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003089 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003090
Dan Gohman6c459a22008-06-22 19:56:46 +00003091 unsigned Opcode = Instruction::UserOp1;
3092 if (Instruction *I = dyn_cast<Instruction>(V))
3093 Opcode = I->getOpcode();
3094 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3095 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003096 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3097 return getConstant(CI);
3098 else if (isa<ConstantPointerNull>(V))
3099 return getIntegerSCEV(0, V->getType());
3100 else if (isa<UndefValue>(V))
3101 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003102 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3103 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003104 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003105 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003106
Dan Gohmanca178902009-07-17 20:47:02 +00003107 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003108 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003109 case Instruction::Add:
3110 // Don't transfer the NSW and NUW bits from the Add instruction to the
3111 // Add expression, because the Instruction may be guarded by control
3112 // flow and the no-overflow bits may not be valid for the expression in
3113 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003114 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003115 getSCEV(U->getOperand(1)));
3116 case Instruction::Mul:
3117 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3118 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003119 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003120 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003121 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003122 return getUDivExpr(getSCEV(U->getOperand(0)),
3123 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003124 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003125 return getMinusSCEV(getSCEV(U->getOperand(0)),
3126 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003127 case Instruction::And:
3128 // For an expression like x&255 that merely masks off the high bits,
3129 // use zext(trunc(x)) as the SCEV expression.
3130 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003131 if (CI->isNullValue())
3132 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003133 if (CI->isAllOnesValue())
3134 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003135 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003136
3137 // Instcombine's ShrinkDemandedConstant may strip bits out of
3138 // constants, obscuring what would otherwise be a low-bits mask.
3139 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3140 // knew about to reconstruct a low-bits mask value.
3141 unsigned LZ = A.countLeadingZeros();
3142 unsigned BitWidth = A.getBitWidth();
3143 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3144 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3145 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3146
3147 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3148
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003149 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003150 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003151 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003152 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003153 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003154 }
3155 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003156
Dan Gohman6c459a22008-06-22 19:56:46 +00003157 case Instruction::Or:
3158 // If the RHS of the Or is a constant, we may have something like:
3159 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3160 // optimizations will transparently handle this case.
3161 //
3162 // In order for this transformation to be safe, the LHS must be of the
3163 // form X*(2^n) and the Or constant must be less than 2^n.
3164 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003165 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003166 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003167 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003168 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3169 // Build a plain add SCEV.
3170 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3171 // If the LHS of the add was an addrec and it has no-wrap flags,
3172 // transfer the no-wrap flags, since an or won't introduce a wrap.
3173 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3174 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3175 if (OldAR->hasNoUnsignedWrap())
3176 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3177 if (OldAR->hasNoSignedWrap())
3178 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3179 }
3180 return S;
3181 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003182 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003183 break;
3184 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003185 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003186 // If the RHS of the xor is a signbit, then this is just an add.
3187 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003188 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003189 return getAddExpr(getSCEV(U->getOperand(0)),
3190 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003191
3192 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003193 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003194 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003195
3196 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3197 // This is a variant of the check for xor with -1, and it handles
3198 // the case where instcombine has trimmed non-demanded bits out
3199 // of an xor with -1.
3200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3201 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3202 if (BO->getOpcode() == Instruction::And &&
3203 LCI->getValue() == CI->getValue())
3204 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003205 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003206 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003207 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003208 const Type *Z0Ty = Z0->getType();
3209 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3210
3211 // If C is a low-bits mask, the zero extend is zerving to
3212 // mask off the high bits. Complement the operand and
3213 // re-apply the zext.
3214 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3215 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3216
3217 // If C is a single bit, it may be in the sign-bit position
3218 // before the zero-extend. In this case, represent the xor
3219 // using an add, which is equivalent, and re-apply the zext.
3220 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3221 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3222 Trunc.isSignBit())
3223 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3224 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003225 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003226 }
3227 break;
3228
3229 case Instruction::Shl:
3230 // Turn shift left of a constant amount into a multiply.
3231 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003232 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003233 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003234 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003235 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003236 }
3237 break;
3238
Nick Lewycky01eaf802008-07-07 06:15:49 +00003239 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003240 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003241 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003242 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003243 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003244 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003245 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003246 }
3247 break;
3248
Dan Gohman4ee29af2009-04-21 02:26:00 +00003249 case Instruction::AShr:
3250 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3251 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3252 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3253 if (L->getOpcode() == Instruction::Shl &&
3254 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003255 unsigned BitWidth = getTypeSizeInBits(U->getType());
3256 uint64_t Amt = BitWidth - CI->getZExtValue();
3257 if (Amt == BitWidth)
3258 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3259 if (Amt > BitWidth)
3260 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003261 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003262 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003263 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003264 U->getType());
3265 }
3266 break;
3267
Dan Gohman6c459a22008-06-22 19:56:46 +00003268 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003269 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003270
3271 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003272 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003273
3274 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003275 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003276
3277 case Instruction::BitCast:
3278 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003279 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003280 return getSCEV(U->getOperand(0));
3281 break;
3282
Dan Gohman4f8eea82010-02-01 18:27:38 +00003283 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3284 // lead to pointer expressions which cannot safely be expanded to GEPs,
3285 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3286 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003287
Dan Gohman26466c02009-05-08 20:26:55 +00003288 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003289 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003290
Dan Gohman6c459a22008-06-22 19:56:46 +00003291 case Instruction::PHI:
3292 return createNodeForPHI(cast<PHINode>(U));
3293
3294 case Instruction::Select:
3295 // This could be a smax or umax that was lowered earlier.
3296 // Try to recover it.
3297 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3298 Value *LHS = ICI->getOperand(0);
3299 Value *RHS = ICI->getOperand(1);
3300 switch (ICI->getPredicate()) {
3301 case ICmpInst::ICMP_SLT:
3302 case ICmpInst::ICMP_SLE:
3303 std::swap(LHS, RHS);
3304 // fall through
3305 case ICmpInst::ICMP_SGT:
3306 case ICmpInst::ICMP_SGE:
3307 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003308 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003309 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003310 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003311 break;
3312 case ICmpInst::ICMP_ULT:
3313 case ICmpInst::ICMP_ULE:
3314 std::swap(LHS, RHS);
3315 // fall through
3316 case ICmpInst::ICMP_UGT:
3317 case ICmpInst::ICMP_UGE:
3318 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003319 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003320 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003321 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003322 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003323 case ICmpInst::ICMP_NE:
3324 // n != 0 ? n : 1 -> umax(n, 1)
3325 if (LHS == U->getOperand(1) &&
3326 isa<ConstantInt>(U->getOperand(2)) &&
3327 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3328 isa<ConstantInt>(RHS) &&
3329 cast<ConstantInt>(RHS)->isZero())
3330 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3331 break;
3332 case ICmpInst::ICMP_EQ:
3333 // n == 0 ? 1 : n -> umax(n, 1)
3334 if (LHS == U->getOperand(2) &&
3335 isa<ConstantInt>(U->getOperand(1)) &&
3336 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3337 isa<ConstantInt>(RHS) &&
3338 cast<ConstantInt>(RHS)->isZero())
3339 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3340 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003341 default:
3342 break;
3343 }
3344 }
3345
3346 default: // We cannot analyze this expression.
3347 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003348 }
3349
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003350 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003351}
3352
3353
3354
3355//===----------------------------------------------------------------------===//
3356// Iteration Count Computation Code
3357//
3358
Dan Gohman46bdfb02009-02-24 18:55:53 +00003359/// getBackedgeTakenCount - If the specified loop has a predictable
3360/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3361/// object. The backedge-taken count is the number of times the loop header
3362/// will be branched to from within the loop. This is one less than the
3363/// trip count of the loop, since it doesn't count the first iteration,
3364/// when the header is branched to from outside the loop.
3365///
3366/// Note that it is not valid to call this method on a loop without a
3367/// loop-invariant backedge-taken count (see
3368/// hasLoopInvariantBackedgeTakenCount).
3369///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003370const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003371 return getBackedgeTakenInfo(L).Exact;
3372}
3373
3374/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3375/// return the least SCEV value that is known never to be less than the
3376/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003377const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003378 return getBackedgeTakenInfo(L).Max;
3379}
3380
Dan Gohman59ae6b92009-07-08 19:23:34 +00003381/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3382/// onto the given Worklist.
3383static void
3384PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3385 BasicBlock *Header = L->getHeader();
3386
3387 // Push all Loop-header PHIs onto the Worklist stack.
3388 for (BasicBlock::iterator I = Header->begin();
3389 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3390 Worklist.push_back(PN);
3391}
3392
Dan Gohmana1af7572009-04-30 20:47:05 +00003393const ScalarEvolution::BackedgeTakenInfo &
3394ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003395 // Initially insert a CouldNotCompute for this loop. If the insertion
3396 // succeeds, procede to actually compute a backedge-taken count and
3397 // update the value. The temporary CouldNotCompute value tells SCEV
3398 // code elsewhere that it shouldn't attempt to request a new
3399 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003400 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003401 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3402 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003403 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3404 if (BECount.Exact != getCouldNotCompute()) {
3405 assert(BECount.Exact->isLoopInvariant(L) &&
3406 BECount.Max->isLoopInvariant(L) &&
3407 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003408 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003409
Dan Gohman01ecca22009-04-27 20:16:15 +00003410 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003411 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003412 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003413 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003414 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003415 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003416 if (isa<PHINode>(L->getHeader()->begin()))
3417 // Only count loops that have phi nodes as not being computable.
3418 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003419 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003420
3421 // Now that we know more about the trip count for this loop, forget any
3422 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003423 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003424 // information. This is similar to the code in forgetLoop, except that
3425 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003426 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003427 SmallVector<Instruction *, 16> Worklist;
3428 PushLoopPHIs(L, Worklist);
3429
3430 SmallPtrSet<Instruction *, 8> Visited;
3431 while (!Worklist.empty()) {
3432 Instruction *I = Worklist.pop_back_val();
3433 if (!Visited.insert(I)) continue;
3434
Dan Gohman5d984912009-12-18 01:14:11 +00003435 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003436 Scalars.find(static_cast<Value *>(I));
3437 if (It != Scalars.end()) {
3438 // SCEVUnknown for a PHI either means that it has an unrecognized
3439 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003440 // by createNodeForPHI. In the former case, additional loop trip
3441 // count information isn't going to change anything. In the later
3442 // case, createNodeForPHI will perform the necessary updates on its
3443 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003444 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3445 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003446 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003447 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003448 if (PHINode *PN = dyn_cast<PHINode>(I))
3449 ConstantEvolutionLoopExitValue.erase(PN);
3450 }
3451
3452 PushDefUseChildren(I, Worklist);
3453 }
3454 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003455 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003456 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003457}
3458
Dan Gohman4c7279a2009-10-31 15:04:55 +00003459/// forgetLoop - This method should be called by the client when it has
3460/// changed a loop in a way that may effect ScalarEvolution's ability to
3461/// compute a trip count, or if the loop is deleted.
3462void ScalarEvolution::forgetLoop(const Loop *L) {
3463 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003464 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003465
Dan Gohman4c7279a2009-10-31 15:04:55 +00003466 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003467 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003468 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003469
Dan Gohman59ae6b92009-07-08 19:23:34 +00003470 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003471 while (!Worklist.empty()) {
3472 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003473 if (!Visited.insert(I)) continue;
3474
Dan Gohman5d984912009-12-18 01:14:11 +00003475 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003476 Scalars.find(static_cast<Value *>(I));
3477 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003478 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003479 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003480 if (PHINode *PN = dyn_cast<PHINode>(I))
3481 ConstantEvolutionLoopExitValue.erase(PN);
3482 }
3483
3484 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003485 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003486}
3487
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003488/// forgetValue - This method should be called by the client when it has
3489/// changed a value in a way that may effect its value, or which may
3490/// disconnect it from a def-use chain linking it to a loop.
3491void ScalarEvolution::forgetValue(Value *V) {
3492 Instruction *I = dyn_cast<Instruction>(V);
3493 if (!I) return;
3494
3495 // Drop information about expressions based on loop-header PHIs.
3496 SmallVector<Instruction *, 16> Worklist;
3497 Worklist.push_back(I);
3498
3499 SmallPtrSet<Instruction *, 8> Visited;
3500 while (!Worklist.empty()) {
3501 I = Worklist.pop_back_val();
3502 if (!Visited.insert(I)) continue;
3503
3504 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3505 Scalars.find(static_cast<Value *>(I));
3506 if (It != Scalars.end()) {
3507 ValuesAtScopes.erase(It->second);
3508 Scalars.erase(It);
3509 if (PHINode *PN = dyn_cast<PHINode>(I))
3510 ConstantEvolutionLoopExitValue.erase(PN);
3511 }
3512
3513 PushDefUseChildren(I, Worklist);
3514 }
3515}
3516
Dan Gohman46bdfb02009-02-24 18:55:53 +00003517/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3518/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003519ScalarEvolution::BackedgeTakenInfo
3520ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003521 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003522 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003523
Dan Gohmana334aa72009-06-22 00:31:57 +00003524 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003525 const SCEV *BECount = getCouldNotCompute();
3526 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003527 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003528 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3529 BackedgeTakenInfo NewBTI =
3530 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003531
Dan Gohman1c343752009-06-27 21:21:31 +00003532 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003533 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003534 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003535 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003536 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003537 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003538 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003539 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003540 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003541 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003542 }
Dan Gohman1c343752009-06-27 21:21:31 +00003543 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003544 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003545 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003546 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003547 }
3548
3549 return BackedgeTakenInfo(BECount, MaxBECount);
3550}
3551
3552/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3553/// of the specified loop will execute if it exits via the specified block.
3554ScalarEvolution::BackedgeTakenInfo
3555ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3556 BasicBlock *ExitingBlock) {
3557
3558 // Okay, we've chosen an exiting block. See what condition causes us to
3559 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003560 //
3561 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003562 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003563 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003564 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003565
Chris Lattner8b0e3602007-01-07 02:24:26 +00003566 // At this point, we know we have a conditional branch that determines whether
3567 // the loop is exited. However, we don't know if the branch is executed each
3568 // time through the loop. If not, then the execution count of the branch will
3569 // not be equal to the trip count of the loop.
3570 //
3571 // Currently we check for this by checking to see if the Exit branch goes to
3572 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003573 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003574 // loop header. This is common for un-rotated loops.
3575 //
3576 // If both of those tests fail, walk up the unique predecessor chain to the
3577 // header, stopping if there is an edge that doesn't exit the loop. If the
3578 // header is reached, the execution count of the branch will be equal to the
3579 // trip count of the loop.
3580 //
3581 // More extensive analysis could be done to handle more cases here.
3582 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003583 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003584 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003585 ExitBr->getParent() != L->getHeader()) {
3586 // The simple checks failed, try climbing the unique predecessor chain
3587 // up to the header.
3588 bool Ok = false;
3589 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3590 BasicBlock *Pred = BB->getUniquePredecessor();
3591 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003592 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003593 TerminatorInst *PredTerm = Pred->getTerminator();
3594 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3595 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3596 if (PredSucc == BB)
3597 continue;
3598 // If the predecessor has a successor that isn't BB and isn't
3599 // outside the loop, assume the worst.
3600 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003601 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003602 }
3603 if (Pred == L->getHeader()) {
3604 Ok = true;
3605 break;
3606 }
3607 BB = Pred;
3608 }
3609 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003610 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003611 }
3612
3613 // Procede to the next level to examine the exit condition expression.
3614 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3615 ExitBr->getSuccessor(0),
3616 ExitBr->getSuccessor(1));
3617}
3618
3619/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3620/// backedge of the specified loop will execute if its exit condition
3621/// were a conditional branch of ExitCond, TBB, and FBB.
3622ScalarEvolution::BackedgeTakenInfo
3623ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3624 Value *ExitCond,
3625 BasicBlock *TBB,
3626 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003627 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003628 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3629 if (BO->getOpcode() == Instruction::And) {
3630 // Recurse on the operands of the and.
3631 BackedgeTakenInfo BTI0 =
3632 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3633 BackedgeTakenInfo BTI1 =
3634 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003635 const SCEV *BECount = getCouldNotCompute();
3636 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003637 if (L->contains(TBB)) {
3638 // Both conditions must be true for the loop to continue executing.
3639 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003640 if (BTI0.Exact == getCouldNotCompute() ||
3641 BTI1.Exact == getCouldNotCompute())
3642 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003643 else
3644 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003645 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003646 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003647 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003648 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003649 else
3650 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003651 } else {
3652 // Both conditions must be true for the loop to exit.
3653 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003654 if (BTI0.Exact != getCouldNotCompute() &&
3655 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003656 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003657 if (BTI0.Max != getCouldNotCompute() &&
3658 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003659 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3660 }
3661
3662 return BackedgeTakenInfo(BECount, MaxBECount);
3663 }
3664 if (BO->getOpcode() == Instruction::Or) {
3665 // Recurse on the operands of the or.
3666 BackedgeTakenInfo BTI0 =
3667 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3668 BackedgeTakenInfo BTI1 =
3669 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003670 const SCEV *BECount = getCouldNotCompute();
3671 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003672 if (L->contains(FBB)) {
3673 // Both conditions must be false for the loop to continue executing.
3674 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003675 if (BTI0.Exact == getCouldNotCompute() ||
3676 BTI1.Exact == getCouldNotCompute())
3677 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003678 else
3679 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003680 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003681 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003682 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003683 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003684 else
3685 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003686 } else {
3687 // Both conditions must be false for the loop to exit.
3688 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003689 if (BTI0.Exact != getCouldNotCompute() &&
3690 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003691 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003692 if (BTI0.Max != getCouldNotCompute() &&
3693 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003694 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3695 }
3696
3697 return BackedgeTakenInfo(BECount, MaxBECount);
3698 }
3699 }
3700
3701 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3702 // Procede to the next level to examine the icmp.
3703 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3704 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003705
Dan Gohman00cb5b72010-02-19 18:12:07 +00003706 // Check for a constant condition. These are normally stripped out by
3707 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3708 // preserve the CFG and is temporarily leaving constant conditions
3709 // in place.
3710 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3711 if (L->contains(FBB) == !CI->getZExtValue())
3712 // The backedge is always taken.
3713 return getCouldNotCompute();
3714 else
3715 // The backedge is never taken.
3716 return getIntegerSCEV(0, CI->getType());
3717 }
3718
Eli Friedman361e54d2009-05-09 12:32:42 +00003719 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003720 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3721}
3722
3723/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3724/// backedge of the specified loop will execute if its exit condition
3725/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3726ScalarEvolution::BackedgeTakenInfo
3727ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3728 ICmpInst *ExitCond,
3729 BasicBlock *TBB,
3730 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003731
Reid Spencere4d87aa2006-12-23 06:05:41 +00003732 // If the condition was exit on true, convert the condition to exit on false
3733 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003734 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003736 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003737 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003738
3739 // Handle common loops like: for (X = "string"; *X; ++X)
3740 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3741 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003742 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003743 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003744 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3745 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3746 return BackedgeTakenInfo(ItCnt,
3747 isa<SCEVConstant>(ItCnt) ? ItCnt :
3748 getConstant(APInt::getMaxValue(BitWidth)-1));
3749 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003750 }
3751
Dan Gohman0bba49c2009-07-07 17:06:11 +00003752 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3753 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003754
3755 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003756 LHS = getSCEVAtScope(LHS, L);
3757 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003758
Dan Gohman64a845e2009-06-24 04:48:43 +00003759 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003761 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3762 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003763 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003764 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003765 }
3766
Chris Lattner53e677a2004-04-02 20:23:17 +00003767 // If we have a comparison of a chrec against a constant, try to use value
3768 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003769 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3770 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003771 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003772 // Form the constant range.
3773 ConstantRange CompRange(
3774 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003775
Dan Gohman0bba49c2009-07-07 17:06:11 +00003776 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003777 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003778 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003779
Chris Lattner53e677a2004-04-02 20:23:17 +00003780 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003781 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003782 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003783 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003785 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003786 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003787 case ICmpInst::ICMP_EQ: { // while (X == Y)
3788 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003789 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003791 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003792 }
3793 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003794 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3795 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003796 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003797 }
3798 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003799 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3800 getNotSCEV(RHS), L, true);
3801 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003802 break;
3803 }
3804 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003805 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3806 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003807 break;
3808 }
3809 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003810 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3811 getNotSCEV(RHS), L, false);
3812 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003813 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003815 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003816#if 0
David Greene25e0e872009-12-23 22:18:14 +00003817 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003818 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003819 dbgs() << "[unsigned] ";
3820 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003821 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003822 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003823#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003824 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003825 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003826 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003827 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003828}
3829
Chris Lattner673e02b2004-10-12 01:49:27 +00003830static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003831EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3832 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003833 const SCEV *InVal = SE.getConstant(C);
3834 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003835 assert(isa<SCEVConstant>(Val) &&
3836 "Evaluation of SCEV at constant didn't fold correctly?");
3837 return cast<SCEVConstant>(Val)->getValue();
3838}
3839
3840/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3841/// and a GEP expression (missing the pointer index) indexing into it, return
3842/// the addressed element of the initializer or null if the index expression is
3843/// invalid.
3844static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003845GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003846 const std::vector<ConstantInt*> &Indices) {
3847 Constant *Init = GV->getInitializer();
3848 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003849 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003850 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3851 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3852 Init = cast<Constant>(CS->getOperand(Idx));
3853 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3854 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3855 Init = cast<Constant>(CA->getOperand(Idx));
3856 } else if (isa<ConstantAggregateZero>(Init)) {
3857 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3858 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003859 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003860 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3861 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003862 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003863 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003864 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003865 }
3866 return 0;
3867 } else {
3868 return 0; // Unknown initializer type
3869 }
3870 }
3871 return Init;
3872}
3873
Dan Gohman46bdfb02009-02-24 18:55:53 +00003874/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3875/// 'icmp op load X, cst', try to see if we can compute the backedge
3876/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003877const SCEV *
3878ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3879 LoadInst *LI,
3880 Constant *RHS,
3881 const Loop *L,
3882 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003883 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003884
3885 // Check to see if the loaded pointer is a getelementptr of a global.
3886 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003887 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003888
3889 // Make sure that it is really a constant global we are gepping, with an
3890 // initializer, and make sure the first IDX is really 0.
3891 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003892 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003893 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3894 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003895 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003896
3897 // Okay, we allow one non-constant index into the GEP instruction.
3898 Value *VarIdx = 0;
3899 std::vector<ConstantInt*> Indexes;
3900 unsigned VarIdxNum = 0;
3901 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3902 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3903 Indexes.push_back(CI);
3904 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003905 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003906 VarIdx = GEP->getOperand(i);
3907 VarIdxNum = i-2;
3908 Indexes.push_back(0);
3909 }
3910
3911 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3912 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003913 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003914 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003915
3916 // We can only recognize very limited forms of loop index expressions, in
3917 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003918 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003919 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3920 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3921 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003922 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003923
3924 unsigned MaxSteps = MaxBruteForceIterations;
3925 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003926 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003927 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003928 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003929
3930 // Form the GEP offset.
3931 Indexes[VarIdxNum] = Val;
3932
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003933 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003934 if (Result == 0) break; // Cannot compute!
3935
3936 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003938 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003939 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003940#if 0
David Greene25e0e872009-12-23 22:18:14 +00003941 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003942 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3943 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003944#endif
3945 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003946 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003947 }
3948 }
Dan Gohman1c343752009-06-27 21:21:31 +00003949 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003950}
3951
3952
Chris Lattner3221ad02004-04-17 22:58:41 +00003953/// CanConstantFold - Return true if we can constant fold an instruction of the
3954/// specified type, assuming that all operands were constants.
3955static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003956 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003957 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3958 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003959
Chris Lattner3221ad02004-04-17 22:58:41 +00003960 if (const CallInst *CI = dyn_cast<CallInst>(I))
3961 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003962 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003963 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003964}
3965
Chris Lattner3221ad02004-04-17 22:58:41 +00003966/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3967/// in the loop that V is derived from. We allow arbitrary operations along the
3968/// way, but the operands of an operation must either be constants or a value
3969/// derived from a constant PHI. If this expression does not fit with these
3970/// constraints, return null.
3971static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3972 // If this is not an instruction, or if this is an instruction outside of the
3973 // loop, it can't be derived from a loop PHI.
3974 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003975 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003976
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003977 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003978 if (L->getHeader() == I->getParent())
3979 return PN;
3980 else
3981 // We don't currently keep track of the control flow needed to evaluate
3982 // PHIs, so we cannot handle PHIs inside of loops.
3983 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003984 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003985
3986 // If we won't be able to constant fold this expression even if the operands
3987 // are constants, return early.
3988 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003989
Chris Lattner3221ad02004-04-17 22:58:41 +00003990 // Otherwise, we can evaluate this instruction if all of its operands are
3991 // constant or derived from a PHI node themselves.
3992 PHINode *PHI = 0;
3993 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3994 if (!(isa<Constant>(I->getOperand(Op)) ||
3995 isa<GlobalValue>(I->getOperand(Op)))) {
3996 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3997 if (P == 0) return 0; // Not evolving from PHI
3998 if (PHI == 0)
3999 PHI = P;
4000 else if (PHI != P)
4001 return 0; // Evolving from multiple different PHIs.
4002 }
4003
4004 // This is a expression evolving from a constant PHI!
4005 return PHI;
4006}
4007
4008/// EvaluateExpression - Given an expression that passes the
4009/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4010/// in the loop has the value PHIVal. If we can't fold this expression for some
4011/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004012static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4013 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004014 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004015 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00004016 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00004017 Instruction *I = cast<Instruction>(V);
4018
4019 std::vector<Constant*> Operands;
4020 Operands.resize(I->getNumOperands());
4021
4022 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004023 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004024 if (Operands[i] == 0) return 0;
4025 }
4026
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004027 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004028 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004029 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004030 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004031 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004032}
4033
4034/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4035/// in the header of its containing loop, we know the loop executes a
4036/// constant number of times, and the PHI node is just a recurrence
4037/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004038Constant *
4039ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004040 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004041 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004042 std::map<PHINode*, Constant*>::iterator I =
4043 ConstantEvolutionLoopExitValue.find(PN);
4044 if (I != ConstantEvolutionLoopExitValue.end())
4045 return I->second;
4046
Dan Gohman46bdfb02009-02-24 18:55:53 +00004047 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00004048 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4049
4050 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4051
4052 // Since the loop is canonicalized, the PHI node must have two entries. One
4053 // entry must be a constant (coming in from outside of the loop), and the
4054 // second must be derived from the same PHI.
4055 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4056 Constant *StartCST =
4057 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4058 if (StartCST == 0)
4059 return RetVal = 0; // Must be a constant.
4060
4061 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4062 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4063 if (PN2 != PN)
4064 return RetVal = 0; // Not derived from same PHI.
4065
4066 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004067 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004068 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004069
Dan Gohman46bdfb02009-02-24 18:55:53 +00004070 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004071 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004072 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4073 if (IterationNum == NumIterations)
4074 return RetVal = PHIVal; // Got exit value!
4075
4076 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004077 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004078 if (NextPHI == PHIVal)
4079 return RetVal = NextPHI; // Stopped evolving!
4080 if (NextPHI == 0)
4081 return 0; // Couldn't evaluate!
4082 PHIVal = NextPHI;
4083 }
4084}
4085
Dan Gohman07ad19b2009-07-27 16:09:48 +00004086/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004087/// constant number of times (the condition evolves only from constants),
4088/// try to evaluate a few iterations of the loop until we get the exit
4089/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004090/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004091const SCEV *
4092ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4093 Value *Cond,
4094 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004095 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004096 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004097
4098 // Since the loop is canonicalized, the PHI node must have two entries. One
4099 // entry must be a constant (coming in from outside of the loop), and the
4100 // second must be derived from the same PHI.
4101 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4102 Constant *StartCST =
4103 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004104 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004105
4106 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4107 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004108 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004109
4110 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4111 // the loop symbolically to determine when the condition gets a value of
4112 // "ExitWhen".
4113 unsigned IterationNum = 0;
4114 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4115 for (Constant *PHIVal = StartCST;
4116 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004117 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004118 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004119
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004120 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004121 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004122
Reid Spencere8019bb2007-03-01 07:25:48 +00004123 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004124 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004125 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004126 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004127
Chris Lattner3221ad02004-04-17 22:58:41 +00004128 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004129 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004130 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004131 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004132 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004133 }
4134
4135 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004136 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004137}
4138
Dan Gohmane7125f42009-09-03 15:00:26 +00004139/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004140/// at the specified scope in the program. The L value specifies a loop
4141/// nest to evaluate the expression at, where null is the top-level or a
4142/// specified loop is immediately inside of the loop.
4143///
4144/// This method can be used to compute the exit value for a variable defined
4145/// in a loop by querying what the value will hold in the parent loop.
4146///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004147/// In the case that a relevant loop exit value cannot be computed, the
4148/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004149const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004150 // Check to see if we've folded this expression at this loop before.
4151 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4152 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4153 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4154 if (!Pair.second)
4155 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004156
Dan Gohman42214892009-08-31 21:15:23 +00004157 // Otherwise compute it.
4158 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004159 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004160 return C;
4161}
4162
4163const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004164 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004165
Nick Lewycky3e630762008-02-20 06:48:22 +00004166 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004167 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004168 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004169 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004170 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004171 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4172 if (PHINode *PN = dyn_cast<PHINode>(I))
4173 if (PN->getParent() == LI->getHeader()) {
4174 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004175 // to see if the loop that contains it has a known backedge-taken
4176 // count. If so, we may be able to force computation of the exit
4177 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004178 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004179 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004180 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004181 // Okay, we know how many times the containing loop executes. If
4182 // this is a constant evolving PHI node, get the final value at
4183 // the specified iteration number.
4184 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004185 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004186 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004187 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004188 }
4189 }
4190
Reid Spencer09906f32006-12-04 21:33:23 +00004191 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004192 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004193 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004194 // result. This is particularly useful for computing loop exit values.
4195 if (CanConstantFold(I)) {
4196 std::vector<Constant*> Operands;
4197 Operands.reserve(I->getNumOperands());
4198 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4199 Value *Op = I->getOperand(i);
4200 if (Constant *C = dyn_cast<Constant>(Op)) {
4201 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004202 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004203 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004204 // non-integer and non-pointer, don't even try to analyze them
4205 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004206 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004207 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004208
Dan Gohman5d984912009-12-18 01:14:11 +00004209 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004210 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004211 Constant *C = SC->getValue();
4212 if (C->getType() != Op->getType())
4213 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4214 Op->getType(),
4215 false),
4216 C, Op->getType());
4217 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004218 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004219 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4220 if (C->getType() != Op->getType())
4221 C =
4222 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4223 Op->getType(),
4224 false),
4225 C, Op->getType());
4226 Operands.push_back(C);
4227 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004228 return V;
4229 } else {
4230 return V;
4231 }
4232 }
4233 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004234
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004235 Constant *C;
4236 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4237 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004238 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004239 else
4240 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004241 &Operands[0], Operands.size(), TD);
Dan Gohman09987962009-06-29 21:31:18 +00004242 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004243 }
4244 }
4245
4246 // This is some other type of SCEVUnknown, just return it.
4247 return V;
4248 }
4249
Dan Gohman622ed672009-05-04 22:02:23 +00004250 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004251 // Avoid performing the look-up in the common case where the specified
4252 // expression has no loop-variant portions.
4253 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004254 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004255 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004256 // Okay, at least one of these operands is loop variant but might be
4257 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004258 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4259 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004260 NewOps.push_back(OpAtScope);
4261
4262 for (++i; i != e; ++i) {
4263 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004264 NewOps.push_back(OpAtScope);
4265 }
4266 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004267 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004268 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004269 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004270 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004271 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004272 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004273 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004274 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004275 }
4276 }
4277 // If we got here, all operands are loop invariant.
4278 return Comm;
4279 }
4280
Dan Gohman622ed672009-05-04 22:02:23 +00004281 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004282 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4283 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004284 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4285 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004286 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004287 }
4288
4289 // If this is a loop recurrence for a loop that does not contain L, then we
4290 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004291 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004292 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004293 // To evaluate this recurrence, we need to know how many times the AddRec
4294 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004295 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004296 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004297
Eli Friedmanb42a6262008-08-04 23:49:06 +00004298 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004299 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004300 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004301 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004302 }
4303
Dan Gohman622ed672009-05-04 22:02:23 +00004304 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004305 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004306 if (Op == Cast->getOperand())
4307 return Cast; // must be loop invariant
4308 return getZeroExtendExpr(Op, Cast->getType());
4309 }
4310
Dan Gohman622ed672009-05-04 22:02:23 +00004311 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004312 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004313 if (Op == Cast->getOperand())
4314 return Cast; // must be loop invariant
4315 return getSignExtendExpr(Op, Cast->getType());
4316 }
4317
Dan Gohman622ed672009-05-04 22:02:23 +00004318 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004319 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004320 if (Op == Cast->getOperand())
4321 return Cast; // must be loop invariant
4322 return getTruncateExpr(Op, Cast->getType());
4323 }
4324
Torok Edwinc23197a2009-07-14 16:55:14 +00004325 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004326 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004327}
4328
Dan Gohman66a7e852009-05-08 20:38:54 +00004329/// getSCEVAtScope - This is a convenience function which does
4330/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004331const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004332 return getSCEVAtScope(getSCEV(V), L);
4333}
4334
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004335/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4336/// following equation:
4337///
4338/// A * X = B (mod N)
4339///
4340/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4341/// A and B isn't important.
4342///
4343/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004344static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004345 ScalarEvolution &SE) {
4346 uint32_t BW = A.getBitWidth();
4347 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4348 assert(A != 0 && "A must be non-zero.");
4349
4350 // 1. D = gcd(A, N)
4351 //
4352 // The gcd of A and N may have only one prime factor: 2. The number of
4353 // trailing zeros in A is its multiplicity
4354 uint32_t Mult2 = A.countTrailingZeros();
4355 // D = 2^Mult2
4356
4357 // 2. Check if B is divisible by D.
4358 //
4359 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4360 // is not less than multiplicity of this prime factor for D.
4361 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004362 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004363
4364 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4365 // modulo (N / D).
4366 //
4367 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4368 // bit width during computations.
4369 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4370 APInt Mod(BW + 1, 0);
4371 Mod.set(BW - Mult2); // Mod = N / D
4372 APInt I = AD.multiplicativeInverse(Mod);
4373
4374 // 4. Compute the minimum unsigned root of the equation:
4375 // I * (B / D) mod (N / D)
4376 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4377
4378 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4379 // bits.
4380 return SE.getConstant(Result.trunc(BW));
4381}
Chris Lattner53e677a2004-04-02 20:23:17 +00004382
4383/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4384/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4385/// might be the same) or two SCEVCouldNotCompute objects.
4386///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004387static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004388SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004389 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004390 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4391 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4392 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004393
Chris Lattner53e677a2004-04-02 20:23:17 +00004394 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004395 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004396 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004397 return std::make_pair(CNC, CNC);
4398 }
4399
Reid Spencere8019bb2007-03-01 07:25:48 +00004400 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004401 const APInt &L = LC->getValue()->getValue();
4402 const APInt &M = MC->getValue()->getValue();
4403 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004404 APInt Two(BitWidth, 2);
4405 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004406
Dan Gohman64a845e2009-06-24 04:48:43 +00004407 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004408 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004409 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004410 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4411 // The B coefficient is M-N/2
4412 APInt B(M);
4413 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004414
Reid Spencere8019bb2007-03-01 07:25:48 +00004415 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004416 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004417
Reid Spencere8019bb2007-03-01 07:25:48 +00004418 // Compute the B^2-4ac term.
4419 APInt SqrtTerm(B);
4420 SqrtTerm *= B;
4421 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004422
Reid Spencere8019bb2007-03-01 07:25:48 +00004423 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4424 // integer value or else APInt::sqrt() will assert.
4425 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004426
Dan Gohman64a845e2009-06-24 04:48:43 +00004427 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004428 // The divisions must be performed as signed divisions.
4429 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004430 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004431 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004432 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004433 return std::make_pair(CNC, CNC);
4434 }
4435
Owen Andersone922c022009-07-22 00:24:57 +00004436 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004437
4438 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004439 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004440 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004441 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004442
Dan Gohman64a845e2009-06-24 04:48:43 +00004443 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004444 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004445 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004446}
4447
4448/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004449/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004450const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004451 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004452 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004453 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004454 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004455 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004456 }
4457
Dan Gohman35738ac2009-05-04 22:30:44 +00004458 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004459 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004460 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004461
4462 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004463 // If this is an affine expression, the execution count of this branch is
4464 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004465 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004466 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004467 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004468 // equivalent to:
4469 //
4470 // Step*N = -Start (mod 2^BW)
4471 //
4472 // where BW is the common bit width of Start and Step.
4473
Chris Lattner53e677a2004-04-02 20:23:17 +00004474 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004475 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4476 L->getParentLoop());
4477 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4478 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004479
Dan Gohman622ed672009-05-04 22:02:23 +00004480 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004481 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004482
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004483 // First, handle unitary steps.
4484 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004485 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004486 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4487 return Start; // N = Start (as unsigned)
4488
4489 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004490 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004491 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004492 -StartC->getValue()->getValue(),
4493 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004494 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004495 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004496 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4497 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004498 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004499 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004500 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4501 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004502 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004503#if 0
David Greene25e0e872009-12-23 22:18:14 +00004504 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004505 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004506#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004507 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004508 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004509 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004510 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004511 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004512 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004513
Chris Lattner53e677a2004-04-02 20:23:17 +00004514 // We can only use this value if the chrec ends up with an exact zero
4515 // value at this index. When solving for "X*X != 5", for example, we
4516 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004517 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004518 if (Val->isZero())
4519 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004520 }
4521 }
4522 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004523
Dan Gohman1c343752009-06-27 21:21:31 +00004524 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004525}
4526
4527/// HowFarToNonZero - Return the number of times a backedge checking the
4528/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004529/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004530const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004531 // Loops that look like: while (X == 0) are very strange indeed. We don't
4532 // handle them yet except for the trivial case. This could be expanded in the
4533 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004534
Chris Lattner53e677a2004-04-02 20:23:17 +00004535 // If the value is a constant, check to see if it is known to be non-zero
4536 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004537 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004538 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004539 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004540 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004541 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004542
Chris Lattner53e677a2004-04-02 20:23:17 +00004543 // We could implement others, but I really doubt anyone writes loops like
4544 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004545 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004546}
4547
Dan Gohman859b4822009-05-18 15:36:09 +00004548/// getLoopPredecessor - If the given loop's header has exactly one unique
4549/// predecessor outside the loop, return it. Otherwise return null.
4550///
4551BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4552 BasicBlock *Header = L->getHeader();
4553 BasicBlock *Pred = 0;
4554 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4555 PI != E; ++PI)
4556 if (!L->contains(*PI)) {
4557 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4558 Pred = *PI;
4559 }
4560 return Pred;
4561}
4562
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004563/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4564/// (which may not be an immediate predecessor) which has exactly one
4565/// successor from which BB is reachable, or null if no such block is
4566/// found.
4567///
4568BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004569ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004570 // If the block has a unique predecessor, then there is no path from the
4571 // predecessor to the block that does not go through the direct edge
4572 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004573 if (BasicBlock *Pred = BB->getSinglePredecessor())
4574 return Pred;
4575
4576 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004577 // If the header has a unique predecessor outside the loop, it must be
4578 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004579 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004580 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004581
4582 return 0;
4583}
4584
Dan Gohman763bad12009-06-20 00:35:32 +00004585/// HasSameValue - SCEV structural equivalence is usually sufficient for
4586/// testing whether two expressions are equal, however for the purposes of
4587/// looking for a condition guarding a loop, it can be useful to be a little
4588/// more general, since a front-end may have replicated the controlling
4589/// expression.
4590///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004591static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004592 // Quick check to see if they are the same SCEV.
4593 if (A == B) return true;
4594
4595 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4596 // two different instructions with the same value. Check for this case.
4597 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4598 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4599 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4600 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004601 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004602 return true;
4603
4604 // Otherwise assume they may have a different value.
4605 return false;
4606}
4607
Dan Gohman85b05a22009-07-13 21:35:55 +00004608bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4609 return getSignedRange(S).getSignedMax().isNegative();
4610}
4611
4612bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4613 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4614}
4615
4616bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4617 return !getSignedRange(S).getSignedMin().isNegative();
4618}
4619
4620bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4621 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4622}
4623
4624bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4625 return isKnownNegative(S) || isKnownPositive(S);
4626}
4627
4628bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4629 const SCEV *LHS, const SCEV *RHS) {
4630
4631 if (HasSameValue(LHS, RHS))
4632 return ICmpInst::isTrueWhenEqual(Pred);
4633
4634 switch (Pred) {
4635 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004636 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004637 break;
4638 case ICmpInst::ICMP_SGT:
4639 Pred = ICmpInst::ICMP_SLT;
4640 std::swap(LHS, RHS);
4641 case ICmpInst::ICMP_SLT: {
4642 ConstantRange LHSRange = getSignedRange(LHS);
4643 ConstantRange RHSRange = getSignedRange(RHS);
4644 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4645 return true;
4646 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4647 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004648 break;
4649 }
4650 case ICmpInst::ICMP_SGE:
4651 Pred = ICmpInst::ICMP_SLE;
4652 std::swap(LHS, RHS);
4653 case ICmpInst::ICMP_SLE: {
4654 ConstantRange LHSRange = getSignedRange(LHS);
4655 ConstantRange RHSRange = getSignedRange(RHS);
4656 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4657 return true;
4658 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4659 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004660 break;
4661 }
4662 case ICmpInst::ICMP_UGT:
4663 Pred = ICmpInst::ICMP_ULT;
4664 std::swap(LHS, RHS);
4665 case ICmpInst::ICMP_ULT: {
4666 ConstantRange LHSRange = getUnsignedRange(LHS);
4667 ConstantRange RHSRange = getUnsignedRange(RHS);
4668 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4669 return true;
4670 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4671 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004672 break;
4673 }
4674 case ICmpInst::ICMP_UGE:
4675 Pred = ICmpInst::ICMP_ULE;
4676 std::swap(LHS, RHS);
4677 case ICmpInst::ICMP_ULE: {
4678 ConstantRange LHSRange = getUnsignedRange(LHS);
4679 ConstantRange RHSRange = getUnsignedRange(RHS);
4680 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4681 return true;
4682 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4683 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004684 break;
4685 }
4686 case ICmpInst::ICMP_NE: {
4687 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4688 return true;
4689 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4690 return true;
4691
4692 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4693 if (isKnownNonZero(Diff))
4694 return true;
4695 break;
4696 }
4697 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004698 // The check at the top of the function catches the case where
4699 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004700 break;
4701 }
4702 return false;
4703}
4704
4705/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4706/// protected by a conditional between LHS and RHS. This is used to
4707/// to eliminate casts.
4708bool
4709ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4710 ICmpInst::Predicate Pred,
4711 const SCEV *LHS, const SCEV *RHS) {
4712 // Interpret a null as meaning no loop, where there is obviously no guard
4713 // (interprocedural conditions notwithstanding).
4714 if (!L) return true;
4715
4716 BasicBlock *Latch = L->getLoopLatch();
4717 if (!Latch)
4718 return false;
4719
4720 BranchInst *LoopContinuePredicate =
4721 dyn_cast<BranchInst>(Latch->getTerminator());
4722 if (!LoopContinuePredicate ||
4723 LoopContinuePredicate->isUnconditional())
4724 return false;
4725
Dan Gohman0f4b2852009-07-21 23:03:19 +00004726 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4727 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004728}
4729
4730/// isLoopGuardedByCond - Test whether entry to the loop is protected
4731/// by a conditional between LHS and RHS. This is used to help avoid max
4732/// expressions in loop trip counts, and to eliminate casts.
4733bool
4734ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4735 ICmpInst::Predicate Pred,
4736 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004737 // Interpret a null as meaning no loop, where there is obviously no guard
4738 // (interprocedural conditions notwithstanding).
4739 if (!L) return false;
4740
Dan Gohman859b4822009-05-18 15:36:09 +00004741 BasicBlock *Predecessor = getLoopPredecessor(L);
4742 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004743
Dan Gohman859b4822009-05-18 15:36:09 +00004744 // Starting at the loop predecessor, climb up the predecessor chain, as long
4745 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004746 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004747 for (; Predecessor;
4748 PredecessorDest = Predecessor,
4749 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004750
4751 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004752 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004753 if (!LoopEntryPredicate ||
4754 LoopEntryPredicate->isUnconditional())
4755 continue;
4756
Dan Gohman0f4b2852009-07-21 23:03:19 +00004757 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4758 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004759 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004760 }
4761
Dan Gohman38372182008-08-12 20:17:31 +00004762 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004763}
4764
Dan Gohman0f4b2852009-07-21 23:03:19 +00004765/// isImpliedCond - Test whether the condition described by Pred, LHS,
4766/// and RHS is true whenever the given Cond value evaluates to true.
4767bool ScalarEvolution::isImpliedCond(Value *CondValue,
4768 ICmpInst::Predicate Pred,
4769 const SCEV *LHS, const SCEV *RHS,
4770 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004771 // Recursivly handle And and Or conditions.
4772 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4773 if (BO->getOpcode() == Instruction::And) {
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 } else if (BO->getOpcode() == Instruction::Or) {
4778 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004779 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4780 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004781 }
4782 }
4783
4784 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4785 if (!ICI) return false;
4786
Dan Gohman85b05a22009-07-13 21:35:55 +00004787 // Bail if the ICmp's operands' types are wider than the needed type
4788 // before attempting to call getSCEV on them. This avoids infinite
4789 // recursion, since the analysis of widening casts can require loop
4790 // exit condition information for overflow checking, which would
4791 // lead back here.
4792 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004793 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004794 return false;
4795
Dan Gohman0f4b2852009-07-21 23:03:19 +00004796 // Now that we found a conditional branch that dominates the loop, check to
4797 // see if it is the comparison we are looking for.
4798 ICmpInst::Predicate FoundPred;
4799 if (Inverse)
4800 FoundPred = ICI->getInversePredicate();
4801 else
4802 FoundPred = ICI->getPredicate();
4803
4804 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4805 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004806
4807 // Balance the types. The case where FoundLHS' type is wider than
4808 // LHS' type is checked for above.
4809 if (getTypeSizeInBits(LHS->getType()) >
4810 getTypeSizeInBits(FoundLHS->getType())) {
4811 if (CmpInst::isSigned(Pred)) {
4812 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4813 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4814 } else {
4815 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4816 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4817 }
4818 }
4819
Dan Gohman0f4b2852009-07-21 23:03:19 +00004820 // Canonicalize the query to match the way instcombine will have
4821 // canonicalized the comparison.
4822 // First, put a constant operand on the right.
4823 if (isa<SCEVConstant>(LHS)) {
4824 std::swap(LHS, RHS);
4825 Pred = ICmpInst::getSwappedPredicate(Pred);
4826 }
4827 // Then, canonicalize comparisons with boundary cases.
4828 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4829 const APInt &RA = RC->getValue()->getValue();
4830 switch (Pred) {
4831 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4832 case ICmpInst::ICMP_EQ:
4833 case ICmpInst::ICMP_NE:
4834 break;
4835 case ICmpInst::ICMP_UGE:
4836 if ((RA - 1).isMinValue()) {
4837 Pred = ICmpInst::ICMP_NE;
4838 RHS = getConstant(RA - 1);
4839 break;
4840 }
4841 if (RA.isMaxValue()) {
4842 Pred = ICmpInst::ICMP_EQ;
4843 break;
4844 }
4845 if (RA.isMinValue()) return true;
4846 break;
4847 case ICmpInst::ICMP_ULE:
4848 if ((RA + 1).isMaxValue()) {
4849 Pred = ICmpInst::ICMP_NE;
4850 RHS = getConstant(RA + 1);
4851 break;
4852 }
4853 if (RA.isMinValue()) {
4854 Pred = ICmpInst::ICMP_EQ;
4855 break;
4856 }
4857 if (RA.isMaxValue()) return true;
4858 break;
4859 case ICmpInst::ICMP_SGE:
4860 if ((RA - 1).isMinSignedValue()) {
4861 Pred = ICmpInst::ICMP_NE;
4862 RHS = getConstant(RA - 1);
4863 break;
4864 }
4865 if (RA.isMaxSignedValue()) {
4866 Pred = ICmpInst::ICMP_EQ;
4867 break;
4868 }
4869 if (RA.isMinSignedValue()) return true;
4870 break;
4871 case ICmpInst::ICMP_SLE:
4872 if ((RA + 1).isMaxSignedValue()) {
4873 Pred = ICmpInst::ICMP_NE;
4874 RHS = getConstant(RA + 1);
4875 break;
4876 }
4877 if (RA.isMinSignedValue()) {
4878 Pred = ICmpInst::ICMP_EQ;
4879 break;
4880 }
4881 if (RA.isMaxSignedValue()) return true;
4882 break;
4883 case ICmpInst::ICMP_UGT:
4884 if (RA.isMinValue()) {
4885 Pred = ICmpInst::ICMP_NE;
4886 break;
4887 }
4888 if ((RA + 1).isMaxValue()) {
4889 Pred = ICmpInst::ICMP_EQ;
4890 RHS = getConstant(RA + 1);
4891 break;
4892 }
4893 if (RA.isMaxValue()) return false;
4894 break;
4895 case ICmpInst::ICMP_ULT:
4896 if (RA.isMaxValue()) {
4897 Pred = ICmpInst::ICMP_NE;
4898 break;
4899 }
4900 if ((RA - 1).isMinValue()) {
4901 Pred = ICmpInst::ICMP_EQ;
4902 RHS = getConstant(RA - 1);
4903 break;
4904 }
4905 if (RA.isMinValue()) return false;
4906 break;
4907 case ICmpInst::ICMP_SGT:
4908 if (RA.isMinSignedValue()) {
4909 Pred = ICmpInst::ICMP_NE;
4910 break;
4911 }
4912 if ((RA + 1).isMaxSignedValue()) {
4913 Pred = ICmpInst::ICMP_EQ;
4914 RHS = getConstant(RA + 1);
4915 break;
4916 }
4917 if (RA.isMaxSignedValue()) return false;
4918 break;
4919 case ICmpInst::ICMP_SLT:
4920 if (RA.isMaxSignedValue()) {
4921 Pred = ICmpInst::ICMP_NE;
4922 break;
4923 }
4924 if ((RA - 1).isMinSignedValue()) {
4925 Pred = ICmpInst::ICMP_EQ;
4926 RHS = getConstant(RA - 1);
4927 break;
4928 }
4929 if (RA.isMinSignedValue()) return false;
4930 break;
4931 }
4932 }
4933
4934 // Check to see if we can make the LHS or RHS match.
4935 if (LHS == FoundRHS || RHS == FoundLHS) {
4936 if (isa<SCEVConstant>(RHS)) {
4937 std::swap(FoundLHS, FoundRHS);
4938 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4939 } else {
4940 std::swap(LHS, RHS);
4941 Pred = ICmpInst::getSwappedPredicate(Pred);
4942 }
4943 }
4944
4945 // Check whether the found predicate is the same as the desired predicate.
4946 if (FoundPred == Pred)
4947 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4948
4949 // Check whether swapping the found predicate makes it the same as the
4950 // desired predicate.
4951 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4952 if (isa<SCEVConstant>(RHS))
4953 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4954 else
4955 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4956 RHS, LHS, FoundLHS, FoundRHS);
4957 }
4958
4959 // Check whether the actual condition is beyond sufficient.
4960 if (FoundPred == ICmpInst::ICMP_EQ)
4961 if (ICmpInst::isTrueWhenEqual(Pred))
4962 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4963 return true;
4964 if (Pred == ICmpInst::ICMP_NE)
4965 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4966 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4967 return true;
4968
4969 // Otherwise assume the worst.
4970 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004971}
4972
Dan Gohman0f4b2852009-07-21 23:03:19 +00004973/// isImpliedCondOperands - Test whether the condition described by Pred,
4974/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4975/// and FoundRHS is true.
4976bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4977 const SCEV *LHS, const SCEV *RHS,
4978 const SCEV *FoundLHS,
4979 const SCEV *FoundRHS) {
4980 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4981 FoundLHS, FoundRHS) ||
4982 // ~x < ~y --> x > y
4983 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4984 getNotSCEV(FoundRHS),
4985 getNotSCEV(FoundLHS));
4986}
4987
4988/// isImpliedCondOperandsHelper - Test whether the condition described by
4989/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4990/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004991bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004992ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4993 const SCEV *LHS, const SCEV *RHS,
4994 const SCEV *FoundLHS,
4995 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004996 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004997 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4998 case ICmpInst::ICMP_EQ:
4999 case ICmpInst::ICMP_NE:
5000 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5001 return true;
5002 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005003 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005004 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005005 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5006 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5007 return true;
5008 break;
5009 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005010 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005011 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5012 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5013 return true;
5014 break;
5015 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005016 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005017 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5018 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5019 return true;
5020 break;
5021 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005022 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005023 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5024 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5025 return true;
5026 break;
5027 }
5028
5029 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005030}
5031
Dan Gohman51f53b72009-06-21 23:46:38 +00005032/// getBECount - Subtract the end and start values and divide by the step,
5033/// rounding up, to get the number of times the backedge is executed. Return
5034/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005035const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005036 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005037 const SCEV *Step,
5038 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005039 assert(!isKnownNegative(Step) &&
5040 "This code doesn't handle negative strides yet!");
5041
Dan Gohman51f53b72009-06-21 23:46:38 +00005042 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00005043 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
5044 const SCEV *Diff = getMinusSCEV(End, Start);
5045 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005046
5047 // Add an adjustment to the difference between End and Start so that
5048 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005049 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005050
Dan Gohman1f96e672009-09-17 18:05:20 +00005051 if (!NoWrap) {
5052 // Check Add for unsigned overflow.
5053 // TODO: More sophisticated things could be done here.
5054 const Type *WideTy = IntegerType::get(getContext(),
5055 getTypeSizeInBits(Ty) + 1);
5056 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5057 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5058 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5059 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5060 return getCouldNotCompute();
5061 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005062
5063 return getUDivExpr(Add, Step);
5064}
5065
Chris Lattnerdb25de42005-08-15 23:33:51 +00005066/// HowManyLessThans - Return the number of times a backedge containing the
5067/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005068/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005069ScalarEvolution::BackedgeTakenInfo
5070ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5071 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005072 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005073 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005074
Dan Gohman35738ac2009-05-04 22:30:44 +00005075 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005076 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005077 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005078
Dan Gohman1f96e672009-09-17 18:05:20 +00005079 // Check to see if we have a flag which makes analysis easy.
5080 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5081 AddRec->hasNoUnsignedWrap();
5082
Chris Lattnerdb25de42005-08-15 23:33:51 +00005083 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005084 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005085 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005086
Dan Gohman52fddd32010-01-26 04:40:18 +00005087 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005088 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005089 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005090 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005091 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005092 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005093 // value and past the maximum value for its type in a single step.
5094 // Note that it's not sufficient to check NoWrap here, because even
5095 // though the value after a wrap is undefined, it's not undefined
5096 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005097 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005098 // iterate at least until the iteration where the wrapping occurs.
5099 const SCEV *One = getIntegerSCEV(1, Step->getType());
5100 if (isSigned) {
5101 APInt Max = APInt::getSignedMaxValue(BitWidth);
5102 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5103 .slt(getSignedRange(RHS).getSignedMax()))
5104 return getCouldNotCompute();
5105 } else {
5106 APInt Max = APInt::getMaxValue(BitWidth);
5107 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5108 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5109 return getCouldNotCompute();
5110 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005111 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005112 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005113 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005114
Dan Gohmana1af7572009-04-30 20:47:05 +00005115 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5116 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5117 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005118 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005119
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005120 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005121 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005122
Dan Gohmana1af7572009-04-30 20:47:05 +00005123 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005124 const SCEV *MinStart = getConstant(isSigned ?
5125 getSignedRange(Start).getSignedMin() :
5126 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005127
Dan Gohmana1af7572009-04-30 20:47:05 +00005128 // If we know that the condition is true in order to enter the loop,
5129 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005130 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5131 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005132 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005133 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005134 isSigned ? ICmpInst::ICMP_SLT :
5135 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005136 getMinusSCEV(Start, Step), RHS))
5137 End = isSigned ? getSMaxExpr(RHS, Start)
5138 : getUMaxExpr(RHS, Start);
5139
5140 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005141 const SCEV *MaxEnd = getConstant(isSigned ?
5142 getSignedRange(End).getSignedMax() :
5143 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005144
Dan Gohman52fddd32010-01-26 04:40:18 +00005145 // If MaxEnd is within a step of the maximum integer value in its type,
5146 // adjust it down to the minimum value which would produce the same effect.
5147 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5148 // compute the correct value.
5149 const SCEV *StepMinusOne = getMinusSCEV(Step,
5150 getIntegerSCEV(1, Step->getType()));
5151 MaxEnd = isSigned ?
5152 getSMinExpr(MaxEnd,
5153 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5154 StepMinusOne)) :
5155 getUMinExpr(MaxEnd,
5156 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5157 StepMinusOne));
5158
Dan Gohmana1af7572009-04-30 20:47:05 +00005159 // Finally, we subtract these two values and divide, rounding up, to get
5160 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005161 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005162
5163 // The maximum backedge count is similar, except using the minimum start
5164 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005165 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005166
5167 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005168 }
5169
Dan Gohman1c343752009-06-27 21:21:31 +00005170 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005171}
5172
Chris Lattner53e677a2004-04-02 20:23:17 +00005173/// getNumIterationsInRange - Return the number of iterations of this loop that
5174/// produce values in the specified constant range. Another way of looking at
5175/// this is that it returns the first iteration number where the value is not in
5176/// the condition, thus computing the exit count. If the iteration count can't
5177/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005178const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005179 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005180 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005181 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005182
5183 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005184 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005185 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005186 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005187 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005188 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005189 if (const SCEVAddRecExpr *ShiftedAddRec =
5190 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005191 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005192 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005193 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005194 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005195 }
5196
5197 // The only time we can solve this is when we have all constant indices.
5198 // Otherwise, we cannot determine the overflow conditions.
5199 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5200 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005201 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005202
5203
5204 // Okay at this point we know that all elements of the chrec are constants and
5205 // that the start element is zero.
5206
5207 // First check to see if the range contains zero. If not, the first
5208 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005209 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005210 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005211 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005212
Chris Lattner53e677a2004-04-02 20:23:17 +00005213 if (isAffine()) {
5214 // If this is an affine expression then we have this situation:
5215 // Solve {0,+,A} in Range === Ax in Range
5216
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005217 // We know that zero is in the range. If A is positive then we know that
5218 // the upper value of the range must be the first possible exit value.
5219 // If A is negative then the lower of the range is the last possible loop
5220 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005221 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005222 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5223 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005224
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005225 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005226 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005227 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005228
5229 // Evaluate at the exit value. If we really did fall out of the valid
5230 // range, then we computed our trip count, otherwise wrap around or other
5231 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005232 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005233 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005234 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005235
5236 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005237 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005238 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005239 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005240 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005241 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005242 } else if (isQuadratic()) {
5243 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5244 // quadratic equation to solve it. To do this, we must frame our problem in
5245 // terms of figuring out when zero is crossed, instead of when
5246 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005247 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005248 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005249 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005250
5251 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005252 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005253 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005254 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5255 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005256 if (R1) {
5257 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005258 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005259 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005260 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005261 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005262 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005263
Chris Lattner53e677a2004-04-02 20:23:17 +00005264 // Make sure the root is not off by one. The returned iteration should
5265 // not be in the range, but the previous one should be. When solving
5266 // for "X*X < 5", for example, we should not return a root of 2.
5267 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005268 R1->getValue(),
5269 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005270 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005271 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005272 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005273 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005274
Dan Gohman246b2562007-10-22 18:31:58 +00005275 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005276 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005277 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005278 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005279 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005280
Chris Lattner53e677a2004-04-02 20:23:17 +00005281 // If R1 was not in the range, then it is a good return value. Make
5282 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005283 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005284 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005285 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005286 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005287 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005288 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005289 }
5290 }
5291 }
5292
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005293 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005294}
5295
5296
5297
5298//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005299// SCEVCallbackVH Class Implementation
5300//===----------------------------------------------------------------------===//
5301
Dan Gohman1959b752009-05-19 19:22:47 +00005302void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005303 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005304 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5305 SE->ConstantEvolutionLoopExitValue.erase(PN);
5306 SE->Scalars.erase(getValPtr());
5307 // this now dangles!
5308}
5309
Dan Gohman1959b752009-05-19 19:22:47 +00005310void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005311 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005312
5313 // Forget all the expressions associated with users of the old value,
5314 // so that future queries will recompute the expressions using the new
5315 // value.
5316 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005317 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005318 Value *Old = getValPtr();
5319 bool DeleteOld = false;
5320 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5321 UI != UE; ++UI)
5322 Worklist.push_back(*UI);
5323 while (!Worklist.empty()) {
5324 User *U = Worklist.pop_back_val();
5325 // Deleting the Old value will cause this to dangle. Postpone
5326 // that until everything else is done.
5327 if (U == Old) {
5328 DeleteOld = true;
5329 continue;
5330 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005331 if (!Visited.insert(U))
5332 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005333 if (PHINode *PN = dyn_cast<PHINode>(U))
5334 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005335 SE->Scalars.erase(U);
5336 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5337 UI != UE; ++UI)
5338 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005339 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005340 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005341 if (DeleteOld) {
5342 if (PHINode *PN = dyn_cast<PHINode>(Old))
5343 SE->ConstantEvolutionLoopExitValue.erase(PN);
5344 SE->Scalars.erase(Old);
5345 // this now dangles!
5346 }
5347 // this may dangle!
5348}
5349
Dan Gohman1959b752009-05-19 19:22:47 +00005350ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005351 : CallbackVH(V), SE(se) {}
5352
5353//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005354// ScalarEvolution Class Implementation
5355//===----------------------------------------------------------------------===//
5356
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005357ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005358 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005359}
5360
Chris Lattner53e677a2004-04-02 20:23:17 +00005361bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005362 this->F = &F;
5363 LI = &getAnalysis<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005364 DT = &getAnalysis<DominatorTree>();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005365 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005366 return false;
5367}
5368
5369void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005370 Scalars.clear();
5371 BackedgeTakenCounts.clear();
5372 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005373 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005374 UniqueSCEVs.clear();
5375 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005376}
5377
5378void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5379 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005380 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005381 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005382}
5383
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005384bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005385 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005386}
5387
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005388static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005389 const Loop *L) {
5390 // Print all inner loops first
5391 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5392 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005393
Dan Gohman30733292010-01-09 18:17:45 +00005394 OS << "Loop ";
5395 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5396 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005397
Dan Gohman5d984912009-12-18 01:14:11 +00005398 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005399 L->getExitBlocks(ExitBlocks);
5400 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005401 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005402
Dan Gohman46bdfb02009-02-24 18:55:53 +00005403 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5404 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005405 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005406 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005407 }
5408
Dan Gohman30733292010-01-09 18:17:45 +00005409 OS << "\n"
5410 "Loop ";
5411 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5412 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005413
5414 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5415 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5416 } else {
5417 OS << "Unpredictable max backedge-taken count. ";
5418 }
5419
5420 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005421}
5422
Dan Gohman5d984912009-12-18 01:14:11 +00005423void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005424 // ScalarEvolution's implementaiton of the print method is to print
5425 // out SCEV values of all instructions that are interesting. Doing
5426 // this potentially causes it to create new SCEV objects though,
5427 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005428 // observable from outside the class though, so casting away the
5429 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005430 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005431
Dan Gohman30733292010-01-09 18:17:45 +00005432 OS << "Classifying expressions for: ";
5433 WriteAsOperand(OS, F, /*PrintType=*/false);
5434 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005435 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005436 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005437 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005438 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005439 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005440 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005441
Dan Gohman0c689c52009-06-19 17:49:54 +00005442 const Loop *L = LI->getLoopFor((*I).getParent());
5443
Dan Gohman0bba49c2009-07-07 17:06:11 +00005444 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005445 if (AtUse != SV) {
5446 OS << " --> ";
5447 AtUse->print(OS);
5448 }
5449
5450 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005451 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005452 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005453 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005454 OS << "<<Unknown>>";
5455 } else {
5456 OS << *ExitValue;
5457 }
5458 }
5459
Chris Lattner53e677a2004-04-02 20:23:17 +00005460 OS << "\n";
5461 }
5462
Dan Gohman30733292010-01-09 18:17:45 +00005463 OS << "Determining loop execution counts for: ";
5464 WriteAsOperand(OS, F, /*PrintType=*/false);
5465 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005466 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5467 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005468}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005469