blob: fba6e203089ae7ecc87fa77cf6a5768c89171230 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000181 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000182 UniqueSCEVs.InsertNode(S, IP);
183 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman0bba49c2009-07-07 17:06:11 +0000186const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000187 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Dan Gohman0bba49c2009-07-07 17:06:11 +0000190const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000192 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohman6e70e312009-09-27 15:26:03 +0000210bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
212}
213
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000217 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
218 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000229 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
230 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000234void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000241 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
242 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000243 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
Dan Gohmanecb403a2009-05-07 14:00:19 +0000259bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
262 return false;
263 }
264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
270 return false;
271 }
272 return true;
273}
274
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000275bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
277}
278
Dan Gohman6e70e312009-09-27 15:26:03 +0000279bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
281}
282
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000283void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000284 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000285}
286
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294}
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000297 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000298 if (!QueryLoop)
299 return false;
300
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000302 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000303 return false;
304
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
306 // are variant.
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
309 return false;
310
311 // Otherwise it's loop-invariant.
312 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000313}
314
Dan Gohman39125d82010-02-13 00:19:39 +0000315bool
316SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
317 return DT->dominates(L->getHeader(), BB) &&
318 SCEVNAryExpr::dominates(BB, DT);
319}
320
321bool
322SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
323 // This uses a "dominates" query instead of "properly dominates" query because
324 // the instruction which produces the addrec's value is a PHI, and a PHI
325 // effectively properly dominates its entire containing block.
326 return DT->dominates(L->getHeader(), BB) &&
327 SCEVNAryExpr::properlyDominates(BB, DT);
328}
329
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000330void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331 OS << "{" << *Operands[0];
332 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
333 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000334 OS << "}<";
335 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
336 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
Chris Lattner53e677a2004-04-02 20:23:17 +0000338
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000339bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
340 // All non-instruction values are loop invariant. All instructions are loop
341 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000342 // Instructions are never considered invariant in the function body
343 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000344 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000345 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000346 return true;
347}
Chris Lattner53e677a2004-04-02 20:23:17 +0000348
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000349bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
350 if (Instruction *I = dyn_cast<Instruction>(getValue()))
351 return DT->dominates(I->getParent(), BB);
352 return true;
353}
354
Dan Gohman6e70e312009-09-27 15:26:03 +0000355bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
356 if (Instruction *I = dyn_cast<Instruction>(getValue()))
357 return DT->properlyDominates(I->getParent(), BB);
358 return true;
359}
360
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361const Type *SCEVUnknown::getType() const {
362 return V->getType();
363}
Chris Lattner53e677a2004-04-02 20:23:17 +0000364
Dan Gohman0f5efe52010-01-28 02:15:55 +0000365bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
366 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
367 if (VCE->getOpcode() == Instruction::PtrToInt)
368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000369 if (CE->getOpcode() == Instruction::GetElementPtr &&
370 CE->getOperand(0)->isNullValue() &&
371 CE->getNumOperands() == 2)
372 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
373 if (CI->isOne()) {
374 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
375 ->getElementType();
376 return true;
377 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000378
379 return false;
380}
381
382bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
384 if (VCE->getOpcode() == Instruction::PtrToInt)
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000386 if (CE->getOpcode() == Instruction::GetElementPtr &&
387 CE->getOperand(0)->isNullValue()) {
388 const Type *Ty =
389 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
390 if (const StructType *STy = dyn_cast<StructType>(Ty))
391 if (!STy->isPacked() &&
392 CE->getNumOperands() == 3 &&
393 CE->getOperand(1)->isNullValue()) {
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
395 if (CI->isOne() &&
396 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000397 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000398 AllocTy = STy->getElementType(1);
399 return true;
400 }
401 }
402 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000403
404 return false;
405}
406
Dan Gohman4f8eea82010-02-01 18:27:38 +0000407bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getNumOperands() == 3 &&
413 CE->getOperand(0)->isNullValue() &&
414 CE->getOperand(1)->isNullValue()) {
415 const Type *Ty =
416 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
417 // Ignore vector types here so that ScalarEvolutionExpander doesn't
418 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000419 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000420 CTy = Ty;
421 FieldNo = CE->getOperand(2);
422 return true;
423 }
424 }
425
426 return false;
427}
428
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000429void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000430 const Type *AllocTy;
431 if (isSizeOf(AllocTy)) {
432 OS << "sizeof(" << *AllocTy << ")";
433 return;
434 }
435 if (isAlignOf(AllocTy)) {
436 OS << "alignof(" << *AllocTy << ")";
437 return;
438 }
439
Dan Gohman4f8eea82010-02-01 18:27:38 +0000440 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000441 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000442 if (isOffsetOf(CTy, FieldNo)) {
443 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000444 WriteAsOperand(OS, FieldNo, false);
445 OS << ")";
446 return;
447 }
448
449 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000450 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000451}
452
Chris Lattner8d741b82004-06-20 06:23:15 +0000453//===----------------------------------------------------------------------===//
454// SCEV Utilities
455//===----------------------------------------------------------------------===//
456
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000457static bool CompareTypes(const Type *A, const Type *B) {
458 if (A->getTypeID() != B->getTypeID())
459 return A->getTypeID() < B->getTypeID();
460 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
461 const IntegerType *BI = cast<IntegerType>(B);
462 return AI->getBitWidth() < BI->getBitWidth();
463 }
464 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
465 const PointerType *BI = cast<PointerType>(B);
466 return CompareTypes(AI->getElementType(), BI->getElementType());
467 }
468 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
469 const ArrayType *BI = cast<ArrayType>(B);
470 if (AI->getNumElements() != BI->getNumElements())
471 return AI->getNumElements() < BI->getNumElements();
472 return CompareTypes(AI->getElementType(), BI->getElementType());
473 }
474 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
475 const VectorType *BI = cast<VectorType>(B);
476 if (AI->getNumElements() != BI->getNumElements())
477 return AI->getNumElements() < BI->getNumElements();
478 return CompareTypes(AI->getElementType(), BI->getElementType());
479 }
480 if (const StructType *AI = dyn_cast<StructType>(A)) {
481 const StructType *BI = cast<StructType>(B);
482 if (AI->getNumElements() != BI->getNumElements())
483 return AI->getNumElements() < BI->getNumElements();
484 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
485 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
486 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
487 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
488 }
489 return false;
490}
491
Chris Lattner8d741b82004-06-20 06:23:15 +0000492namespace {
493 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
494 /// than the complexity of the RHS. This comparator is used to canonicalize
495 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000496 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000497 LoopInfo *LI;
498 public:
499 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
500
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000501 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000502 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
503 if (LHS == RHS)
504 return false;
505
Dan Gohman72861302009-05-07 14:39:04 +0000506 // Primarily, sort the SCEVs by their getSCEVType().
507 if (LHS->getSCEVType() != RHS->getSCEVType())
508 return LHS->getSCEVType() < RHS->getSCEVType();
509
510 // Aside from the getSCEVType() ordering, the particular ordering
511 // isn't very important except that it's beneficial to be consistent,
512 // so that (a + b) and (b + a) don't end up as different expressions.
513
514 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
515 // not as complete as it could be.
516 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
517 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
518
Dan Gohman5be18e82009-05-19 02:15:55 +0000519 // Order pointer values after integer values. This helps SCEVExpander
520 // form GEPs.
Duncan Sands1df98592010-02-16 11:11:14 +0000521 if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
Dan Gohman5be18e82009-05-19 02:15:55 +0000522 return false;
Duncan Sands1df98592010-02-16 11:11:14 +0000523 if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
Dan Gohman5be18e82009-05-19 02:15:55 +0000524 return true;
525
Dan Gohman72861302009-05-07 14:39:04 +0000526 // Compare getValueID values.
527 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
528 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
529
530 // Sort arguments by their position.
531 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
532 const Argument *RA = cast<Argument>(RU->getValue());
533 return LA->getArgNo() < RA->getArgNo();
534 }
535
536 // For instructions, compare their loop depth, and their opcode.
537 // This is pretty loose.
538 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
539 Instruction *RV = cast<Instruction>(RU->getValue());
540
541 // Compare loop depths.
542 if (LI->getLoopDepth(LV->getParent()) !=
543 LI->getLoopDepth(RV->getParent()))
544 return LI->getLoopDepth(LV->getParent()) <
545 LI->getLoopDepth(RV->getParent());
546
547 // Compare opcodes.
548 if (LV->getOpcode() != RV->getOpcode())
549 return LV->getOpcode() < RV->getOpcode();
550
551 // Compare the number of operands.
552 if (LV->getNumOperands() != RV->getNumOperands())
553 return LV->getNumOperands() < RV->getNumOperands();
554 }
555
556 return false;
557 }
558
Dan Gohman4dfad292009-06-14 22:51:25 +0000559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000562 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
563 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000564 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
565 }
566
567 // Compare addrec loop depths.
568 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
569 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
570 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
571 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
572 }
Dan Gohman72861302009-05-07 14:39:04 +0000573
574 // Lexicographically compare n-ary expressions.
575 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
576 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
577 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
578 if (i >= RC->getNumOperands())
579 return false;
580 if (operator()(LC->getOperand(i), RC->getOperand(i)))
581 return true;
582 if (operator()(RC->getOperand(i), LC->getOperand(i)))
583 return false;
584 }
585 return LC->getNumOperands() < RC->getNumOperands();
586 }
587
Dan Gohmana6b35e22009-05-07 19:23:21 +0000588 // Lexicographically compare udiv expressions.
589 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
590 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
591 if (operator()(LC->getLHS(), RC->getLHS()))
592 return true;
593 if (operator()(RC->getLHS(), LC->getLHS()))
594 return false;
595 if (operator()(LC->getRHS(), RC->getRHS()))
596 return true;
597 if (operator()(RC->getRHS(), LC->getRHS()))
598 return false;
599 return false;
600 }
601
Dan Gohman72861302009-05-07 14:39:04 +0000602 // Compare cast expressions by operand.
603 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
604 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
605 return operator()(LC->getOperand(), RC->getOperand());
606 }
607
Torok Edwinc23197a2009-07-14 16:55:14 +0000608 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000609 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000610 }
611 };
612}
613
614/// GroupByComplexity - Given a list of SCEV objects, order them by their
615/// complexity, and group objects of the same complexity together by value.
616/// When this routine is finished, we know that any duplicates in the vector are
617/// consecutive and that complexity is monotonically increasing.
618///
619/// Note that we go take special precautions to ensure that we get determinstic
620/// results from this routine. In other words, we don't want the results of
621/// this to depend on where the addresses of various SCEV objects happened to
622/// land in memory.
623///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000624static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000625 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000626 if (Ops.size() < 2) return; // Noop
627 if (Ops.size() == 2) {
628 // This is the common case, which also happens to be trivially simple.
629 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000630 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000631 std::swap(Ops[0], Ops[1]);
632 return;
633 }
634
635 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000636 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000637
638 // Now that we are sorted by complexity, group elements of the same
639 // complexity. Note that this is, at worst, N^2, but the vector is likely to
640 // be extremely short in practice. Note that we take this approach because we
641 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000642 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000643 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000644 unsigned Complexity = S->getSCEVType();
645
646 // If there are any objects of the same complexity and same value as this
647 // one, group them.
648 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
649 if (Ops[j] == S) { // Found a duplicate.
650 // Move it to immediately after i'th element.
651 std::swap(Ops[i+1], Ops[j]);
652 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000653 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000654 }
655 }
656 }
657}
658
Chris Lattner53e677a2004-04-02 20:23:17 +0000659
Chris Lattner53e677a2004-04-02 20:23:17 +0000660
661//===----------------------------------------------------------------------===//
662// Simple SCEV method implementations
663//===----------------------------------------------------------------------===//
664
Eli Friedmanb42a6262008-08-04 23:49:06 +0000665/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000666/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000667static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000668 ScalarEvolution &SE,
669 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000670 // Handle the simplest case efficiently.
671 if (K == 1)
672 return SE.getTruncateOrZeroExtend(It, ResultTy);
673
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674 // We are using the following formula for BC(It, K):
675 //
676 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
677 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000678 // Suppose, W is the bitwidth of the return value. We must be prepared for
679 // overflow. Hence, we must assure that the result of our computation is
680 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
681 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000682 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000683 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000684 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000685 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
686 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000687 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000689 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000690 // This formula is trivially equivalent to the previous formula. However,
691 // this formula can be implemented much more efficiently. The trick is that
692 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
693 // arithmetic. To do exact division in modular arithmetic, all we have
694 // to do is multiply by the inverse. Therefore, this step can be done at
695 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000696 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000697 // The next issue is how to safely do the division by 2^T. The way this
698 // is done is by doing the multiplication step at a width of at least W + T
699 // bits. This way, the bottom W+T bits of the product are accurate. Then,
700 // when we perform the division by 2^T (which is equivalent to a right shift
701 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
702 // truncated out after the division by 2^T.
703 //
704 // In comparison to just directly using the first formula, this technique
705 // is much more efficient; using the first formula requires W * K bits,
706 // but this formula less than W + K bits. Also, the first formula requires
707 // a division step, whereas this formula only requires multiplies and shifts.
708 //
709 // It doesn't matter whether the subtraction step is done in the calculation
710 // width or the input iteration count's width; if the subtraction overflows,
711 // the result must be zero anyway. We prefer here to do it in the width of
712 // the induction variable because it helps a lot for certain cases; CodeGen
713 // isn't smart enough to ignore the overflow, which leads to much less
714 // efficient code if the width of the subtraction is wider than the native
715 // register width.
716 //
717 // (It's possible to not widen at all by pulling out factors of 2 before
718 // the multiplication; for example, K=2 can be calculated as
719 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
720 // extra arithmetic, so it's not an obvious win, and it gets
721 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000722
Eli Friedmanb42a6262008-08-04 23:49:06 +0000723 // Protection from insane SCEVs; this bound is conservative,
724 // but it probably doesn't matter.
725 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000726 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000727
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000728 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000729
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730 // Calculate K! / 2^T and T; we divide out the factors of two before
731 // multiplying for calculating K! / 2^T to avoid overflow.
732 // Other overflow doesn't matter because we only care about the bottom
733 // W bits of the result.
734 APInt OddFactorial(W, 1);
735 unsigned T = 1;
736 for (unsigned i = 3; i <= K; ++i) {
737 APInt Mult(W, i);
738 unsigned TwoFactors = Mult.countTrailingZeros();
739 T += TwoFactors;
740 Mult = Mult.lshr(TwoFactors);
741 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000742 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000743
Eli Friedmanb42a6262008-08-04 23:49:06 +0000744 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000745 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000746
747 // Calcuate 2^T, at width T+W.
748 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
749
750 // Calculate the multiplicative inverse of K! / 2^T;
751 // this multiplication factor will perform the exact division by
752 // K! / 2^T.
753 APInt Mod = APInt::getSignedMinValue(W+1);
754 APInt MultiplyFactor = OddFactorial.zext(W+1);
755 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
756 MultiplyFactor = MultiplyFactor.trunc(W);
757
758 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000759 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
760 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000761 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000762 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000763 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000764 Dividend = SE.getMulExpr(Dividend,
765 SE.getTruncateOrZeroExtend(S, CalculationTy));
766 }
767
768 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000769 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000770
771 // Truncate the result, and divide by K! / 2^T.
772
773 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
774 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000775}
776
Chris Lattner53e677a2004-04-02 20:23:17 +0000777/// evaluateAtIteration - Return the value of this chain of recurrences at
778/// the specified iteration number. We can evaluate this recurrence by
779/// multiplying each element in the chain by the binomial coefficient
780/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
781///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000782/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000783///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000784/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000785///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000786const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000787 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000788 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000790 // The computation is correct in the face of overflow provided that the
791 // multiplication is performed _after_ the evaluation of the binomial
792 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000793 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000794 if (isa<SCEVCouldNotCompute>(Coeff))
795 return Coeff;
796
797 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000798 }
799 return Result;
800}
801
Chris Lattner53e677a2004-04-02 20:23:17 +0000802//===----------------------------------------------------------------------===//
803// SCEV Expression folder implementations
804//===----------------------------------------------------------------------===//
805
Dan Gohman0bba49c2009-07-07 17:06:11 +0000806const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000807 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000808 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000809 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000810 assert(isSCEVable(Ty) &&
811 "This is not a conversion to a SCEVable type!");
812 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000813
Dan Gohmanc050fd92009-07-13 20:50:19 +0000814 FoldingSetNodeID ID;
815 ID.AddInteger(scTruncate);
816 ID.AddPointer(Op);
817 ID.AddPointer(Ty);
818 void *IP = 0;
819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
820
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000821 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000822 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000823 return getConstant(
824 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000825
Dan Gohman20900ca2009-04-22 16:20:48 +0000826 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000827 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000828 return getTruncateExpr(ST->getOperand(), Ty);
829
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000830 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000831 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000832 return getTruncateOrSignExtend(SS->getOperand(), Ty);
833
834 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000835 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000836 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
837
Dan Gohman6864db62009-06-18 16:24:47 +0000838 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000839 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000841 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000842 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
843 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000844 }
845
Dan Gohmanc050fd92009-07-13 20:50:19 +0000846 // The cast wasn't folded; create an explicit cast node.
847 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000848 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
849 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000850 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000851 UniqueSCEVs.InsertNode(S, IP);
852 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000853}
854
Dan Gohman0bba49c2009-07-07 17:06:11 +0000855const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000856 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000857 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000858 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000859 assert(isSCEVable(Ty) &&
860 "This is not a conversion to a SCEVable type!");
861 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000862
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000863 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000864 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000865 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000866 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
867 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000868 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000869 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000870
Dan Gohman20900ca2009-04-22 16:20:48 +0000871 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000872 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000873 return getZeroExtendExpr(SZ->getOperand(), Ty);
874
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000875 // Before doing any expensive analysis, check to see if we've already
876 // computed a SCEV for this Op and Ty.
877 FoldingSetNodeID ID;
878 ID.AddInteger(scZeroExtend);
879 ID.AddPointer(Op);
880 ID.AddPointer(Ty);
881 void *IP = 0;
882 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
883
Dan Gohman01ecca22009-04-27 20:16:15 +0000884 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000885 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000886 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000887 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000888 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000889 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000890 const SCEV *Start = AR->getStart();
891 const SCEV *Step = AR->getStepRecurrence(*this);
892 unsigned BitWidth = getTypeSizeInBits(AR->getType());
893 const Loop *L = AR->getLoop();
894
Dan Gohmaneb490a72009-07-25 01:22:26 +0000895 // If we have special knowledge that this addrec won't overflow,
896 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000897 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000898 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
899 getZeroExtendExpr(Step, Ty),
900 L);
901
Dan Gohman01ecca22009-04-27 20:16:15 +0000902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000910 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000912 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000913 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000914
915 // Check whether the backedge-taken count can be losslessly casted to
916 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000917 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000918 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000919 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000920 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
921 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000922 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000923 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000924 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000925 const SCEV *Add = getAddExpr(Start, ZMul);
926 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000927 getAddExpr(getZeroExtendExpr(Start, WideTy),
928 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
929 getZeroExtendExpr(Step, WideTy)));
930 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000931 // Return the expression with the addrec on the outside.
932 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
933 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000934 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000935
936 // Similar to above, only this time treat the step value as signed.
937 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000938 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000939 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000940 OperandExtendedAdd =
941 getAddExpr(getZeroExtendExpr(Start, WideTy),
942 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
943 getSignExtendExpr(Step, WideTy)));
944 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000945 // Return the expression with the addrec on the outside.
946 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
947 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000948 L);
949 }
950
951 // If the backedge is guarded by a comparison with the pre-inc value
952 // the addrec is safe. Also, if the entry is guarded by a comparison
953 // with the start value and the backedge is guarded by a comparison
954 // with the post-inc value, the addrec is safe.
955 if (isKnownPositive(Step)) {
956 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
957 getUnsignedRange(Step).getUnsignedMax());
958 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
959 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
960 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
961 AR->getPostIncExpr(*this), N)))
962 // Return the expression with the addrec on the outside.
963 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
964 getZeroExtendExpr(Step, Ty),
965 L);
966 } else if (isKnownNegative(Step)) {
967 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
968 getSignedRange(Step).getSignedMin());
969 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
970 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
971 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
972 AR->getPostIncExpr(*this), N)))
973 // Return the expression with the addrec on the outside.
974 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
975 getSignExtendExpr(Step, Ty),
976 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000977 }
978 }
979 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000980
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000981 // The cast wasn't folded; create an explicit cast node.
982 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000983 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
984 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000985 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000986 UniqueSCEVs.InsertNode(S, IP);
987 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000988}
989
Dan Gohman0bba49c2009-07-07 17:06:11 +0000990const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000991 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000993 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000994 assert(isSCEVable(Ty) &&
995 "This is not a conversion to a SCEVable type!");
996 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000997
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000998 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001000 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001001 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1002 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001003 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +00001004 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001005
Dan Gohman20900ca2009-04-22 16:20:48 +00001006 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001007 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001008 return getSignExtendExpr(SS->getOperand(), Ty);
1009
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001010 // Before doing any expensive analysis, check to see if we've already
1011 // computed a SCEV for this Op and Ty.
1012 FoldingSetNodeID ID;
1013 ID.AddInteger(scSignExtend);
1014 ID.AddPointer(Op);
1015 ID.AddPointer(Ty);
1016 void *IP = 0;
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1018
Dan Gohman01ecca22009-04-27 20:16:15 +00001019 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001020 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001021 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001022 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001023 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001024 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001025 const SCEV *Start = AR->getStart();
1026 const SCEV *Step = AR->getStepRecurrence(*this);
1027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1028 const Loop *L = AR->getLoop();
1029
Dan Gohmaneb490a72009-07-25 01:22:26 +00001030 // If we have special knowledge that this addrec won't overflow,
1031 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001032 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001033 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1034 getSignExtendExpr(Step, Ty),
1035 L);
1036
Dan Gohman01ecca22009-04-27 20:16:15 +00001037 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1038 // Note that this serves two purposes: It filters out loops that are
1039 // simply not analyzable, and it covers the case where this code is
1040 // being called from within backedge-taken count analysis, such that
1041 // attempting to ask for the backedge-taken count would likely result
1042 // in infinite recursion. In the later case, the analysis code will
1043 // cope with a conservative value, and it will take care to purge
1044 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001045 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001046 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001047 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001048 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001049
1050 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001051 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001052 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001053 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001054 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001055 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1056 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001057 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001058 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001059 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001060 const SCEV *Add = getAddExpr(Start, SMul);
1061 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001062 getAddExpr(getSignExtendExpr(Start, WideTy),
1063 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1064 getSignExtendExpr(Step, WideTy)));
1065 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001066 // Return the expression with the addrec on the outside.
1067 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1068 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001069 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001070
1071 // Similar to above, only this time treat the step value as unsigned.
1072 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001073 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001074 Add = getAddExpr(Start, UMul);
1075 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001076 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001077 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1078 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001079 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getZeroExtendExpr(Step, Ty),
1083 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001084 }
1085
1086 // If the backedge is guarded by a comparison with the pre-inc value
1087 // the addrec is safe. Also, if the entry is guarded by a comparison
1088 // with the start value and the backedge is guarded by a comparison
1089 // with the post-inc value, the addrec is safe.
1090 if (isKnownPositive(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1092 getSignedRange(Step).getSignedMax());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1094 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1096 AR->getPostIncExpr(*this), N)))
1097 // Return the expression with the addrec on the outside.
1098 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1099 getSignExtendExpr(Step, Ty),
1100 L);
1101 } else if (isKnownNegative(Step)) {
1102 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1103 getSignedRange(Step).getSignedMin());
1104 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1105 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1106 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1107 AR->getPostIncExpr(*this), N)))
1108 // Return the expression with the addrec on the outside.
1109 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1110 getSignExtendExpr(Step, Ty),
1111 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001112 }
1113 }
1114 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001115
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001116 // The cast wasn't folded; create an explicit cast node.
1117 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1119 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001120 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001121 UniqueSCEVs.InsertNode(S, IP);
1122 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001123}
1124
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001125/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1126/// unspecified bits out to the given type.
1127///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001128const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001129 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001130 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1131 "This is not an extending conversion!");
1132 assert(isSCEVable(Ty) &&
1133 "This is not a conversion to a SCEVable type!");
1134 Ty = getEffectiveSCEVType(Ty);
1135
1136 // Sign-extend negative constants.
1137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1138 if (SC->getValue()->getValue().isNegative())
1139 return getSignExtendExpr(Op, Ty);
1140
1141 // Peel off a truncate cast.
1142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001143 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001144 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1145 return getAnyExtendExpr(NewOp, Ty);
1146 return getTruncateOrNoop(NewOp, Ty);
1147 }
1148
1149 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001150 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001151 if (!isa<SCEVZeroExtendExpr>(ZExt))
1152 return ZExt;
1153
1154 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001155 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001156 if (!isa<SCEVSignExtendExpr>(SExt))
1157 return SExt;
1158
Dan Gohmana10756e2010-01-21 02:09:26 +00001159 // Force the cast to be folded into the operands of an addrec.
1160 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1161 SmallVector<const SCEV *, 4> Ops;
1162 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1163 I != E; ++I)
1164 Ops.push_back(getAnyExtendExpr(*I, Ty));
1165 return getAddRecExpr(Ops, AR->getLoop());
1166 }
1167
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001168 // If the expression is obviously signed, use the sext cast value.
1169 if (isa<SCEVSMaxExpr>(Op))
1170 return SExt;
1171
1172 // Absent any other information, use the zext cast value.
1173 return ZExt;
1174}
1175
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001176/// CollectAddOperandsWithScales - Process the given Ops list, which is
1177/// a list of operands to be added under the given scale, update the given
1178/// map. This is a helper function for getAddRecExpr. As an example of
1179/// what it does, given a sequence of operands that would form an add
1180/// expression like this:
1181///
1182/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1183///
1184/// where A and B are constants, update the map with these values:
1185///
1186/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1187///
1188/// and add 13 + A*B*29 to AccumulatedConstant.
1189/// This will allow getAddRecExpr to produce this:
1190///
1191/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1192///
1193/// This form often exposes folding opportunities that are hidden in
1194/// the original operand list.
1195///
1196/// Return true iff it appears that any interesting folding opportunities
1197/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1198/// the common case where no interesting opportunities are present, and
1199/// is also used as a check to avoid infinite recursion.
1200///
1201static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001202CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1203 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001204 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001205 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001206 const APInt &Scale,
1207 ScalarEvolution &SE) {
1208 bool Interesting = false;
1209
1210 // Iterate over the add operands.
1211 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1212 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1213 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1214 APInt NewScale =
1215 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1216 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1217 // A multiplication of a constant with another add; recurse.
1218 Interesting |=
1219 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1220 cast<SCEVAddExpr>(Mul->getOperand(1))
1221 ->getOperands(),
1222 NewScale, SE);
1223 } else {
1224 // A multiplication of a constant with some other value. Update
1225 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001226 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1227 const SCEV *Key = SE.getMulExpr(MulOps);
1228 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001229 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001230 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001231 NewOps.push_back(Pair.first->first);
1232 } else {
1233 Pair.first->second += NewScale;
1234 // The map already had an entry for this value, which may indicate
1235 // a folding opportunity.
1236 Interesting = true;
1237 }
1238 }
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // Pull a buried constant out to the outside.
1241 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1242 Interesting = true;
1243 AccumulatedConstant += Scale * C->getValue()->getValue();
1244 } else {
1245 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001246 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001247 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001248 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001249 NewOps.push_back(Pair.first->first);
1250 } else {
1251 Pair.first->second += Scale;
1252 // The map already had an entry for this value, which may indicate
1253 // a folding opportunity.
1254 Interesting = true;
1255 }
1256 }
1257 }
1258
1259 return Interesting;
1260}
1261
1262namespace {
1263 struct APIntCompare {
1264 bool operator()(const APInt &LHS, const APInt &RHS) const {
1265 return LHS.ult(RHS);
1266 }
1267 };
1268}
1269
Dan Gohman6c0866c2009-05-24 23:45:28 +00001270/// getAddExpr - Get a canonical add expression, or something simpler if
1271/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001272const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1273 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001274 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001275 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001276#ifndef NDEBUG
1277 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1278 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1279 getEffectiveSCEVType(Ops[0]->getType()) &&
1280 "SCEVAddExpr operand types don't match!");
1281#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001282
Dan Gohmana10756e2010-01-21 02:09:26 +00001283 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1284 if (!HasNUW && HasNSW) {
1285 bool All = true;
1286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1287 if (!isKnownNonNegative(Ops[i])) {
1288 All = false;
1289 break;
1290 }
1291 if (All) HasNUW = true;
1292 }
1293
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001295 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001296
1297 // If there are any constants, fold them together.
1298 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001301 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001304 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1305 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001306 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001307 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001308 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001309 }
1310
1311 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001312 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001313 Ops.erase(Ops.begin());
1314 --Idx;
1315 }
1316 }
1317
Chris Lattner627018b2004-04-07 16:16:11 +00001318 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001319
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 // Okay, check to see if the same value occurs in the operand list twice. If
1321 // so, merge them together into an multiply expression. Since we sorted the
1322 // list, these values are required to be adjacent.
1323 const Type *Ty = Ops[0]->getType();
1324 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1325 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1326 // Found a match, merge the two values into a multiply, and add any
1327 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001328 const SCEV *Two = getIntegerSCEV(2, Ty);
1329 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 if (Ops.size() == 2)
1331 return Mul;
1332 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1333 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001334 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 }
1336
Dan Gohman728c7f32009-05-08 21:03:19 +00001337 // Check for truncates. If all the operands are truncated from the same
1338 // type, see if factoring out the truncate would permit the result to be
1339 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1340 // if the contents of the resulting outer trunc fold to something simple.
1341 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1342 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1343 const Type *DstType = Trunc->getType();
1344 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001345 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001346 bool Ok = true;
1347 // Check all the operands to see if they can be represented in the
1348 // source type of the truncate.
1349 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1350 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1351 if (T->getOperand()->getType() != SrcType) {
1352 Ok = false;
1353 break;
1354 }
1355 LargeOps.push_back(T->getOperand());
1356 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1357 // This could be either sign or zero extension, but sign extension
1358 // is much more likely to be foldable here.
1359 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1360 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001361 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001362 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1363 if (const SCEVTruncateExpr *T =
1364 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1365 if (T->getOperand()->getType() != SrcType) {
1366 Ok = false;
1367 break;
1368 }
1369 LargeMulOps.push_back(T->getOperand());
1370 } else if (const SCEVConstant *C =
1371 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1372 // This could be either sign or zero extension, but sign extension
1373 // is much more likely to be foldable here.
1374 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1375 } else {
1376 Ok = false;
1377 break;
1378 }
1379 }
1380 if (Ok)
1381 LargeOps.push_back(getMulExpr(LargeMulOps));
1382 } else {
1383 Ok = false;
1384 break;
1385 }
1386 }
1387 if (Ok) {
1388 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001389 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001390 // If it folds to something simple, use it. Otherwise, don't.
1391 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1392 return getTruncateExpr(Fold, DstType);
1393 }
1394 }
1395
1396 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001397 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1398 ++Idx;
1399
1400 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 if (Idx < Ops.size()) {
1402 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001403 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // If we have an add, expand the add operands onto the end of the operands
1405 // list.
1406 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1407 Ops.erase(Ops.begin()+Idx);
1408 DeletedAdd = true;
1409 }
1410
1411 // If we deleted at least one add, we added operands to the end of the list,
1412 // and they are not necessarily sorted. Recurse to resort and resimplify
1413 // any operands we just aquired.
1414 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001415 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001416 }
1417
1418 // Skip over the add expression until we get to a multiply.
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1420 ++Idx;
1421
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001422 // Check to see if there are any folding opportunities present with
1423 // operands multiplied by constant values.
1424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1425 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001426 DenseMap<const SCEV *, APInt> M;
1427 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001428 APInt AccumulatedConstant(BitWidth, 0);
1429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1430 Ops, APInt(BitWidth, 1), *this)) {
1431 // Some interesting folding opportunity is present, so its worthwhile to
1432 // re-generate the operands list. Group the operands by constant scale,
1433 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001434 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1435 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001436 E = NewOps.end(); I != E; ++I)
1437 MulOpLists[M.find(*I)->second].push_back(*I);
1438 // Re-generate the operands list.
1439 Ops.clear();
1440 if (AccumulatedConstant != 0)
1441 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001442 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1443 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001444 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001445 Ops.push_back(getMulExpr(getConstant(I->first),
1446 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001447 if (Ops.empty())
1448 return getIntegerSCEV(0, Ty);
1449 if (Ops.size() == 1)
1450 return Ops[0];
1451 return getAddExpr(Ops);
1452 }
1453 }
1454
Chris Lattner53e677a2004-04-02 20:23:17 +00001455 // If we are adding something to a multiply expression, make sure the
1456 // something is not already an operand of the multiply. If so, merge it into
1457 // the multiply.
1458 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001459 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001461 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001463 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001464 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001465 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 if (Mul->getNumOperands() != 2) {
1467 // If the multiply has more than two operands, we must get the
1468 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001469 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001471 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001472 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001473 const SCEV *One = getIntegerSCEV(1, Ty);
1474 const SCEV *AddOne = getAddExpr(InnerMul, One);
1475 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 if (Ops.size() == 2) return OuterMul;
1477 if (AddOp < Idx) {
1478 Ops.erase(Ops.begin()+AddOp);
1479 Ops.erase(Ops.begin()+Idx-1);
1480 } else {
1481 Ops.erase(Ops.begin()+Idx);
1482 Ops.erase(Ops.begin()+AddOp-1);
1483 }
1484 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001485 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001487
Chris Lattner53e677a2004-04-02 20:23:17 +00001488 // Check this multiply against other multiplies being added together.
1489 for (unsigned OtherMulIdx = Idx+1;
1490 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1491 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001492 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 // If MulOp occurs in OtherMul, we can fold the two multiplies
1494 // together.
1495 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1496 OMulOp != e; ++OMulOp)
1497 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1498 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001499 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001500 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001501 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1502 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001504 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001506 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001507 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001508 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1509 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001511 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001512 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001513 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1514 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 if (Ops.size() == 2) return OuterMul;
1516 Ops.erase(Ops.begin()+Idx);
1517 Ops.erase(Ops.begin()+OtherMulIdx-1);
1518 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001519 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 }
1521 }
1522 }
1523 }
1524
1525 // If there are any add recurrences in the operands list, see if any other
1526 // added values are loop invariant. If so, we can fold them into the
1527 // recurrence.
1528 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1529 ++Idx;
1530
1531 // Scan over all recurrences, trying to fold loop invariants into them.
1532 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1533 // Scan all of the other operands to this add and add them to the vector if
1534 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001535 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001536 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1538 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1539 LIOps.push_back(Ops[i]);
1540 Ops.erase(Ops.begin()+i);
1541 --i; --e;
1542 }
1543
1544 // If we found some loop invariants, fold them into the recurrence.
1545 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001546 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001547 LIOps.push_back(AddRec->getStart());
1548
Dan Gohman0bba49c2009-07-07 17:06:11 +00001549 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001550 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001551 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001552
Dan Gohman355b4f32009-12-19 01:46:34 +00001553 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001554 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001555 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001556
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 // If all of the other operands were loop invariant, we are done.
1558 if (Ops.size() == 1) return NewRec;
1559
1560 // Otherwise, add the folded AddRec by the non-liv parts.
1561 for (unsigned i = 0;; ++i)
1562 if (Ops[i] == AddRec) {
1563 Ops[i] = NewRec;
1564 break;
1565 }
Dan Gohman246b2562007-10-22 18:31:58 +00001566 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 }
1568
1569 // Okay, if there weren't any loop invariants to be folded, check to see if
1570 // there are multiple AddRec's with the same loop induction variable being
1571 // added together. If so, we can fold them.
1572 for (unsigned OtherIdx = Idx+1;
1573 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1574 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001575 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001576 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1577 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001578 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1579 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1581 if (i >= NewOps.size()) {
1582 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1583 OtherAddRec->op_end());
1584 break;
1585 }
Dan Gohman246b2562007-10-22 18:31:58 +00001586 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001588 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001589
1590 if (Ops.size() == 2) return NewAddRec;
1591
1592 Ops.erase(Ops.begin()+Idx);
1593 Ops.erase(Ops.begin()+OtherIdx-1);
1594 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001595 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 }
1597 }
1598
1599 // Otherwise couldn't fold anything into this recurrence. Move onto the
1600 // next one.
1601 }
1602
1603 // Okay, it looks like we really DO need an add expr. Check to see if we
1604 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001605 FoldingSetNodeID ID;
1606 ID.AddInteger(scAddExpr);
1607 ID.AddInteger(Ops.size());
1608 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1609 ID.AddPointer(Ops[i]);
1610 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001611 SCEVAddExpr *S =
1612 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1613 if (!S) {
1614 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1615 new (S) SCEVAddExpr(ID, Ops);
1616 UniqueSCEVs.InsertNode(S, IP);
1617 }
Dan Gohman3645b012009-10-09 00:10:36 +00001618 if (HasNUW) S->setHasNoUnsignedWrap(true);
1619 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001620 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001621}
1622
Dan Gohman6c0866c2009-05-24 23:45:28 +00001623/// getMulExpr - Get a canonical multiply expression, or something simpler if
1624/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001625const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1626 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001628 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001629#ifndef NDEBUG
1630 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1631 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1632 getEffectiveSCEVType(Ops[0]->getType()) &&
1633 "SCEVMulExpr operand types don't match!");
1634#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001635
Dan Gohmana10756e2010-01-21 02:09:26 +00001636 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1637 if (!HasNUW && HasNSW) {
1638 bool All = true;
1639 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1640 if (!isKnownNonNegative(Ops[i])) {
1641 All = false;
1642 break;
1643 }
1644 if (All) HasNUW = true;
1645 }
1646
Chris Lattner53e677a2004-04-02 20:23:17 +00001647 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001648 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001649
1650 // If there are any constants, fold them together.
1651 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001652 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001653
1654 // C1*(C2+V) -> C1*C2 + C1*V
1655 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001656 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001657 if (Add->getNumOperands() == 2 &&
1658 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001659 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1660 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001661
Chris Lattner53e677a2004-04-02 20:23:17 +00001662 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001663 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001664 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001665 ConstantInt *Fold = ConstantInt::get(getContext(),
1666 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001667 RHSC->getValue()->getValue());
1668 Ops[0] = getConstant(Fold);
1669 Ops.erase(Ops.begin()+1); // Erase the folded element
1670 if (Ops.size() == 1) return Ops[0];
1671 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 }
1673
1674 // If we are left with a constant one being multiplied, strip it off.
1675 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1676 Ops.erase(Ops.begin());
1677 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001678 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001679 // If we have a multiply of zero, it will always be zero.
1680 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001681 } else if (Ops[0]->isAllOnesValue()) {
1682 // If we have a mul by -1 of an add, try distributing the -1 among the
1683 // add operands.
1684 if (Ops.size() == 2)
1685 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1686 SmallVector<const SCEV *, 4> NewOps;
1687 bool AnyFolded = false;
1688 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1689 I != E; ++I) {
1690 const SCEV *Mul = getMulExpr(Ops[0], *I);
1691 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1692 NewOps.push_back(Mul);
1693 }
1694 if (AnyFolded)
1695 return getAddExpr(NewOps);
1696 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001697 }
1698 }
1699
1700 // Skip over the add expression until we get to a multiply.
1701 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1702 ++Idx;
1703
1704 if (Ops.size() == 1)
1705 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001706
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 // If there are mul operands inline them all into this expression.
1708 if (Idx < Ops.size()) {
1709 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001710 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001711 // If we have an mul, expand the mul operands onto the end of the operands
1712 // list.
1713 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1714 Ops.erase(Ops.begin()+Idx);
1715 DeletedMul = true;
1716 }
1717
1718 // If we deleted at least one mul, we added operands to the end of the list,
1719 // and they are not necessarily sorted. Recurse to resort and resimplify
1720 // any operands we just aquired.
1721 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001722 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 }
1724
1725 // If there are any add recurrences in the operands list, see if any other
1726 // added values are loop invariant. If so, we can fold them into the
1727 // recurrence.
1728 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1729 ++Idx;
1730
1731 // Scan over all recurrences, trying to fold loop invariants into them.
1732 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1733 // Scan all of the other operands to this mul and add them to the vector if
1734 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001735 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001736 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1738 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1739 LIOps.push_back(Ops[i]);
1740 Ops.erase(Ops.begin()+i);
1741 --i; --e;
1742 }
1743
1744 // If we found some loop invariants, fold them into the recurrence.
1745 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001746 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001747 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 NewOps.reserve(AddRec->getNumOperands());
1749 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001750 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001752 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001753 } else {
1754 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001755 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001756 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001757 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001758 }
1759 }
1760
Dan Gohman355b4f32009-12-19 01:46:34 +00001761 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001762 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001763 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1764 HasNUW && AddRec->hasNoUnsignedWrap(),
1765 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001766
1767 // If all of the other operands were loop invariant, we are done.
1768 if (Ops.size() == 1) return NewRec;
1769
1770 // Otherwise, multiply the folded AddRec by the non-liv parts.
1771 for (unsigned i = 0;; ++i)
1772 if (Ops[i] == AddRec) {
1773 Ops[i] = NewRec;
1774 break;
1775 }
Dan Gohman246b2562007-10-22 18:31:58 +00001776 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 }
1778
1779 // Okay, if there weren't any loop invariants to be folded, check to see if
1780 // there are multiple AddRec's with the same loop induction variable being
1781 // multiplied together. If so, we can fold them.
1782 for (unsigned OtherIdx = Idx+1;
1783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1784 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001785 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1787 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001788 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001789 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001790 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001791 const SCEV *B = F->getStepRecurrence(*this);
1792 const SCEV *D = G->getStepRecurrence(*this);
1793 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001794 getMulExpr(G, B),
1795 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001796 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001797 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001798 if (Ops.size() == 2) return NewAddRec;
1799
1800 Ops.erase(Ops.begin()+Idx);
1801 Ops.erase(Ops.begin()+OtherIdx-1);
1802 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001803 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001804 }
1805 }
1806
1807 // Otherwise couldn't fold anything into this recurrence. Move onto the
1808 // next one.
1809 }
1810
1811 // Okay, it looks like we really DO need an mul expr. Check to see if we
1812 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001813 FoldingSetNodeID ID;
1814 ID.AddInteger(scMulExpr);
1815 ID.AddInteger(Ops.size());
1816 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1817 ID.AddPointer(Ops[i]);
1818 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001819 SCEVMulExpr *S =
1820 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1821 if (!S) {
1822 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1823 new (S) SCEVMulExpr(ID, Ops);
1824 UniqueSCEVs.InsertNode(S, IP);
1825 }
Dan Gohman3645b012009-10-09 00:10:36 +00001826 if (HasNUW) S->setHasNoUnsignedWrap(true);
1827 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001828 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001829}
1830
Andreas Bolka8a11c982009-08-07 22:55:26 +00001831/// getUDivExpr - Get a canonical unsigned division expression, or something
1832/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001833const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1834 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001835 assert(getEffectiveSCEVType(LHS->getType()) ==
1836 getEffectiveSCEVType(RHS->getType()) &&
1837 "SCEVUDivExpr operand types don't match!");
1838
Dan Gohman622ed672009-05-04 22:02:23 +00001839 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001840 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001841 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001842 if (RHSC->isZero())
1843 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001844
Dan Gohman185cf032009-05-08 20:18:49 +00001845 // Determine if the division can be folded into the operands of
1846 // its operands.
1847 // TODO: Generalize this to non-constants by using known-bits information.
1848 const Type *Ty = LHS->getType();
1849 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1850 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1851 // For non-power-of-two values, effectively round the value up to the
1852 // nearest power of two.
1853 if (!RHSC->getValue()->getValue().isPowerOf2())
1854 ++MaxShiftAmt;
1855 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001856 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001857 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1858 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1859 if (const SCEVConstant *Step =
1860 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1861 if (!Step->getValue()->getValue()
1862 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001863 getZeroExtendExpr(AR, ExtTy) ==
1864 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1865 getZeroExtendExpr(Step, ExtTy),
1866 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001867 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001868 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1869 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1870 return getAddRecExpr(Operands, AR->getLoop());
1871 }
1872 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001873 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001874 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001875 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1876 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1877 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001878 // Find an operand that's safely divisible.
1879 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001880 const SCEV *Op = M->getOperand(i);
1881 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001882 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001883 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1884 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001885 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001886 Operands[i] = Div;
1887 return getMulExpr(Operands);
1888 }
1889 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001890 }
Dan Gohman185cf032009-05-08 20:18:49 +00001891 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001892 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001893 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001894 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1895 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1896 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1897 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001898 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001899 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001900 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1901 break;
1902 Operands.push_back(Op);
1903 }
1904 if (Operands.size() == A->getNumOperands())
1905 return getAddExpr(Operands);
1906 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001907 }
Dan Gohman185cf032009-05-08 20:18:49 +00001908
1909 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001910 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001911 Constant *LHSCV = LHSC->getValue();
1912 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001913 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001914 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001915 }
1916 }
1917
Dan Gohman1c343752009-06-27 21:21:31 +00001918 FoldingSetNodeID ID;
1919 ID.AddInteger(scUDivExpr);
1920 ID.AddPointer(LHS);
1921 ID.AddPointer(RHS);
1922 void *IP = 0;
1923 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1924 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001925 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001926 UniqueSCEVs.InsertNode(S, IP);
1927 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001928}
1929
1930
Dan Gohman6c0866c2009-05-24 23:45:28 +00001931/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1932/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001933const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001934 const SCEV *Step, const Loop *L,
1935 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001936 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001937 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001938 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001939 if (StepChrec->getLoop() == L) {
1940 Operands.insert(Operands.end(), StepChrec->op_begin(),
1941 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001942 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001943 }
1944
1945 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001946 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001947}
1948
Dan Gohman6c0866c2009-05-24 23:45:28 +00001949/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1950/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001951const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001952ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001953 const Loop *L,
1954 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001955 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001956#ifndef NDEBUG
1957 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1958 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1959 getEffectiveSCEVType(Operands[0]->getType()) &&
1960 "SCEVAddRecExpr operand types don't match!");
1961#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001962
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001963 if (Operands.back()->isZero()) {
1964 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001965 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001966 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001967
Dan Gohmanbc028532010-02-19 18:49:22 +00001968 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1969 // use that information to infer NUW and NSW flags. However, computing a
1970 // BE count requires calling getAddRecExpr, so we may not yet have a
1971 // meaningful BE count at this point (and if we don't, we'd be stuck
1972 // with a SCEVCouldNotCompute as the cached BE count).
1973
Dan Gohmana10756e2010-01-21 02:09:26 +00001974 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1975 if (!HasNUW && HasNSW) {
1976 bool All = true;
1977 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1978 if (!isKnownNonNegative(Operands[i])) {
1979 All = false;
1980 break;
1981 }
1982 if (All) HasNUW = true;
1983 }
1984
Dan Gohmand9cc7492008-08-08 18:33:12 +00001985 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001986 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001987 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001988 if (L->contains(NestedLoop->getHeader()) ?
1989 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1990 (!NestedLoop->contains(L->getHeader()) &&
1991 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001992 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001993 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001994 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001995 // AddRecs require their operands be loop-invariant with respect to their
1996 // loops. Don't perform this transformation if it would break this
1997 // requirement.
1998 bool AllInvariant = true;
1999 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2000 if (!Operands[i]->isLoopInvariant(L)) {
2001 AllInvariant = false;
2002 break;
2003 }
2004 if (AllInvariant) {
2005 NestedOperands[0] = getAddRecExpr(Operands, L);
2006 AllInvariant = true;
2007 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2008 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2009 AllInvariant = false;
2010 break;
2011 }
2012 if (AllInvariant)
2013 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002014 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002015 }
2016 // Reset Operands to its original state.
2017 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002018 }
2019 }
2020
Dan Gohman67847532010-01-19 22:27:22 +00002021 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2022 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002023 FoldingSetNodeID ID;
2024 ID.AddInteger(scAddRecExpr);
2025 ID.AddInteger(Operands.size());
2026 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2027 ID.AddPointer(Operands[i]);
2028 ID.AddPointer(L);
2029 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002030 SCEVAddRecExpr *S =
2031 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2032 if (!S) {
2033 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2034 new (S) SCEVAddRecExpr(ID, Operands, L);
2035 UniqueSCEVs.InsertNode(S, IP);
2036 }
Dan Gohman3645b012009-10-09 00:10:36 +00002037 if (HasNUW) S->setHasNoUnsignedWrap(true);
2038 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002039 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002040}
2041
Dan Gohman9311ef62009-06-24 14:49:00 +00002042const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2043 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002044 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002045 Ops.push_back(LHS);
2046 Ops.push_back(RHS);
2047 return getSMaxExpr(Ops);
2048}
2049
Dan Gohman0bba49c2009-07-07 17:06:11 +00002050const SCEV *
2051ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002052 assert(!Ops.empty() && "Cannot get empty smax!");
2053 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002054#ifndef NDEBUG
2055 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2056 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2057 getEffectiveSCEVType(Ops[0]->getType()) &&
2058 "SCEVSMaxExpr operand types don't match!");
2059#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002060
2061 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002062 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002063
2064 // If there are any constants, fold them together.
2065 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002066 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002067 ++Idx;
2068 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002069 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002070 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002071 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002072 APIntOps::smax(LHSC->getValue()->getValue(),
2073 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002074 Ops[0] = getConstant(Fold);
2075 Ops.erase(Ops.begin()+1); // Erase the folded element
2076 if (Ops.size() == 1) return Ops[0];
2077 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002078 }
2079
Dan Gohmane5aceed2009-06-24 14:46:22 +00002080 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002081 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2082 Ops.erase(Ops.begin());
2083 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002084 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2085 // If we have an smax with a constant maximum-int, it will always be
2086 // maximum-int.
2087 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002088 }
2089 }
2090
2091 if (Ops.size() == 1) return Ops[0];
2092
2093 // Find the first SMax
2094 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2095 ++Idx;
2096
2097 // Check to see if one of the operands is an SMax. If so, expand its operands
2098 // onto our operand list, and recurse to simplify.
2099 if (Idx < Ops.size()) {
2100 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002101 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002102 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2103 Ops.erase(Ops.begin()+Idx);
2104 DeletedSMax = true;
2105 }
2106
2107 if (DeletedSMax)
2108 return getSMaxExpr(Ops);
2109 }
2110
2111 // Okay, check to see if the same value occurs in the operand list twice. If
2112 // so, delete one. Since we sorted the list, these values are required to
2113 // be adjacent.
2114 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2115 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2116 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2117 --i; --e;
2118 }
2119
2120 if (Ops.size() == 1) return Ops[0];
2121
2122 assert(!Ops.empty() && "Reduced smax down to nothing!");
2123
Nick Lewycky3e630762008-02-20 06:48:22 +00002124 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002125 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002126 FoldingSetNodeID ID;
2127 ID.AddInteger(scSMaxExpr);
2128 ID.AddInteger(Ops.size());
2129 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2130 ID.AddPointer(Ops[i]);
2131 void *IP = 0;
2132 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2133 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002134 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002135 UniqueSCEVs.InsertNode(S, IP);
2136 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002137}
2138
Dan Gohman9311ef62009-06-24 14:49:00 +00002139const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2140 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002141 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002142 Ops.push_back(LHS);
2143 Ops.push_back(RHS);
2144 return getUMaxExpr(Ops);
2145}
2146
Dan Gohman0bba49c2009-07-07 17:06:11 +00002147const SCEV *
2148ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002149 assert(!Ops.empty() && "Cannot get empty umax!");
2150 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002151#ifndef NDEBUG
2152 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2153 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2154 getEffectiveSCEVType(Ops[0]->getType()) &&
2155 "SCEVUMaxExpr operand types don't match!");
2156#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002157
2158 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002159 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002160
2161 // If there are any constants, fold them together.
2162 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002163 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002164 ++Idx;
2165 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002166 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002167 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002168 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002169 APIntOps::umax(LHSC->getValue()->getValue(),
2170 RHSC->getValue()->getValue()));
2171 Ops[0] = getConstant(Fold);
2172 Ops.erase(Ops.begin()+1); // Erase the folded element
2173 if (Ops.size() == 1) return Ops[0];
2174 LHSC = cast<SCEVConstant>(Ops[0]);
2175 }
2176
Dan Gohmane5aceed2009-06-24 14:46:22 +00002177 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002178 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2179 Ops.erase(Ops.begin());
2180 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002181 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2182 // If we have an umax with a constant maximum-int, it will always be
2183 // maximum-int.
2184 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002185 }
2186 }
2187
2188 if (Ops.size() == 1) return Ops[0];
2189
2190 // Find the first UMax
2191 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2192 ++Idx;
2193
2194 // Check to see if one of the operands is a UMax. If so, expand its operands
2195 // onto our operand list, and recurse to simplify.
2196 if (Idx < Ops.size()) {
2197 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002198 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002199 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2200 Ops.erase(Ops.begin()+Idx);
2201 DeletedUMax = true;
2202 }
2203
2204 if (DeletedUMax)
2205 return getUMaxExpr(Ops);
2206 }
2207
2208 // Okay, check to see if the same value occurs in the operand list twice. If
2209 // so, delete one. Since we sorted the list, these values are required to
2210 // be adjacent.
2211 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2212 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2213 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2214 --i; --e;
2215 }
2216
2217 if (Ops.size() == 1) return Ops[0];
2218
2219 assert(!Ops.empty() && "Reduced umax down to nothing!");
2220
2221 // Okay, it looks like we really DO need a umax expr. Check to see if we
2222 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002223 FoldingSetNodeID ID;
2224 ID.AddInteger(scUMaxExpr);
2225 ID.AddInteger(Ops.size());
2226 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2227 ID.AddPointer(Ops[i]);
2228 void *IP = 0;
2229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2230 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002231 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002232 UniqueSCEVs.InsertNode(S, IP);
2233 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002234}
2235
Dan Gohman9311ef62009-06-24 14:49:00 +00002236const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2237 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002238 // ~smax(~x, ~y) == smin(x, y).
2239 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2240}
2241
Dan Gohman9311ef62009-06-24 14:49:00 +00002242const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2243 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002244 // ~umax(~x, ~y) == umin(x, y)
2245 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2246}
2247
Dan Gohman4f8eea82010-02-01 18:27:38 +00002248const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2249 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2250 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2251 C = ConstantFoldConstantExpression(CE, TD);
2252 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2253 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2254}
2255
2256const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2257 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2258 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2259 C = ConstantFoldConstantExpression(CE, TD);
2260 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2261 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2262}
2263
2264const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2265 unsigned FieldNo) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002266 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2268 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002269 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002270 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002271}
2272
Dan Gohman4f8eea82010-02-01 18:27:38 +00002273const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2274 Constant *FieldNo) {
2275 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002276 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2277 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohman4f8eea82010-02-01 18:27:38 +00002278 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002279 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002280}
2281
Dan Gohman0bba49c2009-07-07 17:06:11 +00002282const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002283 // Don't attempt to do anything other than create a SCEVUnknown object
2284 // here. createSCEV only calls getUnknown after checking for all other
2285 // interesting possibilities, and any other code that calls getUnknown
2286 // is doing so in order to hide a value from SCEV canonicalization.
2287
Dan Gohman1c343752009-06-27 21:21:31 +00002288 FoldingSetNodeID ID;
2289 ID.AddInteger(scUnknown);
2290 ID.AddPointer(V);
2291 void *IP = 0;
2292 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2293 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002294 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002295 UniqueSCEVs.InsertNode(S, IP);
2296 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002297}
2298
Chris Lattner53e677a2004-04-02 20:23:17 +00002299//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002300// Basic SCEV Analysis and PHI Idiom Recognition Code
2301//
2302
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002303/// isSCEVable - Test if values of the given type are analyzable within
2304/// the SCEV framework. This primarily includes integer types, and it
2305/// can optionally include pointer types if the ScalarEvolution class
2306/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002307bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002308 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002309 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002310}
2311
2312/// getTypeSizeInBits - Return the size in bits of the specified type,
2313/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002314uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002315 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2316
2317 // If we have a TargetData, use it!
2318 if (TD)
2319 return TD->getTypeSizeInBits(Ty);
2320
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002321 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002322 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002323 return Ty->getPrimitiveSizeInBits();
2324
2325 // The only other support type is pointer. Without TargetData, conservatively
2326 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002327 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002328 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002329}
2330
2331/// getEffectiveSCEVType - Return a type with the same bitwidth as
2332/// the given type and which represents how SCEV will treat the given
2333/// type, for which isSCEVable must return true. For pointer types,
2334/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002335const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002336 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2337
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002338 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002339 return Ty;
2340
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002341 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002342 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002343 if (TD) return TD->getIntPtrType(getContext());
2344
2345 // Without TargetData, conservatively assume pointers are 64-bit.
2346 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002347}
Chris Lattner53e677a2004-04-02 20:23:17 +00002348
Dan Gohman0bba49c2009-07-07 17:06:11 +00002349const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002350 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002351}
2352
Chris Lattner53e677a2004-04-02 20:23:17 +00002353/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2354/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002355const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002356 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002357
Dan Gohman0bba49c2009-07-07 17:06:11 +00002358 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002359 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002360 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002361 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002362 return S;
2363}
2364
Dan Gohman6bbcba12009-06-24 00:54:57 +00002365/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002366/// specified signed integer value and return a SCEV for the constant.
Dan Gohman32efba62010-02-04 02:43:51 +00002367const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002368 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002369 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002370}
2371
2372/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2373///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002374const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002375 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002376 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002378
2379 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002380 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002381 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002382 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002383}
2384
2385/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002386const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002387 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002388 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002389 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002390
2391 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002392 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002393 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002394 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002395 return getMinusSCEV(AllOnes, V);
2396}
2397
2398/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2399///
Dan Gohman9311ef62009-06-24 14:49:00 +00002400const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2401 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002402 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002403 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002404}
2405
2406/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2407/// input value to the specified type. If the type must be extended, it is zero
2408/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002409const SCEV *
2410ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002411 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002412 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002413 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2414 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002415 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002416 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002417 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002418 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002419 return getTruncateExpr(V, Ty);
2420 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002421}
2422
2423/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2424/// input value to the specified type. If the type must be extended, it is sign
2425/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002426const SCEV *
2427ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002428 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002429 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002430 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2431 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002432 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002433 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002434 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002435 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002436 return getTruncateExpr(V, Ty);
2437 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002438}
2439
Dan Gohman467c4302009-05-13 03:46:30 +00002440/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2441/// input value to the specified type. If the type must be extended, it is zero
2442/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002443const SCEV *
2444ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002445 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002446 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2447 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002448 "Cannot noop or zero extend with non-integer arguments!");
2449 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2450 "getNoopOrZeroExtend cannot truncate!");
2451 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2452 return V; // No conversion
2453 return getZeroExtendExpr(V, Ty);
2454}
2455
2456/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2457/// input value to the specified type. If the type must be extended, it is sign
2458/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002459const SCEV *
2460ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002461 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002462 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2463 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002464 "Cannot noop or sign extend with non-integer arguments!");
2465 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2466 "getNoopOrSignExtend cannot truncate!");
2467 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2468 return V; // No conversion
2469 return getSignExtendExpr(V, Ty);
2470}
2471
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002472/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2473/// the input value to the specified type. If the type must be extended,
2474/// it is extended with unspecified bits. The conversion must not be
2475/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002476const SCEV *
2477ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002478 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002479 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2480 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002481 "Cannot noop or any extend with non-integer arguments!");
2482 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2483 "getNoopOrAnyExtend cannot truncate!");
2484 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2485 return V; // No conversion
2486 return getAnyExtendExpr(V, Ty);
2487}
2488
Dan Gohman467c4302009-05-13 03:46:30 +00002489/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2490/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002491const SCEV *
2492ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002493 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002494 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2495 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002496 "Cannot truncate or noop with non-integer arguments!");
2497 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2498 "getTruncateOrNoop cannot extend!");
2499 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2500 return V; // No conversion
2501 return getTruncateExpr(V, Ty);
2502}
2503
Dan Gohmana334aa72009-06-22 00:31:57 +00002504/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2505/// the types using zero-extension, and then perform a umax operation
2506/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002507const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2508 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002509 const SCEV *PromotedLHS = LHS;
2510 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002511
2512 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2513 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2514 else
2515 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2516
2517 return getUMaxExpr(PromotedLHS, PromotedRHS);
2518}
2519
Dan Gohmanc9759e82009-06-22 15:03:27 +00002520/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2521/// the types using zero-extension, and then perform a umin operation
2522/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002523const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2524 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002525 const SCEV *PromotedLHS = LHS;
2526 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002527
2528 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2529 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2530 else
2531 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2532
2533 return getUMinExpr(PromotedLHS, PromotedRHS);
2534}
2535
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002536/// PushDefUseChildren - Push users of the given Instruction
2537/// onto the given Worklist.
2538static void
2539PushDefUseChildren(Instruction *I,
2540 SmallVectorImpl<Instruction *> &Worklist) {
2541 // Push the def-use children onto the Worklist stack.
2542 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2543 UI != UE; ++UI)
2544 Worklist.push_back(cast<Instruction>(UI));
2545}
2546
2547/// ForgetSymbolicValue - This looks up computed SCEV values for all
2548/// instructions that depend on the given instruction and removes them from
2549/// the Scalars map if they reference SymName. This is used during PHI
2550/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002551void
Dan Gohman85669632010-02-25 06:57:05 +00002552ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002553 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002554 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002555
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002556 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002557 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002558 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002559 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002560 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002561
Dan Gohman5d984912009-12-18 01:14:11 +00002562 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002563 Scalars.find(static_cast<Value *>(I));
2564 if (It != Scalars.end()) {
2565 // Short-circuit the def-use traversal if the symbolic name
2566 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002567 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002568 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002569
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002570 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002571 // structure, it's a PHI that's in the progress of being computed
2572 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2573 // additional loop trip count information isn't going to change anything.
2574 // In the second case, createNodeForPHI will perform the necessary
2575 // updates on its own when it gets to that point. In the third, we do
2576 // want to forget the SCEVUnknown.
2577 if (!isa<PHINode>(I) ||
2578 !isa<SCEVUnknown>(It->second) ||
2579 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002580 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002581 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002582 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002583 }
2584
2585 PushDefUseChildren(I, Worklist);
2586 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002587}
Chris Lattner53e677a2004-04-02 20:23:17 +00002588
2589/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2590/// a loop header, making it a potential recurrence, or it doesn't.
2591///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002592const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002593 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002594 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002595 if (L->getHeader() == PN->getParent()) {
2596 // If it lives in the loop header, it has two incoming values, one
2597 // from outside the loop, and one from inside.
2598 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2599 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002600
Chris Lattner53e677a2004-04-02 20:23:17 +00002601 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002602 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002603 assert(Scalars.find(PN) == Scalars.end() &&
2604 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002605 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002606
2607 // Using this symbolic name for the PHI, analyze the value coming around
2608 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002609 Value *BEValueV = PN->getIncomingValue(BackEdge);
2610 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002611
2612 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2613 // has a special value for the first iteration of the loop.
2614
2615 // If the value coming around the backedge is an add with the symbolic
2616 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002617 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002618 // If there is a single occurrence of the symbolic value, replace it
2619 // with a recurrence.
2620 unsigned FoundIndex = Add->getNumOperands();
2621 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2622 if (Add->getOperand(i) == SymbolicName)
2623 if (FoundIndex == e) {
2624 FoundIndex = i;
2625 break;
2626 }
2627
2628 if (FoundIndex != Add->getNumOperands()) {
2629 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002630 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002631 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2632 if (i != FoundIndex)
2633 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002634 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002635
2636 // This is not a valid addrec if the step amount is varying each
2637 // loop iteration, but is not itself an addrec in this loop.
2638 if (Accum->isLoopInvariant(L) ||
2639 (isa<SCEVAddRecExpr>(Accum) &&
2640 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002641 bool HasNUW = false;
2642 bool HasNSW = false;
2643
2644 // If the increment doesn't overflow, then neither the addrec nor
2645 // the post-increment will overflow.
2646 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2647 if (OBO->hasNoUnsignedWrap())
2648 HasNUW = true;
2649 if (OBO->hasNoSignedWrap())
2650 HasNSW = true;
2651 }
2652
Dan Gohman64a845e2009-06-24 04:48:43 +00002653 const SCEV *StartVal =
2654 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002655 const SCEV *PHISCEV =
2656 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002657
Dan Gohmana10756e2010-01-21 02:09:26 +00002658 // Since the no-wrap flags are on the increment, they apply to the
2659 // post-incremented value as well.
2660 if (Accum->isLoopInvariant(L))
2661 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2662 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002663
2664 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002665 // to be symbolic. We now need to go back and purge all of the
2666 // entries for the scalars that use the symbolic expression.
2667 ForgetSymbolicName(PN, SymbolicName);
2668 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002669 return PHISCEV;
2670 }
2671 }
Dan Gohman622ed672009-05-04 22:02:23 +00002672 } else if (const SCEVAddRecExpr *AddRec =
2673 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002674 // Otherwise, this could be a loop like this:
2675 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2676 // In this case, j = {1,+,1} and BEValue is j.
2677 // Because the other in-value of i (0) fits the evolution of BEValue
2678 // i really is an addrec evolution.
2679 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002680 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002681
2682 // If StartVal = j.start - j.stride, we can use StartVal as the
2683 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002684 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002685 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002686 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002687 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002688
2689 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002690 // to be symbolic. We now need to go back and purge all of the
2691 // entries for the scalars that use the symbolic expression.
2692 ForgetSymbolicName(PN, SymbolicName);
2693 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002694 return PHISCEV;
2695 }
2696 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002697 }
2698
2699 return SymbolicName;
2700 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002701
Dan Gohman85669632010-02-25 06:57:05 +00002702 // If the PHI has a single incoming value, follow that value, unless the
2703 // PHI's incoming blocks are in a different loop, in which case doing so
2704 // risks breaking LCSSA form. Instcombine would normally zap these, but
2705 // it doesn't have DominatorTree information, so it may miss cases.
2706 if (Value *V = PN->hasConstantValue(DT)) {
2707 bool AllSameLoop = true;
2708 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2709 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2710 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2711 AllSameLoop = false;
2712 break;
2713 }
2714 if (AllSameLoop)
2715 return getSCEV(V);
2716 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002717
Chris Lattner53e677a2004-04-02 20:23:17 +00002718 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002719 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002720}
2721
Dan Gohman26466c02009-05-08 20:26:55 +00002722/// createNodeForGEP - Expand GEP instructions into add and multiply
2723/// operations. This allows them to be analyzed by regular SCEV code.
2724///
Dan Gohmand281ed22009-12-18 02:09:29 +00002725const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002726
Dan Gohmand281ed22009-12-18 02:09:29 +00002727 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002728 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002729 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002730 // Don't attempt to analyze GEPs over unsized objects.
2731 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2732 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002733 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002734 gep_type_iterator GTI = gep_type_begin(GEP);
2735 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2736 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002737 I != E; ++I) {
2738 Value *Index = *I;
2739 // Compute the (potentially symbolic) offset in bytes for this index.
2740 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2741 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002742 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002743 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002744 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002745 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002746 } else {
2747 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002748 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman8db08df2010-02-02 01:38:49 +00002749 // Getelementptr indicies are signed.
2750 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002751 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002752 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002753 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2754 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2755 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002756 }
2757 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002758 return getAddExpr(getSCEV(Base), TotalOffset,
2759 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002760}
2761
Nick Lewycky83bb0052007-11-22 07:59:40 +00002762/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2763/// guaranteed to end in (at every loop iteration). It is, at the same time,
2764/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2765/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002766uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002767ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002768 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002769 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002770
Dan Gohman622ed672009-05-04 22:02:23 +00002771 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002772 return std::min(GetMinTrailingZeros(T->getOperand()),
2773 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002774
Dan Gohman622ed672009-05-04 22:02:23 +00002775 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002776 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2777 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2778 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002779 }
2780
Dan Gohman622ed672009-05-04 22:02:23 +00002781 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002782 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2783 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2784 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002785 }
2786
Dan Gohman622ed672009-05-04 22:02:23 +00002787 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002788 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002789 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002790 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002791 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002792 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002793 }
2794
Dan Gohman622ed672009-05-04 22:02:23 +00002795 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002796 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002797 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2798 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002799 for (unsigned i = 1, e = M->getNumOperands();
2800 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002801 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002802 BitWidth);
2803 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002804 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002805
Dan Gohman622ed672009-05-04 22:02:23 +00002806 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002807 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002808 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002809 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002810 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002811 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002812 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002813
Dan Gohman622ed672009-05-04 22:02:23 +00002814 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002815 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002816 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002817 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002818 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002819 return MinOpRes;
2820 }
2821
Dan Gohman622ed672009-05-04 22:02:23 +00002822 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002823 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002824 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002825 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002826 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002827 return MinOpRes;
2828 }
2829
Dan Gohman2c364ad2009-06-19 23:29:04 +00002830 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2831 // For a SCEVUnknown, ask ValueTracking.
2832 unsigned BitWidth = getTypeSizeInBits(U->getType());
2833 APInt Mask = APInt::getAllOnesValue(BitWidth);
2834 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2835 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2836 return Zeros.countTrailingOnes();
2837 }
2838
2839 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002840 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002841}
Chris Lattner53e677a2004-04-02 20:23:17 +00002842
Dan Gohman85b05a22009-07-13 21:35:55 +00002843/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2844///
2845ConstantRange
2846ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002847
2848 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002849 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002850
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002851 unsigned BitWidth = getTypeSizeInBits(S->getType());
2852 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2853
2854 // If the value has known zeros, the maximum unsigned value will have those
2855 // known zeros as well.
2856 uint32_t TZ = GetMinTrailingZeros(S);
2857 if (TZ != 0)
2858 ConservativeResult =
2859 ConstantRange(APInt::getMinValue(BitWidth),
2860 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2861
Dan Gohman85b05a22009-07-13 21:35:55 +00002862 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2863 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2864 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2865 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002866 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002867 }
2868
2869 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2870 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2871 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2872 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002873 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002874 }
2875
2876 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2877 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2878 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2879 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002880 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002881 }
2882
2883 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2884 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2885 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2886 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002887 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002888 }
2889
2890 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2891 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2892 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002893 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002894 }
2895
2896 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2897 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002898 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002899 }
2900
2901 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2902 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002903 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002904 }
2905
2906 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2907 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002908 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002909 }
2910
Dan Gohman85b05a22009-07-13 21:35:55 +00002911 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002912 // If there's no unsigned wrap, the value will never be less than its
2913 // initial value.
2914 if (AddRec->hasNoUnsignedWrap())
2915 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2916 ConservativeResult =
2917 ConstantRange(C->getValue()->getValue(),
2918 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002919
2920 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002921 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002922 const Type *Ty = AddRec->getType();
2923 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002924 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2925 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002926 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2927
2928 const SCEV *Start = AddRec->getStart();
2929 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2930
2931 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002932 if (!AddRec->hasNoUnsignedWrap())
2933 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002934
2935 ConstantRange StartRange = getUnsignedRange(Start);
2936 ConstantRange EndRange = getUnsignedRange(End);
2937 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2938 EndRange.getUnsignedMin());
2939 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2940 EndRange.getUnsignedMax());
2941 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002942 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002943 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002944 }
2945 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002946
2947 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002948 }
2949
2950 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2951 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002952 APInt Mask = APInt::getAllOnesValue(BitWidth);
2953 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2954 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002955 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002956 return ConservativeResult;
2957 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002958 }
2959
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002960 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002961}
2962
Dan Gohman85b05a22009-07-13 21:35:55 +00002963/// getSignedRange - Determine the signed range for a particular SCEV.
2964///
2965ConstantRange
2966ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002967
Dan Gohman85b05a22009-07-13 21:35:55 +00002968 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2969 return ConstantRange(C->getValue()->getValue());
2970
Dan Gohman52fddd32010-01-26 04:40:18 +00002971 unsigned BitWidth = getTypeSizeInBits(S->getType());
2972 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2973
2974 // If the value has known zeros, the maximum signed value will have those
2975 // known zeros as well.
2976 uint32_t TZ = GetMinTrailingZeros(S);
2977 if (TZ != 0)
2978 ConservativeResult =
2979 ConstantRange(APInt::getSignedMinValue(BitWidth),
2980 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2981
Dan Gohman85b05a22009-07-13 21:35:55 +00002982 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2983 ConstantRange X = getSignedRange(Add->getOperand(0));
2984 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2985 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002986 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002987 }
2988
Dan Gohman85b05a22009-07-13 21:35:55 +00002989 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2990 ConstantRange X = getSignedRange(Mul->getOperand(0));
2991 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2992 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002993 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002994 }
2995
Dan Gohman85b05a22009-07-13 21:35:55 +00002996 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2997 ConstantRange X = getSignedRange(SMax->getOperand(0));
2998 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2999 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003000 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003001 }
Dan Gohman62849c02009-06-24 01:05:09 +00003002
Dan Gohman85b05a22009-07-13 21:35:55 +00003003 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3004 ConstantRange X = getSignedRange(UMax->getOperand(0));
3005 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3006 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003007 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003008 }
Dan Gohman62849c02009-06-24 01:05:09 +00003009
Dan Gohman85b05a22009-07-13 21:35:55 +00003010 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3011 ConstantRange X = getSignedRange(UDiv->getLHS());
3012 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003013 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003014 }
Dan Gohman62849c02009-06-24 01:05:09 +00003015
Dan Gohman85b05a22009-07-13 21:35:55 +00003016 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3017 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003018 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003019 }
3020
3021 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3022 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003023 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003024 }
3025
3026 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3027 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003028 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003029 }
3030
Dan Gohman85b05a22009-07-13 21:35:55 +00003031 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003032 // If there's no signed wrap, and all the operands have the same sign or
3033 // zero, the value won't ever change sign.
3034 if (AddRec->hasNoSignedWrap()) {
3035 bool AllNonNeg = true;
3036 bool AllNonPos = true;
3037 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3038 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3039 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3040 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003041 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003042 ConservativeResult = ConservativeResult.intersectWith(
3043 ConstantRange(APInt(BitWidth, 0),
3044 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003045 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003046 ConservativeResult = ConservativeResult.intersectWith(
3047 ConstantRange(APInt::getSignedMinValue(BitWidth),
3048 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003049 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003050
3051 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003052 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003053 const Type *Ty = AddRec->getType();
3054 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003055 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3056 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003057 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3058
3059 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003060 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3061
3062 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003063 if (!AddRec->hasNoSignedWrap())
3064 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003065
3066 ConstantRange StartRange = getSignedRange(Start);
3067 ConstantRange EndRange = getSignedRange(End);
3068 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3069 EndRange.getSignedMin());
3070 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3071 EndRange.getSignedMax());
3072 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003073 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003074 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003075 }
Dan Gohman62849c02009-06-24 01:05:09 +00003076 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003077
3078 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003079 }
3080
Dan Gohman2c364ad2009-06-19 23:29:04 +00003081 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3082 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003083 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003084 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003085 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3086 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003087 return ConservativeResult;
3088 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003089 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003090 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003091 }
3092
Dan Gohman52fddd32010-01-26 04:40:18 +00003093 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003094}
3095
Chris Lattner53e677a2004-04-02 20:23:17 +00003096/// createSCEV - We know that there is no SCEV for the specified value.
3097/// Analyze the expression.
3098///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003099const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003100 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003101 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003102
Dan Gohman6c459a22008-06-22 19:56:46 +00003103 unsigned Opcode = Instruction::UserOp1;
3104 if (Instruction *I = dyn_cast<Instruction>(V))
3105 Opcode = I->getOpcode();
3106 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3107 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003108 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3109 return getConstant(CI);
3110 else if (isa<ConstantPointerNull>(V))
3111 return getIntegerSCEV(0, V->getType());
3112 else if (isa<UndefValue>(V))
3113 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003114 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3115 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003116 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003117 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003118
Dan Gohmanca178902009-07-17 20:47:02 +00003119 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003120 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003121 case Instruction::Add:
3122 // Don't transfer the NSW and NUW bits from the Add instruction to the
3123 // Add expression, because the Instruction may be guarded by control
3124 // flow and the no-overflow bits may not be valid for the expression in
3125 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003126 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003127 getSCEV(U->getOperand(1)));
3128 case Instruction::Mul:
3129 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3130 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003131 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003132 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003133 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003134 return getUDivExpr(getSCEV(U->getOperand(0)),
3135 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003136 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003137 return getMinusSCEV(getSCEV(U->getOperand(0)),
3138 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003139 case Instruction::And:
3140 // For an expression like x&255 that merely masks off the high bits,
3141 // use zext(trunc(x)) as the SCEV expression.
3142 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003143 if (CI->isNullValue())
3144 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003145 if (CI->isAllOnesValue())
3146 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003147 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003148
3149 // Instcombine's ShrinkDemandedConstant may strip bits out of
3150 // constants, obscuring what would otherwise be a low-bits mask.
3151 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3152 // knew about to reconstruct a low-bits mask value.
3153 unsigned LZ = A.countLeadingZeros();
3154 unsigned BitWidth = A.getBitWidth();
3155 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3156 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3157 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3158
3159 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3160
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003161 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003162 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003163 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003164 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003165 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003166 }
3167 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003168
Dan Gohman6c459a22008-06-22 19:56:46 +00003169 case Instruction::Or:
3170 // If the RHS of the Or is a constant, we may have something like:
3171 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3172 // optimizations will transparently handle this case.
3173 //
3174 // In order for this transformation to be safe, the LHS must be of the
3175 // form X*(2^n) and the Or constant must be less than 2^n.
3176 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003177 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003178 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003179 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003180 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3181 // Build a plain add SCEV.
3182 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3183 // If the LHS of the add was an addrec and it has no-wrap flags,
3184 // transfer the no-wrap flags, since an or won't introduce a wrap.
3185 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3186 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3187 if (OldAR->hasNoUnsignedWrap())
3188 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3189 if (OldAR->hasNoSignedWrap())
3190 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3191 }
3192 return S;
3193 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003194 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003195 break;
3196 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003197 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003198 // If the RHS of the xor is a signbit, then this is just an add.
3199 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003200 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003201 return getAddExpr(getSCEV(U->getOperand(0)),
3202 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003203
3204 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003205 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003206 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003207
3208 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3209 // This is a variant of the check for xor with -1, and it handles
3210 // the case where instcombine has trimmed non-demanded bits out
3211 // of an xor with -1.
3212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3213 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3214 if (BO->getOpcode() == Instruction::And &&
3215 LCI->getValue() == CI->getValue())
3216 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003217 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003218 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003219 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003220 const Type *Z0Ty = Z0->getType();
3221 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3222
3223 // If C is a low-bits mask, the zero extend is zerving to
3224 // mask off the high bits. Complement the operand and
3225 // re-apply the zext.
3226 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3227 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3228
3229 // If C is a single bit, it may be in the sign-bit position
3230 // before the zero-extend. In this case, represent the xor
3231 // using an add, which is equivalent, and re-apply the zext.
3232 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3233 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3234 Trunc.isSignBit())
3235 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3236 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003237 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003238 }
3239 break;
3240
3241 case Instruction::Shl:
3242 // Turn shift left of a constant amount into a multiply.
3243 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003244 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003245 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003246 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003247 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003248 }
3249 break;
3250
Nick Lewycky01eaf802008-07-07 06:15:49 +00003251 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003252 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003253 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003254 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003255 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003256 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003257 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003258 }
3259 break;
3260
Dan Gohman4ee29af2009-04-21 02:26:00 +00003261 case Instruction::AShr:
3262 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3263 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3264 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3265 if (L->getOpcode() == Instruction::Shl &&
3266 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003267 unsigned BitWidth = getTypeSizeInBits(U->getType());
3268 uint64_t Amt = BitWidth - CI->getZExtValue();
3269 if (Amt == BitWidth)
3270 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3271 if (Amt > BitWidth)
3272 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003273 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003274 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003275 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003276 U->getType());
3277 }
3278 break;
3279
Dan Gohman6c459a22008-06-22 19:56:46 +00003280 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003281 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003282
3283 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003284 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003285
3286 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003287 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003288
3289 case Instruction::BitCast:
3290 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003291 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003292 return getSCEV(U->getOperand(0));
3293 break;
3294
Dan Gohman4f8eea82010-02-01 18:27:38 +00003295 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3296 // lead to pointer expressions which cannot safely be expanded to GEPs,
3297 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3298 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003299
Dan Gohman26466c02009-05-08 20:26:55 +00003300 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003301 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003302
Dan Gohman6c459a22008-06-22 19:56:46 +00003303 case Instruction::PHI:
3304 return createNodeForPHI(cast<PHINode>(U));
3305
3306 case Instruction::Select:
3307 // This could be a smax or umax that was lowered earlier.
3308 // Try to recover it.
3309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3310 Value *LHS = ICI->getOperand(0);
3311 Value *RHS = ICI->getOperand(1);
3312 switch (ICI->getPredicate()) {
3313 case ICmpInst::ICMP_SLT:
3314 case ICmpInst::ICMP_SLE:
3315 std::swap(LHS, RHS);
3316 // fall through
3317 case ICmpInst::ICMP_SGT:
3318 case ICmpInst::ICMP_SGE:
3319 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003320 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003321 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003322 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003323 break;
3324 case ICmpInst::ICMP_ULT:
3325 case ICmpInst::ICMP_ULE:
3326 std::swap(LHS, RHS);
3327 // fall through
3328 case ICmpInst::ICMP_UGT:
3329 case ICmpInst::ICMP_UGE:
3330 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003331 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003332 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003333 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003334 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003335 case ICmpInst::ICMP_NE:
3336 // n != 0 ? n : 1 -> umax(n, 1)
3337 if (LHS == U->getOperand(1) &&
3338 isa<ConstantInt>(U->getOperand(2)) &&
3339 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3340 isa<ConstantInt>(RHS) &&
3341 cast<ConstantInt>(RHS)->isZero())
3342 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3343 break;
3344 case ICmpInst::ICMP_EQ:
3345 // n == 0 ? 1 : n -> umax(n, 1)
3346 if (LHS == U->getOperand(2) &&
3347 isa<ConstantInt>(U->getOperand(1)) &&
3348 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3349 isa<ConstantInt>(RHS) &&
3350 cast<ConstantInt>(RHS)->isZero())
3351 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3352 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003353 default:
3354 break;
3355 }
3356 }
3357
3358 default: // We cannot analyze this expression.
3359 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003360 }
3361
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003362 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003363}
3364
3365
3366
3367//===----------------------------------------------------------------------===//
3368// Iteration Count Computation Code
3369//
3370
Dan Gohman46bdfb02009-02-24 18:55:53 +00003371/// getBackedgeTakenCount - If the specified loop has a predictable
3372/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3373/// object. The backedge-taken count is the number of times the loop header
3374/// will be branched to from within the loop. This is one less than the
3375/// trip count of the loop, since it doesn't count the first iteration,
3376/// when the header is branched to from outside the loop.
3377///
3378/// Note that it is not valid to call this method on a loop without a
3379/// loop-invariant backedge-taken count (see
3380/// hasLoopInvariantBackedgeTakenCount).
3381///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003382const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003383 return getBackedgeTakenInfo(L).Exact;
3384}
3385
3386/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3387/// return the least SCEV value that is known never to be less than the
3388/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003389const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003390 return getBackedgeTakenInfo(L).Max;
3391}
3392
Dan Gohman59ae6b92009-07-08 19:23:34 +00003393/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3394/// onto the given Worklist.
3395static void
3396PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3397 BasicBlock *Header = L->getHeader();
3398
3399 // Push all Loop-header PHIs onto the Worklist stack.
3400 for (BasicBlock::iterator I = Header->begin();
3401 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3402 Worklist.push_back(PN);
3403}
3404
Dan Gohmana1af7572009-04-30 20:47:05 +00003405const ScalarEvolution::BackedgeTakenInfo &
3406ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003407 // Initially insert a CouldNotCompute for this loop. If the insertion
3408 // succeeds, procede to actually compute a backedge-taken count and
3409 // update the value. The temporary CouldNotCompute value tells SCEV
3410 // code elsewhere that it shouldn't attempt to request a new
3411 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003412 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003413 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3414 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003415 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3416 if (BECount.Exact != getCouldNotCompute()) {
3417 assert(BECount.Exact->isLoopInvariant(L) &&
3418 BECount.Max->isLoopInvariant(L) &&
3419 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003420 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003421
Dan Gohman01ecca22009-04-27 20:16:15 +00003422 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003423 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003424 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003425 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003426 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003427 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003428 if (isa<PHINode>(L->getHeader()->begin()))
3429 // Only count loops that have phi nodes as not being computable.
3430 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003431 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003432
3433 // Now that we know more about the trip count for this loop, forget any
3434 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003435 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003436 // information. This is similar to the code in forgetLoop, except that
3437 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003438 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003439 SmallVector<Instruction *, 16> Worklist;
3440 PushLoopPHIs(L, Worklist);
3441
3442 SmallPtrSet<Instruction *, 8> Visited;
3443 while (!Worklist.empty()) {
3444 Instruction *I = Worklist.pop_back_val();
3445 if (!Visited.insert(I)) continue;
3446
Dan Gohman5d984912009-12-18 01:14:11 +00003447 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003448 Scalars.find(static_cast<Value *>(I));
3449 if (It != Scalars.end()) {
3450 // SCEVUnknown for a PHI either means that it has an unrecognized
3451 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003452 // by createNodeForPHI. In the former case, additional loop trip
3453 // count information isn't going to change anything. In the later
3454 // case, createNodeForPHI will perform the necessary updates on its
3455 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003456 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3457 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003458 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003459 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003460 if (PHINode *PN = dyn_cast<PHINode>(I))
3461 ConstantEvolutionLoopExitValue.erase(PN);
3462 }
3463
3464 PushDefUseChildren(I, Worklist);
3465 }
3466 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003467 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003468 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003469}
3470
Dan Gohman4c7279a2009-10-31 15:04:55 +00003471/// forgetLoop - This method should be called by the client when it has
3472/// changed a loop in a way that may effect ScalarEvolution's ability to
3473/// compute a trip count, or if the loop is deleted.
3474void ScalarEvolution::forgetLoop(const Loop *L) {
3475 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003476 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003477
Dan Gohman4c7279a2009-10-31 15:04:55 +00003478 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003479 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003480 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003481
Dan Gohman59ae6b92009-07-08 19:23:34 +00003482 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003483 while (!Worklist.empty()) {
3484 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003485 if (!Visited.insert(I)) continue;
3486
Dan Gohman5d984912009-12-18 01:14:11 +00003487 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003488 Scalars.find(static_cast<Value *>(I));
3489 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003490 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003491 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003492 if (PHINode *PN = dyn_cast<PHINode>(I))
3493 ConstantEvolutionLoopExitValue.erase(PN);
3494 }
3495
3496 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003497 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003498}
3499
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003500/// forgetValue - This method should be called by the client when it has
3501/// changed a value in a way that may effect its value, or which may
3502/// disconnect it from a def-use chain linking it to a loop.
3503void ScalarEvolution::forgetValue(Value *V) {
3504 Instruction *I = dyn_cast<Instruction>(V);
3505 if (!I) return;
3506
3507 // Drop information about expressions based on loop-header PHIs.
3508 SmallVector<Instruction *, 16> Worklist;
3509 Worklist.push_back(I);
3510
3511 SmallPtrSet<Instruction *, 8> Visited;
3512 while (!Worklist.empty()) {
3513 I = Worklist.pop_back_val();
3514 if (!Visited.insert(I)) continue;
3515
3516 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3517 Scalars.find(static_cast<Value *>(I));
3518 if (It != Scalars.end()) {
3519 ValuesAtScopes.erase(It->second);
3520 Scalars.erase(It);
3521 if (PHINode *PN = dyn_cast<PHINode>(I))
3522 ConstantEvolutionLoopExitValue.erase(PN);
3523 }
3524
3525 PushDefUseChildren(I, Worklist);
3526 }
3527}
3528
Dan Gohman46bdfb02009-02-24 18:55:53 +00003529/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3530/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003531ScalarEvolution::BackedgeTakenInfo
3532ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003533 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003534 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003535
Dan Gohmana334aa72009-06-22 00:31:57 +00003536 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003537 const SCEV *BECount = getCouldNotCompute();
3538 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003539 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003540 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3541 BackedgeTakenInfo NewBTI =
3542 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003543
Dan Gohman1c343752009-06-27 21:21:31 +00003544 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003545 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003546 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003547 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003548 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003549 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003550 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003551 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003552 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003553 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003554 }
Dan Gohman1c343752009-06-27 21:21:31 +00003555 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003556 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003557 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003558 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003559 }
3560
3561 return BackedgeTakenInfo(BECount, MaxBECount);
3562}
3563
3564/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3565/// of the specified loop will execute if it exits via the specified block.
3566ScalarEvolution::BackedgeTakenInfo
3567ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3568 BasicBlock *ExitingBlock) {
3569
3570 // Okay, we've chosen an exiting block. See what condition causes us to
3571 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003572 //
3573 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003574 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003575 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003576 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003577
Chris Lattner8b0e3602007-01-07 02:24:26 +00003578 // At this point, we know we have a conditional branch that determines whether
3579 // the loop is exited. However, we don't know if the branch is executed each
3580 // time through the loop. If not, then the execution count of the branch will
3581 // not be equal to the trip count of the loop.
3582 //
3583 // Currently we check for this by checking to see if the Exit branch goes to
3584 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003585 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003586 // loop header. This is common for un-rotated loops.
3587 //
3588 // If both of those tests fail, walk up the unique predecessor chain to the
3589 // header, stopping if there is an edge that doesn't exit the loop. If the
3590 // header is reached, the execution count of the branch will be equal to the
3591 // trip count of the loop.
3592 //
3593 // More extensive analysis could be done to handle more cases here.
3594 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003595 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003596 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003597 ExitBr->getParent() != L->getHeader()) {
3598 // The simple checks failed, try climbing the unique predecessor chain
3599 // up to the header.
3600 bool Ok = false;
3601 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3602 BasicBlock *Pred = BB->getUniquePredecessor();
3603 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003604 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003605 TerminatorInst *PredTerm = Pred->getTerminator();
3606 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3607 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3608 if (PredSucc == BB)
3609 continue;
3610 // If the predecessor has a successor that isn't BB and isn't
3611 // outside the loop, assume the worst.
3612 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003613 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003614 }
3615 if (Pred == L->getHeader()) {
3616 Ok = true;
3617 break;
3618 }
3619 BB = Pred;
3620 }
3621 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003622 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003623 }
3624
3625 // Procede to the next level to examine the exit condition expression.
3626 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3627 ExitBr->getSuccessor(0),
3628 ExitBr->getSuccessor(1));
3629}
3630
3631/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3632/// backedge of the specified loop will execute if its exit condition
3633/// were a conditional branch of ExitCond, TBB, and FBB.
3634ScalarEvolution::BackedgeTakenInfo
3635ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3636 Value *ExitCond,
3637 BasicBlock *TBB,
3638 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003639 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003640 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3641 if (BO->getOpcode() == Instruction::And) {
3642 // Recurse on the operands of the and.
3643 BackedgeTakenInfo BTI0 =
3644 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3645 BackedgeTakenInfo BTI1 =
3646 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003647 const SCEV *BECount = getCouldNotCompute();
3648 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003649 if (L->contains(TBB)) {
3650 // Both conditions must be true for the loop to continue executing.
3651 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003652 if (BTI0.Exact == getCouldNotCompute() ||
3653 BTI1.Exact == getCouldNotCompute())
3654 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003655 else
3656 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003657 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003658 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003659 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003660 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003661 else
3662 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003663 } else {
3664 // Both conditions must be true for the loop to exit.
3665 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003666 if (BTI0.Exact != getCouldNotCompute() &&
3667 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003668 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003669 if (BTI0.Max != getCouldNotCompute() &&
3670 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003671 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3672 }
3673
3674 return BackedgeTakenInfo(BECount, MaxBECount);
3675 }
3676 if (BO->getOpcode() == Instruction::Or) {
3677 // Recurse on the operands of the or.
3678 BackedgeTakenInfo BTI0 =
3679 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3680 BackedgeTakenInfo BTI1 =
3681 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003682 const SCEV *BECount = getCouldNotCompute();
3683 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003684 if (L->contains(FBB)) {
3685 // Both conditions must be false for the loop to continue executing.
3686 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003687 if (BTI0.Exact == getCouldNotCompute() ||
3688 BTI1.Exact == getCouldNotCompute())
3689 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003690 else
3691 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003692 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003693 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003694 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003695 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003696 else
3697 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003698 } else {
3699 // Both conditions must be false for the loop to exit.
3700 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003701 if (BTI0.Exact != getCouldNotCompute() &&
3702 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003703 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003704 if (BTI0.Max != getCouldNotCompute() &&
3705 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003706 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3707 }
3708
3709 return BackedgeTakenInfo(BECount, MaxBECount);
3710 }
3711 }
3712
3713 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3714 // Procede to the next level to examine the icmp.
3715 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3716 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717
Dan Gohman00cb5b72010-02-19 18:12:07 +00003718 // Check for a constant condition. These are normally stripped out by
3719 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3720 // preserve the CFG and is temporarily leaving constant conditions
3721 // in place.
3722 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3723 if (L->contains(FBB) == !CI->getZExtValue())
3724 // The backedge is always taken.
3725 return getCouldNotCompute();
3726 else
3727 // The backedge is never taken.
3728 return getIntegerSCEV(0, CI->getType());
3729 }
3730
Eli Friedman361e54d2009-05-09 12:32:42 +00003731 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003732 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3733}
3734
3735/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3736/// backedge of the specified loop will execute if its exit condition
3737/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3738ScalarEvolution::BackedgeTakenInfo
3739ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3740 ICmpInst *ExitCond,
3741 BasicBlock *TBB,
3742 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003743
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744 // If the condition was exit on true, convert the condition to exit on false
3745 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003746 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003747 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003748 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003749 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003750
3751 // Handle common loops like: for (X = "string"; *X; ++X)
3752 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3753 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003754 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003755 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003756 if (ItCnt.hasAnyInfo())
3757 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003758 }
3759
Dan Gohman0bba49c2009-07-07 17:06:11 +00003760 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3761 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003762
3763 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003764 LHS = getSCEVAtScope(LHS, L);
3765 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003766
Dan Gohman64a845e2009-06-24 04:48:43 +00003767 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003768 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003769 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3770 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003771 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003772 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003773 }
3774
Chris Lattner53e677a2004-04-02 20:23:17 +00003775 // If we have a comparison of a chrec against a constant, try to use value
3776 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003777 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3778 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003779 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003780 // Form the constant range.
3781 ConstantRange CompRange(
3782 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003783
Dan Gohman0bba49c2009-07-07 17:06:11 +00003784 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003785 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003786 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003787
Chris Lattner53e677a2004-04-02 20:23:17 +00003788 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003789 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003790 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003791 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3792 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003793 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003794 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003795 case ICmpInst::ICMP_EQ: { // while (X == Y)
3796 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003797 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3798 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003799 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003800 }
3801 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003802 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3803 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003804 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003805 }
3806 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003807 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3808 getNotSCEV(RHS), L, true);
3809 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003810 break;
3811 }
3812 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003813 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3814 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003815 break;
3816 }
3817 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003818 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3819 getNotSCEV(RHS), L, false);
3820 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003821 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003822 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003823 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003824#if 0
David Greene25e0e872009-12-23 22:18:14 +00003825 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003826 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003827 dbgs() << "[unsigned] ";
3828 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003829 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003830 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003831#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003832 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003833 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003834 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003835 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003836}
3837
Chris Lattner673e02b2004-10-12 01:49:27 +00003838static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003839EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3840 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003841 const SCEV *InVal = SE.getConstant(C);
3842 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003843 assert(isa<SCEVConstant>(Val) &&
3844 "Evaluation of SCEV at constant didn't fold correctly?");
3845 return cast<SCEVConstant>(Val)->getValue();
3846}
3847
3848/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3849/// and a GEP expression (missing the pointer index) indexing into it, return
3850/// the addressed element of the initializer or null if the index expression is
3851/// invalid.
3852static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003853GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003854 const std::vector<ConstantInt*> &Indices) {
3855 Constant *Init = GV->getInitializer();
3856 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003857 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003858 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3859 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3860 Init = cast<Constant>(CS->getOperand(Idx));
3861 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3862 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3863 Init = cast<Constant>(CA->getOperand(Idx));
3864 } else if (isa<ConstantAggregateZero>(Init)) {
3865 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3866 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003867 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003868 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3869 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003870 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003871 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003872 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003873 }
3874 return 0;
3875 } else {
3876 return 0; // Unknown initializer type
3877 }
3878 }
3879 return Init;
3880}
3881
Dan Gohman46bdfb02009-02-24 18:55:53 +00003882/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3883/// 'icmp op load X, cst', try to see if we can compute the backedge
3884/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003885ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00003886ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3887 LoadInst *LI,
3888 Constant *RHS,
3889 const Loop *L,
3890 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003891 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003892
3893 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003894 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00003895 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003896 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003897
3898 // Make sure that it is really a constant global we are gepping, with an
3899 // initializer, and make sure the first IDX is really 0.
3900 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003901 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003902 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3903 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003904 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003905
3906 // Okay, we allow one non-constant index into the GEP instruction.
3907 Value *VarIdx = 0;
3908 std::vector<ConstantInt*> Indexes;
3909 unsigned VarIdxNum = 0;
3910 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3911 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3912 Indexes.push_back(CI);
3913 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003914 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003915 VarIdx = GEP->getOperand(i);
3916 VarIdxNum = i-2;
3917 Indexes.push_back(0);
3918 }
3919
3920 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3921 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003922 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003923 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003924
3925 // We can only recognize very limited forms of loop index expressions, in
3926 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003927 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003928 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3929 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3930 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003931 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003932
3933 unsigned MaxSteps = MaxBruteForceIterations;
3934 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003935 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003936 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003937 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003938
3939 // Form the GEP offset.
3940 Indexes[VarIdxNum] = Val;
3941
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003942 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003943 if (Result == 0) break; // Cannot compute!
3944
3945 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003946 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003947 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003948 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003949#if 0
David Greene25e0e872009-12-23 22:18:14 +00003950 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003951 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3952 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003953#endif
3954 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003955 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003956 }
3957 }
Dan Gohman1c343752009-06-27 21:21:31 +00003958 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003959}
3960
3961
Chris Lattner3221ad02004-04-17 22:58:41 +00003962/// CanConstantFold - Return true if we can constant fold an instruction of the
3963/// specified type, assuming that all operands were constants.
3964static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003965 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003966 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3967 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003968
Chris Lattner3221ad02004-04-17 22:58:41 +00003969 if (const CallInst *CI = dyn_cast<CallInst>(I))
3970 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003971 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003972 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003973}
3974
Chris Lattner3221ad02004-04-17 22:58:41 +00003975/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3976/// in the loop that V is derived from. We allow arbitrary operations along the
3977/// way, but the operands of an operation must either be constants or a value
3978/// derived from a constant PHI. If this expression does not fit with these
3979/// constraints, return null.
3980static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3981 // If this is not an instruction, or if this is an instruction outside of the
3982 // loop, it can't be derived from a loop PHI.
3983 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003984 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003985
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003986 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003987 if (L->getHeader() == I->getParent())
3988 return PN;
3989 else
3990 // We don't currently keep track of the control flow needed to evaluate
3991 // PHIs, so we cannot handle PHIs inside of loops.
3992 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003993 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003994
3995 // If we won't be able to constant fold this expression even if the operands
3996 // are constants, return early.
3997 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003998
Chris Lattner3221ad02004-04-17 22:58:41 +00003999 // Otherwise, we can evaluate this instruction if all of its operands are
4000 // constant or derived from a PHI node themselves.
4001 PHINode *PHI = 0;
4002 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4003 if (!(isa<Constant>(I->getOperand(Op)) ||
4004 isa<GlobalValue>(I->getOperand(Op)))) {
4005 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4006 if (P == 0) return 0; // Not evolving from PHI
4007 if (PHI == 0)
4008 PHI = P;
4009 else if (PHI != P)
4010 return 0; // Evolving from multiple different PHIs.
4011 }
4012
4013 // This is a expression evolving from a constant PHI!
4014 return PHI;
4015}
4016
4017/// EvaluateExpression - Given an expression that passes the
4018/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4019/// in the loop has the value PHIVal. If we can't fold this expression for some
4020/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004021static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4022 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004023 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004024 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00004025 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00004026 Instruction *I = cast<Instruction>(V);
4027
4028 std::vector<Constant*> Operands;
4029 Operands.resize(I->getNumOperands());
4030
4031 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004032 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004033 if (Operands[i] == 0) return 0;
4034 }
4035
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004036 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004037 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004038 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004039 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004040 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004041}
4042
4043/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4044/// in the header of its containing loop, we know the loop executes a
4045/// constant number of times, and the PHI node is just a recurrence
4046/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004047Constant *
4048ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004049 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004050 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004051 std::map<PHINode*, Constant*>::iterator I =
4052 ConstantEvolutionLoopExitValue.find(PN);
4053 if (I != ConstantEvolutionLoopExitValue.end())
4054 return I->second;
4055
Dan Gohman46bdfb02009-02-24 18:55:53 +00004056 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00004057 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4058
4059 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4060
4061 // Since the loop is canonicalized, the PHI node must have two entries. One
4062 // entry must be a constant (coming in from outside of the loop), and the
4063 // second must be derived from the same PHI.
4064 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4065 Constant *StartCST =
4066 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4067 if (StartCST == 0)
4068 return RetVal = 0; // Must be a constant.
4069
4070 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4071 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4072 if (PN2 != PN)
4073 return RetVal = 0; // Not derived from same PHI.
4074
4075 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004076 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004077 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004078
Dan Gohman46bdfb02009-02-24 18:55:53 +00004079 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004080 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004081 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4082 if (IterationNum == NumIterations)
4083 return RetVal = PHIVal; // Got exit value!
4084
4085 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004086 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004087 if (NextPHI == PHIVal)
4088 return RetVal = NextPHI; // Stopped evolving!
4089 if (NextPHI == 0)
4090 return 0; // Couldn't evaluate!
4091 PHIVal = NextPHI;
4092 }
4093}
4094
Dan Gohman07ad19b2009-07-27 16:09:48 +00004095/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004096/// constant number of times (the condition evolves only from constants),
4097/// try to evaluate a few iterations of the loop until we get the exit
4098/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004099/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004100const SCEV *
4101ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4102 Value *Cond,
4103 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004104 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004105 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004106
4107 // Since the loop is canonicalized, the PHI node must have two entries. One
4108 // entry must be a constant (coming in from outside of the loop), and the
4109 // second must be derived from the same PHI.
4110 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4111 Constant *StartCST =
4112 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004113 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004114
4115 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4116 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004117 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004118
4119 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4120 // the loop symbolically to determine when the condition gets a value of
4121 // "ExitWhen".
4122 unsigned IterationNum = 0;
4123 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4124 for (Constant *PHIVal = StartCST;
4125 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004126 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004127 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004128
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004129 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004130 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004131
Reid Spencere8019bb2007-03-01 07:25:48 +00004132 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004133 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004134 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004135 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004136
Chris Lattner3221ad02004-04-17 22:58:41 +00004137 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004138 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004139 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004140 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004141 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004142 }
4143
4144 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004145 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004146}
4147
Dan Gohmane7125f42009-09-03 15:00:26 +00004148/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004149/// at the specified scope in the program. The L value specifies a loop
4150/// nest to evaluate the expression at, where null is the top-level or a
4151/// specified loop is immediately inside of the loop.
4152///
4153/// This method can be used to compute the exit value for a variable defined
4154/// in a loop by querying what the value will hold in the parent loop.
4155///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004156/// In the case that a relevant loop exit value cannot be computed, the
4157/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004158const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004159 // Check to see if we've folded this expression at this loop before.
4160 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4161 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4162 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4163 if (!Pair.second)
4164 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004165
Dan Gohman42214892009-08-31 21:15:23 +00004166 // Otherwise compute it.
4167 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004168 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004169 return C;
4170}
4171
4172const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004173 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004174
Nick Lewycky3e630762008-02-20 06:48:22 +00004175 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004176 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004177 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004178 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004179 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004180 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4181 if (PHINode *PN = dyn_cast<PHINode>(I))
4182 if (PN->getParent() == LI->getHeader()) {
4183 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004184 // to see if the loop that contains it has a known backedge-taken
4185 // count. If so, we may be able to force computation of the exit
4186 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004187 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004188 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004189 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004190 // Okay, we know how many times the containing loop executes. If
4191 // this is a constant evolving PHI node, get the final value at
4192 // the specified iteration number.
4193 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004194 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004195 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004196 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004197 }
4198 }
4199
Reid Spencer09906f32006-12-04 21:33:23 +00004200 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004201 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004202 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004203 // result. This is particularly useful for computing loop exit values.
4204 if (CanConstantFold(I)) {
4205 std::vector<Constant*> Operands;
4206 Operands.reserve(I->getNumOperands());
4207 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4208 Value *Op = I->getOperand(i);
4209 if (Constant *C = dyn_cast<Constant>(Op)) {
4210 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004211 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004212 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004213 // non-integer and non-pointer, don't even try to analyze them
4214 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004215 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004216 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004217
Dan Gohman5d984912009-12-18 01:14:11 +00004218 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004219 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004220 Constant *C = SC->getValue();
4221 if (C->getType() != Op->getType())
4222 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4223 Op->getType(),
4224 false),
4225 C, Op->getType());
4226 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004227 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004228 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4229 if (C->getType() != Op->getType())
4230 C =
4231 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4232 Op->getType(),
4233 false),
4234 C, Op->getType());
4235 Operands.push_back(C);
4236 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004237 return V;
4238 } else {
4239 return V;
4240 }
4241 }
4242 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004243
Dan Gohmane177c9a2010-02-24 19:31:47 +00004244 Constant *C = 0;
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004245 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4246 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004247 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004248 else
4249 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004250 &Operands[0], Operands.size(), TD);
Dan Gohmane177c9a2010-02-24 19:31:47 +00004251 if (C)
4252 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004253 }
4254 }
4255
4256 // This is some other type of SCEVUnknown, just return it.
4257 return V;
4258 }
4259
Dan Gohman622ed672009-05-04 22:02:23 +00004260 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004261 // Avoid performing the look-up in the common case where the specified
4262 // expression has no loop-variant portions.
4263 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004264 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004265 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004266 // Okay, at least one of these operands is loop variant but might be
4267 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004268 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4269 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004270 NewOps.push_back(OpAtScope);
4271
4272 for (++i; i != e; ++i) {
4273 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004274 NewOps.push_back(OpAtScope);
4275 }
4276 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004277 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004278 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004279 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004280 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004281 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004282 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004283 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004284 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004285 }
4286 }
4287 // If we got here, all operands are loop invariant.
4288 return Comm;
4289 }
4290
Dan Gohman622ed672009-05-04 22:02:23 +00004291 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004292 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4293 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004294 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4295 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004296 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004297 }
4298
4299 // If this is a loop recurrence for a loop that does not contain L, then we
4300 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004301 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004302 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004303 // To evaluate this recurrence, we need to know how many times the AddRec
4304 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004305 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004306 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004307
Eli Friedmanb42a6262008-08-04 23:49:06 +00004308 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004309 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004310 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004311 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004312 }
4313
Dan Gohman622ed672009-05-04 22:02:23 +00004314 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004315 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004316 if (Op == Cast->getOperand())
4317 return Cast; // must be loop invariant
4318 return getZeroExtendExpr(Op, Cast->getType());
4319 }
4320
Dan Gohman622ed672009-05-04 22:02:23 +00004321 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004322 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004323 if (Op == Cast->getOperand())
4324 return Cast; // must be loop invariant
4325 return getSignExtendExpr(Op, Cast->getType());
4326 }
4327
Dan Gohman622ed672009-05-04 22:02:23 +00004328 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004329 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004330 if (Op == Cast->getOperand())
4331 return Cast; // must be loop invariant
4332 return getTruncateExpr(Op, Cast->getType());
4333 }
4334
Torok Edwinc23197a2009-07-14 16:55:14 +00004335 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004336 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004337}
4338
Dan Gohman66a7e852009-05-08 20:38:54 +00004339/// getSCEVAtScope - This is a convenience function which does
4340/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004341const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004342 return getSCEVAtScope(getSCEV(V), L);
4343}
4344
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004345/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4346/// following equation:
4347///
4348/// A * X = B (mod N)
4349///
4350/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4351/// A and B isn't important.
4352///
4353/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004354static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004355 ScalarEvolution &SE) {
4356 uint32_t BW = A.getBitWidth();
4357 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4358 assert(A != 0 && "A must be non-zero.");
4359
4360 // 1. D = gcd(A, N)
4361 //
4362 // The gcd of A and N may have only one prime factor: 2. The number of
4363 // trailing zeros in A is its multiplicity
4364 uint32_t Mult2 = A.countTrailingZeros();
4365 // D = 2^Mult2
4366
4367 // 2. Check if B is divisible by D.
4368 //
4369 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4370 // is not less than multiplicity of this prime factor for D.
4371 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004372 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004373
4374 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4375 // modulo (N / D).
4376 //
4377 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4378 // bit width during computations.
4379 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4380 APInt Mod(BW + 1, 0);
4381 Mod.set(BW - Mult2); // Mod = N / D
4382 APInt I = AD.multiplicativeInverse(Mod);
4383
4384 // 4. Compute the minimum unsigned root of the equation:
4385 // I * (B / D) mod (N / D)
4386 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4387
4388 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4389 // bits.
4390 return SE.getConstant(Result.trunc(BW));
4391}
Chris Lattner53e677a2004-04-02 20:23:17 +00004392
4393/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4394/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4395/// might be the same) or two SCEVCouldNotCompute objects.
4396///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004397static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004398SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004399 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004400 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4401 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4402 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004403
Chris Lattner53e677a2004-04-02 20:23:17 +00004404 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004405 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004406 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004407 return std::make_pair(CNC, CNC);
4408 }
4409
Reid Spencere8019bb2007-03-01 07:25:48 +00004410 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004411 const APInt &L = LC->getValue()->getValue();
4412 const APInt &M = MC->getValue()->getValue();
4413 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004414 APInt Two(BitWidth, 2);
4415 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004416
Dan Gohman64a845e2009-06-24 04:48:43 +00004417 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004418 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004419 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004420 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4421 // The B coefficient is M-N/2
4422 APInt B(M);
4423 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004424
Reid Spencere8019bb2007-03-01 07:25:48 +00004425 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004426 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004427
Reid Spencere8019bb2007-03-01 07:25:48 +00004428 // Compute the B^2-4ac term.
4429 APInt SqrtTerm(B);
4430 SqrtTerm *= B;
4431 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004432
Reid Spencere8019bb2007-03-01 07:25:48 +00004433 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4434 // integer value or else APInt::sqrt() will assert.
4435 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004436
Dan Gohman64a845e2009-06-24 04:48:43 +00004437 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004438 // The divisions must be performed as signed divisions.
4439 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004440 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004441 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004442 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004443 return std::make_pair(CNC, CNC);
4444 }
4445
Owen Andersone922c022009-07-22 00:24:57 +00004446 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004447
4448 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004449 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004450 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004451 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004452
Dan Gohman64a845e2009-06-24 04:48:43 +00004453 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004454 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004455 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004456}
4457
4458/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004459/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004460ScalarEvolution::BackedgeTakenInfo
4461ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004462 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004463 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004464 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004465 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004466 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004467 }
4468
Dan Gohman35738ac2009-05-04 22:30:44 +00004469 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004470 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004471 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004472
4473 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004474 // If this is an affine expression, the execution count of this branch is
4475 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004476 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004477 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004478 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004479 // equivalent to:
4480 //
4481 // Step*N = -Start (mod 2^BW)
4482 //
4483 // where BW is the common bit width of Start and Step.
4484
Chris Lattner53e677a2004-04-02 20:23:17 +00004485 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004486 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4487 L->getParentLoop());
4488 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4489 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004490
Dan Gohman622ed672009-05-04 22:02:23 +00004491 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004492 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004493
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004494 // First, handle unitary steps.
4495 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004496 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004497 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4498 return Start; // N = Start (as unsigned)
4499
4500 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004501 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004502 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004503 -StartC->getValue()->getValue(),
4504 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004505 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004506 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004507 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4508 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004509 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004510 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004511 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4512 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004513 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004514#if 0
David Greene25e0e872009-12-23 22:18:14 +00004515 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004516 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004517#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004518 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004519 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004520 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004521 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004522 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004523 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004524
Chris Lattner53e677a2004-04-02 20:23:17 +00004525 // We can only use this value if the chrec ends up with an exact zero
4526 // value at this index. When solving for "X*X != 5", for example, we
4527 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004528 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004529 if (Val->isZero())
4530 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004531 }
4532 }
4533 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004534
Dan Gohman1c343752009-06-27 21:21:31 +00004535 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004536}
4537
4538/// HowFarToNonZero - Return the number of times a backedge checking the
4539/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004540/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004541ScalarEvolution::BackedgeTakenInfo
4542ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004543 // Loops that look like: while (X == 0) are very strange indeed. We don't
4544 // handle them yet except for the trivial case. This could be expanded in the
4545 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004546
Chris Lattner53e677a2004-04-02 20:23:17 +00004547 // If the value is a constant, check to see if it is known to be non-zero
4548 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004549 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004550 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004551 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004552 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004553 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004554
Chris Lattner53e677a2004-04-02 20:23:17 +00004555 // We could implement others, but I really doubt anyone writes loops like
4556 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004557 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004558}
4559
Dan Gohman859b4822009-05-18 15:36:09 +00004560/// getLoopPredecessor - If the given loop's header has exactly one unique
4561/// predecessor outside the loop, return it. Otherwise return null.
4562///
4563BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4564 BasicBlock *Header = L->getHeader();
4565 BasicBlock *Pred = 0;
4566 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4567 PI != E; ++PI)
4568 if (!L->contains(*PI)) {
4569 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4570 Pred = *PI;
4571 }
4572 return Pred;
4573}
4574
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004575/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4576/// (which may not be an immediate predecessor) which has exactly one
4577/// successor from which BB is reachable, or null if no such block is
4578/// found.
4579///
4580BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004581ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004582 // If the block has a unique predecessor, then there is no path from the
4583 // predecessor to the block that does not go through the direct edge
4584 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004585 if (BasicBlock *Pred = BB->getSinglePredecessor())
4586 return Pred;
4587
4588 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004589 // If the header has a unique predecessor outside the loop, it must be
4590 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004591 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004592 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004593
4594 return 0;
4595}
4596
Dan Gohman763bad12009-06-20 00:35:32 +00004597/// HasSameValue - SCEV structural equivalence is usually sufficient for
4598/// testing whether two expressions are equal, however for the purposes of
4599/// looking for a condition guarding a loop, it can be useful to be a little
4600/// more general, since a front-end may have replicated the controlling
4601/// expression.
4602///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004603static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004604 // Quick check to see if they are the same SCEV.
4605 if (A == B) return true;
4606
4607 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4608 // two different instructions with the same value. Check for this case.
4609 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4610 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4611 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4612 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004613 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004614 return true;
4615
4616 // Otherwise assume they may have a different value.
4617 return false;
4618}
4619
Dan Gohman85b05a22009-07-13 21:35:55 +00004620bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4621 return getSignedRange(S).getSignedMax().isNegative();
4622}
4623
4624bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4625 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4626}
4627
4628bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4629 return !getSignedRange(S).getSignedMin().isNegative();
4630}
4631
4632bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4633 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4634}
4635
4636bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4637 return isKnownNegative(S) || isKnownPositive(S);
4638}
4639
4640bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4641 const SCEV *LHS, const SCEV *RHS) {
4642
4643 if (HasSameValue(LHS, RHS))
4644 return ICmpInst::isTrueWhenEqual(Pred);
4645
4646 switch (Pred) {
4647 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004648 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004649 break;
4650 case ICmpInst::ICMP_SGT:
4651 Pred = ICmpInst::ICMP_SLT;
4652 std::swap(LHS, RHS);
4653 case ICmpInst::ICMP_SLT: {
4654 ConstantRange LHSRange = getSignedRange(LHS);
4655 ConstantRange RHSRange = getSignedRange(RHS);
4656 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4657 return true;
4658 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4659 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004660 break;
4661 }
4662 case ICmpInst::ICMP_SGE:
4663 Pred = ICmpInst::ICMP_SLE;
4664 std::swap(LHS, RHS);
4665 case ICmpInst::ICMP_SLE: {
4666 ConstantRange LHSRange = getSignedRange(LHS);
4667 ConstantRange RHSRange = getSignedRange(RHS);
4668 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4669 return true;
4670 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4671 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004672 break;
4673 }
4674 case ICmpInst::ICMP_UGT:
4675 Pred = ICmpInst::ICMP_ULT;
4676 std::swap(LHS, RHS);
4677 case ICmpInst::ICMP_ULT: {
4678 ConstantRange LHSRange = getUnsignedRange(LHS);
4679 ConstantRange RHSRange = getUnsignedRange(RHS);
4680 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4681 return true;
4682 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4683 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004684 break;
4685 }
4686 case ICmpInst::ICMP_UGE:
4687 Pred = ICmpInst::ICMP_ULE;
4688 std::swap(LHS, RHS);
4689 case ICmpInst::ICMP_ULE: {
4690 ConstantRange LHSRange = getUnsignedRange(LHS);
4691 ConstantRange RHSRange = getUnsignedRange(RHS);
4692 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4693 return true;
4694 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4695 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004696 break;
4697 }
4698 case ICmpInst::ICMP_NE: {
4699 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4700 return true;
4701 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4702 return true;
4703
4704 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4705 if (isKnownNonZero(Diff))
4706 return true;
4707 break;
4708 }
4709 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004710 // The check at the top of the function catches the case where
4711 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004712 break;
4713 }
4714 return false;
4715}
4716
4717/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4718/// protected by a conditional between LHS and RHS. This is used to
4719/// to eliminate casts.
4720bool
4721ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4722 ICmpInst::Predicate Pred,
4723 const SCEV *LHS, const SCEV *RHS) {
4724 // Interpret a null as meaning no loop, where there is obviously no guard
4725 // (interprocedural conditions notwithstanding).
4726 if (!L) return true;
4727
4728 BasicBlock *Latch = L->getLoopLatch();
4729 if (!Latch)
4730 return false;
4731
4732 BranchInst *LoopContinuePredicate =
4733 dyn_cast<BranchInst>(Latch->getTerminator());
4734 if (!LoopContinuePredicate ||
4735 LoopContinuePredicate->isUnconditional())
4736 return false;
4737
Dan Gohman0f4b2852009-07-21 23:03:19 +00004738 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4739 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004740}
4741
4742/// isLoopGuardedByCond - Test whether entry to the loop is protected
4743/// by a conditional between LHS and RHS. This is used to help avoid max
4744/// expressions in loop trip counts, and to eliminate casts.
4745bool
4746ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4747 ICmpInst::Predicate Pred,
4748 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004749 // Interpret a null as meaning no loop, where there is obviously no guard
4750 // (interprocedural conditions notwithstanding).
4751 if (!L) return false;
4752
Dan Gohman859b4822009-05-18 15:36:09 +00004753 BasicBlock *Predecessor = getLoopPredecessor(L);
4754 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004755
Dan Gohman859b4822009-05-18 15:36:09 +00004756 // Starting at the loop predecessor, climb up the predecessor chain, as long
4757 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004758 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004759 for (; Predecessor;
4760 PredecessorDest = Predecessor,
4761 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004762
4763 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004764 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004765 if (!LoopEntryPredicate ||
4766 LoopEntryPredicate->isUnconditional())
4767 continue;
4768
Dan Gohman0f4b2852009-07-21 23:03:19 +00004769 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4770 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004771 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004772 }
4773
Dan Gohman38372182008-08-12 20:17:31 +00004774 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004775}
4776
Dan Gohman0f4b2852009-07-21 23:03:19 +00004777/// isImpliedCond - Test whether the condition described by Pred, LHS,
4778/// and RHS is true whenever the given Cond value evaluates to true.
4779bool ScalarEvolution::isImpliedCond(Value *CondValue,
4780 ICmpInst::Predicate Pred,
4781 const SCEV *LHS, const SCEV *RHS,
4782 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004783 // Recursivly handle And and Or conditions.
4784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4785 if (BO->getOpcode() == Instruction::And) {
4786 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004787 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4788 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004789 } else if (BO->getOpcode() == Instruction::Or) {
4790 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004791 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4792 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004793 }
4794 }
4795
4796 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4797 if (!ICI) return false;
4798
Dan Gohman85b05a22009-07-13 21:35:55 +00004799 // Bail if the ICmp's operands' types are wider than the needed type
4800 // before attempting to call getSCEV on them. This avoids infinite
4801 // recursion, since the analysis of widening casts can require loop
4802 // exit condition information for overflow checking, which would
4803 // lead back here.
4804 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004805 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004806 return false;
4807
Dan Gohman0f4b2852009-07-21 23:03:19 +00004808 // Now that we found a conditional branch that dominates the loop, check to
4809 // see if it is the comparison we are looking for.
4810 ICmpInst::Predicate FoundPred;
4811 if (Inverse)
4812 FoundPred = ICI->getInversePredicate();
4813 else
4814 FoundPred = ICI->getPredicate();
4815
4816 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4817 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004818
4819 // Balance the types. The case where FoundLHS' type is wider than
4820 // LHS' type is checked for above.
4821 if (getTypeSizeInBits(LHS->getType()) >
4822 getTypeSizeInBits(FoundLHS->getType())) {
4823 if (CmpInst::isSigned(Pred)) {
4824 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4825 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4826 } else {
4827 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4828 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4829 }
4830 }
4831
Dan Gohman0f4b2852009-07-21 23:03:19 +00004832 // Canonicalize the query to match the way instcombine will have
4833 // canonicalized the comparison.
4834 // First, put a constant operand on the right.
4835 if (isa<SCEVConstant>(LHS)) {
4836 std::swap(LHS, RHS);
4837 Pred = ICmpInst::getSwappedPredicate(Pred);
4838 }
4839 // Then, canonicalize comparisons with boundary cases.
4840 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4841 const APInt &RA = RC->getValue()->getValue();
4842 switch (Pred) {
4843 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4844 case ICmpInst::ICMP_EQ:
4845 case ICmpInst::ICMP_NE:
4846 break;
4847 case ICmpInst::ICMP_UGE:
4848 if ((RA - 1).isMinValue()) {
4849 Pred = ICmpInst::ICMP_NE;
4850 RHS = getConstant(RA - 1);
4851 break;
4852 }
4853 if (RA.isMaxValue()) {
4854 Pred = ICmpInst::ICMP_EQ;
4855 break;
4856 }
4857 if (RA.isMinValue()) return true;
4858 break;
4859 case ICmpInst::ICMP_ULE:
4860 if ((RA + 1).isMaxValue()) {
4861 Pred = ICmpInst::ICMP_NE;
4862 RHS = getConstant(RA + 1);
4863 break;
4864 }
4865 if (RA.isMinValue()) {
4866 Pred = ICmpInst::ICMP_EQ;
4867 break;
4868 }
4869 if (RA.isMaxValue()) return true;
4870 break;
4871 case ICmpInst::ICMP_SGE:
4872 if ((RA - 1).isMinSignedValue()) {
4873 Pred = ICmpInst::ICMP_NE;
4874 RHS = getConstant(RA - 1);
4875 break;
4876 }
4877 if (RA.isMaxSignedValue()) {
4878 Pred = ICmpInst::ICMP_EQ;
4879 break;
4880 }
4881 if (RA.isMinSignedValue()) return true;
4882 break;
4883 case ICmpInst::ICMP_SLE:
4884 if ((RA + 1).isMaxSignedValue()) {
4885 Pred = ICmpInst::ICMP_NE;
4886 RHS = getConstant(RA + 1);
4887 break;
4888 }
4889 if (RA.isMinSignedValue()) {
4890 Pred = ICmpInst::ICMP_EQ;
4891 break;
4892 }
4893 if (RA.isMaxSignedValue()) return true;
4894 break;
4895 case ICmpInst::ICMP_UGT:
4896 if (RA.isMinValue()) {
4897 Pred = ICmpInst::ICMP_NE;
4898 break;
4899 }
4900 if ((RA + 1).isMaxValue()) {
4901 Pred = ICmpInst::ICMP_EQ;
4902 RHS = getConstant(RA + 1);
4903 break;
4904 }
4905 if (RA.isMaxValue()) return false;
4906 break;
4907 case ICmpInst::ICMP_ULT:
4908 if (RA.isMaxValue()) {
4909 Pred = ICmpInst::ICMP_NE;
4910 break;
4911 }
4912 if ((RA - 1).isMinValue()) {
4913 Pred = ICmpInst::ICMP_EQ;
4914 RHS = getConstant(RA - 1);
4915 break;
4916 }
4917 if (RA.isMinValue()) return false;
4918 break;
4919 case ICmpInst::ICMP_SGT:
4920 if (RA.isMinSignedValue()) {
4921 Pred = ICmpInst::ICMP_NE;
4922 break;
4923 }
4924 if ((RA + 1).isMaxSignedValue()) {
4925 Pred = ICmpInst::ICMP_EQ;
4926 RHS = getConstant(RA + 1);
4927 break;
4928 }
4929 if (RA.isMaxSignedValue()) return false;
4930 break;
4931 case ICmpInst::ICMP_SLT:
4932 if (RA.isMaxSignedValue()) {
4933 Pred = ICmpInst::ICMP_NE;
4934 break;
4935 }
4936 if ((RA - 1).isMinSignedValue()) {
4937 Pred = ICmpInst::ICMP_EQ;
4938 RHS = getConstant(RA - 1);
4939 break;
4940 }
4941 if (RA.isMinSignedValue()) return false;
4942 break;
4943 }
4944 }
4945
4946 // Check to see if we can make the LHS or RHS match.
4947 if (LHS == FoundRHS || RHS == FoundLHS) {
4948 if (isa<SCEVConstant>(RHS)) {
4949 std::swap(FoundLHS, FoundRHS);
4950 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4951 } else {
4952 std::swap(LHS, RHS);
4953 Pred = ICmpInst::getSwappedPredicate(Pred);
4954 }
4955 }
4956
4957 // Check whether the found predicate is the same as the desired predicate.
4958 if (FoundPred == Pred)
4959 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4960
4961 // Check whether swapping the found predicate makes it the same as the
4962 // desired predicate.
4963 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4964 if (isa<SCEVConstant>(RHS))
4965 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4966 else
4967 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4968 RHS, LHS, FoundLHS, FoundRHS);
4969 }
4970
4971 // Check whether the actual condition is beyond sufficient.
4972 if (FoundPred == ICmpInst::ICMP_EQ)
4973 if (ICmpInst::isTrueWhenEqual(Pred))
4974 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4975 return true;
4976 if (Pred == ICmpInst::ICMP_NE)
4977 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4978 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4979 return true;
4980
4981 // Otherwise assume the worst.
4982 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004983}
4984
Dan Gohman0f4b2852009-07-21 23:03:19 +00004985/// isImpliedCondOperands - Test whether the condition described by Pred,
4986/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4987/// and FoundRHS is true.
4988bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4989 const SCEV *LHS, const SCEV *RHS,
4990 const SCEV *FoundLHS,
4991 const SCEV *FoundRHS) {
4992 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4993 FoundLHS, FoundRHS) ||
4994 // ~x < ~y --> x > y
4995 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4996 getNotSCEV(FoundRHS),
4997 getNotSCEV(FoundLHS));
4998}
4999
5000/// isImpliedCondOperandsHelper - Test whether the condition described by
5001/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
5002/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005003bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005004ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5005 const SCEV *LHS, const SCEV *RHS,
5006 const SCEV *FoundLHS,
5007 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005008 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005009 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5010 case ICmpInst::ICMP_EQ:
5011 case ICmpInst::ICMP_NE:
5012 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5013 return true;
5014 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005015 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005016 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005017 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5018 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5019 return true;
5020 break;
5021 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005022 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005023 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5024 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5025 return true;
5026 break;
5027 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005028 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005029 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5030 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5031 return true;
5032 break;
5033 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005034 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00005035 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5036 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5037 return true;
5038 break;
5039 }
5040
5041 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005042}
5043
Dan Gohman51f53b72009-06-21 23:46:38 +00005044/// getBECount - Subtract the end and start values and divide by the step,
5045/// rounding up, to get the number of times the backedge is executed. Return
5046/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005047const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005048 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005049 const SCEV *Step,
5050 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005051 assert(!isKnownNegative(Step) &&
5052 "This code doesn't handle negative strides yet!");
5053
Dan Gohman51f53b72009-06-21 23:46:38 +00005054 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00005055 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
5056 const SCEV *Diff = getMinusSCEV(End, Start);
5057 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005058
5059 // Add an adjustment to the difference between End and Start so that
5060 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005061 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005062
Dan Gohman1f96e672009-09-17 18:05:20 +00005063 if (!NoWrap) {
5064 // Check Add for unsigned overflow.
5065 // TODO: More sophisticated things could be done here.
5066 const Type *WideTy = IntegerType::get(getContext(),
5067 getTypeSizeInBits(Ty) + 1);
5068 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5069 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5070 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5071 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5072 return getCouldNotCompute();
5073 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005074
5075 return getUDivExpr(Add, Step);
5076}
5077
Chris Lattnerdb25de42005-08-15 23:33:51 +00005078/// HowManyLessThans - Return the number of times a backedge containing the
5079/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005080/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005081ScalarEvolution::BackedgeTakenInfo
5082ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5083 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005084 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005085 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005086
Dan Gohman35738ac2009-05-04 22:30:44 +00005087 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005088 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005089 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005090
Dan Gohman1f96e672009-09-17 18:05:20 +00005091 // Check to see if we have a flag which makes analysis easy.
5092 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5093 AddRec->hasNoUnsignedWrap();
5094
Chris Lattnerdb25de42005-08-15 23:33:51 +00005095 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005096 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005097 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005098
Dan Gohman52fddd32010-01-26 04:40:18 +00005099 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005100 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005101 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005102 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005103 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005104 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005105 // value and past the maximum value for its type in a single step.
5106 // Note that it's not sufficient to check NoWrap here, because even
5107 // though the value after a wrap is undefined, it's not undefined
5108 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005109 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005110 // iterate at least until the iteration where the wrapping occurs.
5111 const SCEV *One = getIntegerSCEV(1, Step->getType());
5112 if (isSigned) {
5113 APInt Max = APInt::getSignedMaxValue(BitWidth);
5114 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5115 .slt(getSignedRange(RHS).getSignedMax()))
5116 return getCouldNotCompute();
5117 } else {
5118 APInt Max = APInt::getMaxValue(BitWidth);
5119 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5120 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5121 return getCouldNotCompute();
5122 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005123 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005124 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005125 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005126
Dan Gohmana1af7572009-04-30 20:47:05 +00005127 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5128 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5129 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005130 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005131
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005132 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005133 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005134
Dan Gohmana1af7572009-04-30 20:47:05 +00005135 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005136 const SCEV *MinStart = getConstant(isSigned ?
5137 getSignedRange(Start).getSignedMin() :
5138 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005139
Dan Gohmana1af7572009-04-30 20:47:05 +00005140 // If we know that the condition is true in order to enter the loop,
5141 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005142 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5143 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005144 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005145 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005146 isSigned ? ICmpInst::ICMP_SLT :
5147 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005148 getMinusSCEV(Start, Step), RHS))
5149 End = isSigned ? getSMaxExpr(RHS, Start)
5150 : getUMaxExpr(RHS, Start);
5151
5152 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005153 const SCEV *MaxEnd = getConstant(isSigned ?
5154 getSignedRange(End).getSignedMax() :
5155 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005156
Dan Gohman52fddd32010-01-26 04:40:18 +00005157 // If MaxEnd is within a step of the maximum integer value in its type,
5158 // adjust it down to the minimum value which would produce the same effect.
5159 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5160 // compute the correct value.
5161 const SCEV *StepMinusOne = getMinusSCEV(Step,
5162 getIntegerSCEV(1, Step->getType()));
5163 MaxEnd = isSigned ?
5164 getSMinExpr(MaxEnd,
5165 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5166 StepMinusOne)) :
5167 getUMinExpr(MaxEnd,
5168 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5169 StepMinusOne));
5170
Dan Gohmana1af7572009-04-30 20:47:05 +00005171 // Finally, we subtract these two values and divide, rounding up, to get
5172 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005173 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005174
5175 // The maximum backedge count is similar, except using the minimum start
5176 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005177 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005178
5179 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005180 }
5181
Dan Gohman1c343752009-06-27 21:21:31 +00005182 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005183}
5184
Chris Lattner53e677a2004-04-02 20:23:17 +00005185/// getNumIterationsInRange - Return the number of iterations of this loop that
5186/// produce values in the specified constant range. Another way of looking at
5187/// this is that it returns the first iteration number where the value is not in
5188/// the condition, thus computing the exit count. If the iteration count can't
5189/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005190const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005191 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005192 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005193 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005194
5195 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005196 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005197 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005198 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005199 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005200 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005201 if (const SCEVAddRecExpr *ShiftedAddRec =
5202 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005203 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005204 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005205 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005206 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005207 }
5208
5209 // The only time we can solve this is when we have all constant indices.
5210 // Otherwise, we cannot determine the overflow conditions.
5211 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5212 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005213 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005214
5215
5216 // Okay at this point we know that all elements of the chrec are constants and
5217 // that the start element is zero.
5218
5219 // First check to see if the range contains zero. If not, the first
5220 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005221 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005222 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005223 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005224
Chris Lattner53e677a2004-04-02 20:23:17 +00005225 if (isAffine()) {
5226 // If this is an affine expression then we have this situation:
5227 // Solve {0,+,A} in Range === Ax in Range
5228
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005229 // We know that zero is in the range. If A is positive then we know that
5230 // the upper value of the range must be the first possible exit value.
5231 // If A is negative then the lower of the range is the last possible loop
5232 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005233 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005234 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5235 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005236
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005237 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005238 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005239 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005240
5241 // Evaluate at the exit value. If we really did fall out of the valid
5242 // range, then we computed our trip count, otherwise wrap around or other
5243 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005244 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005245 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005246 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005247
5248 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005249 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005250 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005251 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005252 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005253 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005254 } else if (isQuadratic()) {
5255 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5256 // quadratic equation to solve it. To do this, we must frame our problem in
5257 // terms of figuring out when zero is crossed, instead of when
5258 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005259 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005260 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005261 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005262
5263 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005264 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005265 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005266 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5267 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005268 if (R1) {
5269 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005270 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005271 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005272 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005273 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005274 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005275
Chris Lattner53e677a2004-04-02 20:23:17 +00005276 // Make sure the root is not off by one. The returned iteration should
5277 // not be in the range, but the previous one should be. When solving
5278 // for "X*X < 5", for example, we should not return a root of 2.
5279 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005280 R1->getValue(),
5281 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005282 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005283 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005284 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005285 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005286
Dan Gohman246b2562007-10-22 18:31:58 +00005287 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005288 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005289 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005290 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005291 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005292
Chris Lattner53e677a2004-04-02 20:23:17 +00005293 // If R1 was not in the range, then it is a good return value. Make
5294 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005295 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005296 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005297 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005298 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005299 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005300 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005301 }
5302 }
5303 }
5304
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005305 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005306}
5307
5308
5309
5310//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005311// SCEVCallbackVH Class Implementation
5312//===----------------------------------------------------------------------===//
5313
Dan Gohman1959b752009-05-19 19:22:47 +00005314void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005315 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005316 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5317 SE->ConstantEvolutionLoopExitValue.erase(PN);
5318 SE->Scalars.erase(getValPtr());
5319 // this now dangles!
5320}
5321
Dan Gohman1959b752009-05-19 19:22:47 +00005322void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005323 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005324
5325 // Forget all the expressions associated with users of the old value,
5326 // so that future queries will recompute the expressions using the new
5327 // value.
5328 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005329 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005330 Value *Old = getValPtr();
5331 bool DeleteOld = false;
5332 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5333 UI != UE; ++UI)
5334 Worklist.push_back(*UI);
5335 while (!Worklist.empty()) {
5336 User *U = Worklist.pop_back_val();
5337 // Deleting the Old value will cause this to dangle. Postpone
5338 // that until everything else is done.
5339 if (U == Old) {
5340 DeleteOld = true;
5341 continue;
5342 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005343 if (!Visited.insert(U))
5344 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005345 if (PHINode *PN = dyn_cast<PHINode>(U))
5346 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005347 SE->Scalars.erase(U);
5348 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5349 UI != UE; ++UI)
5350 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005351 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005352 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005353 if (DeleteOld) {
5354 if (PHINode *PN = dyn_cast<PHINode>(Old))
5355 SE->ConstantEvolutionLoopExitValue.erase(PN);
5356 SE->Scalars.erase(Old);
5357 // this now dangles!
5358 }
5359 // this may dangle!
5360}
5361
Dan Gohman1959b752009-05-19 19:22:47 +00005362ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005363 : CallbackVH(V), SE(se) {}
5364
5365//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005366// ScalarEvolution Class Implementation
5367//===----------------------------------------------------------------------===//
5368
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005369ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005370 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005371}
5372
Chris Lattner53e677a2004-04-02 20:23:17 +00005373bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005374 this->F = &F;
5375 LI = &getAnalysis<LoopInfo>();
5376 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005377 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005378 return false;
5379}
5380
5381void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005382 Scalars.clear();
5383 BackedgeTakenCounts.clear();
5384 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005385 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005386 UniqueSCEVs.clear();
5387 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005388}
5389
5390void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5391 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005392 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005393 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005394}
5395
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005396bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005397 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005398}
5399
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005400static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005401 const Loop *L) {
5402 // Print all inner loops first
5403 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5404 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005405
Dan Gohman30733292010-01-09 18:17:45 +00005406 OS << "Loop ";
5407 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5408 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005409
Dan Gohman5d984912009-12-18 01:14:11 +00005410 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005411 L->getExitBlocks(ExitBlocks);
5412 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005413 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005414
Dan Gohman46bdfb02009-02-24 18:55:53 +00005415 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5416 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005417 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005418 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005419 }
5420
Dan Gohman30733292010-01-09 18:17:45 +00005421 OS << "\n"
5422 "Loop ";
5423 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5424 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005425
5426 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5427 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5428 } else {
5429 OS << "Unpredictable max backedge-taken count. ";
5430 }
5431
5432 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005433}
5434
Dan Gohman5d984912009-12-18 01:14:11 +00005435void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005436 // ScalarEvolution's implementaiton of the print method is to print
5437 // out SCEV values of all instructions that are interesting. Doing
5438 // this potentially causes it to create new SCEV objects though,
5439 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005440 // observable from outside the class though, so casting away the
5441 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005442 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005443
Dan Gohman30733292010-01-09 18:17:45 +00005444 OS << "Classifying expressions for: ";
5445 WriteAsOperand(OS, F, /*PrintType=*/false);
5446 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005447 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005448 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005449 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005450 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005451 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005452 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005453
Dan Gohman0c689c52009-06-19 17:49:54 +00005454 const Loop *L = LI->getLoopFor((*I).getParent());
5455
Dan Gohman0bba49c2009-07-07 17:06:11 +00005456 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005457 if (AtUse != SV) {
5458 OS << " --> ";
5459 AtUse->print(OS);
5460 }
5461
5462 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005463 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005464 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005465 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005466 OS << "<<Unknown>>";
5467 } else {
5468 OS << *ExitValue;
5469 }
5470 }
5471
Chris Lattner53e677a2004-04-02 20:23:17 +00005472 OS << "\n";
5473 }
5474
Dan Gohman30733292010-01-09 18:17:45 +00005475 OS << "Determining loop execution counts for: ";
5476 WriteAsOperand(OS, F, /*PrintType=*/false);
5477 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005478 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5479 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005480}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005481