blob: b734d00f7fe05587d601154ceb97c78fb384b9e3 [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"
Duncan Sandsa0c52442010-11-17 04:18:45 +000072#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000074#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000076#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000077#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000079#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000080#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000081#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000082#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000083#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000084#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000085#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000086#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000087#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000088#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000089using namespace llvm;
90
Chris Lattner3b27d682006-12-19 22:30:33 +000091STATISTIC(NumArrayLenItCounts,
92 "Number of trip counts computed with array length");
93STATISTIC(NumTripCountsComputed,
94 "Number of loops with predictable loop counts");
95STATISTIC(NumTripCountsNotComputed,
96 "Number of loops without predictable loop counts");
97STATISTIC(NumBruteForceTripCountsComputed,
98 "Number of loops with trip counts computed by force");
99
Dan Gohman844731a2008-05-13 00:00:25 +0000100static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000101MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
102 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000103 "symbolically execute a constant "
104 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000105 cl::init(100));
106
Owen Anderson2ab36d32010-10-12 19:48:12 +0000107INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
108 "Scalar Evolution Analysis", false, true)
109INITIALIZE_PASS_DEPENDENCY(LoopInfo)
110INITIALIZE_PASS_DEPENDENCY(DominatorTree)
111INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
Owen Andersonce665bd2010-10-07 22:25:06 +0000112 "Scalar Evolution Analysis", false, true)
Devang Patel19974732007-05-03 01:11:54 +0000113char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000114
115//===----------------------------------------------------------------------===//
116// SCEV class definitions
117//===----------------------------------------------------------------------===//
118
119//===----------------------------------------------------------------------===//
120// Implementation of the SCEV class.
121//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000122
Chris Lattner53e677a2004-04-02 20:23:17 +0000123void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000124 print(dbgs());
125 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000126}
127
Dan Gohman4ce32db2010-11-17 22:27:42 +0000128void SCEV::print(raw_ostream &OS) const {
129 switch (getSCEVType()) {
130 case scConstant:
131 WriteAsOperand(OS, cast<SCEVConstant>(this)->getValue(), false);
132 return;
133 case scTruncate: {
134 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
135 const SCEV *Op = Trunc->getOperand();
136 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
137 << *Trunc->getType() << ")";
138 return;
139 }
140 case scZeroExtend: {
141 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
142 const SCEV *Op = ZExt->getOperand();
143 OS << "(zext " << *Op->getType() << " " << *Op << " to "
144 << *ZExt->getType() << ")";
145 return;
146 }
147 case scSignExtend: {
148 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
149 const SCEV *Op = SExt->getOperand();
150 OS << "(sext " << *Op->getType() << " " << *Op << " to "
151 << *SExt->getType() << ")";
152 return;
153 }
154 case scAddRecExpr: {
155 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
156 OS << "{" << *AR->getOperand(0);
157 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
158 OS << ",+," << *AR->getOperand(i);
159 OS << "}<";
160 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
161 OS << ">";
162 return;
163 }
164 case scAddExpr:
165 case scMulExpr:
166 case scUMaxExpr:
167 case scSMaxExpr: {
168 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
169 const char *OpStr;
170 switch (NAry->getSCEVType()) {
171 case scAddExpr: OpStr = " + "; break;
172 case scMulExpr: OpStr = " * "; break;
173 case scUMaxExpr: OpStr = " umax "; break;
174 case scSMaxExpr: OpStr = " smax "; break;
175 }
176 OS << "(";
177 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
178 I != E; ++I) {
179 OS << **I;
180 if (llvm::next(I) != E)
181 OS << OpStr;
182 }
183 OS << ")";
184 return;
185 }
186 case scUDivExpr: {
187 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
188 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
189 return;
190 }
191 case scUnknown: {
192 const SCEVUnknown *U = cast<SCEVUnknown>(this);
193 const Type *AllocTy;
194 if (U->isSizeOf(AllocTy)) {
195 OS << "sizeof(" << *AllocTy << ")";
196 return;
197 }
198 if (U->isAlignOf(AllocTy)) {
199 OS << "alignof(" << *AllocTy << ")";
200 return;
201 }
202
203 const Type *CTy;
204 Constant *FieldNo;
205 if (U->isOffsetOf(CTy, FieldNo)) {
206 OS << "offsetof(" << *CTy << ", ";
207 WriteAsOperand(OS, FieldNo, false);
208 OS << ")";
209 return;
210 }
211
212 // Otherwise just print it normally.
213 WriteAsOperand(OS, U->getValue(), false);
214 return;
215 }
216 case scCouldNotCompute:
217 OS << "***COULDNOTCOMPUTE***";
218 return;
219 default: break;
220 }
221 llvm_unreachable("Unknown SCEV kind!");
222}
223
224const Type *SCEV::getType() const {
225 switch (getSCEVType()) {
226 case scConstant:
227 return cast<SCEVConstant>(this)->getType();
228 case scTruncate:
229 case scZeroExtend:
230 case scSignExtend:
231 return cast<SCEVCastExpr>(this)->getType();
232 case scAddRecExpr:
233 case scMulExpr:
234 case scUMaxExpr:
235 case scSMaxExpr:
236 return cast<SCEVNAryExpr>(this)->getType();
237 case scAddExpr:
238 return cast<SCEVAddExpr>(this)->getType();
239 case scUDivExpr:
240 return cast<SCEVUDivExpr>(this)->getType();
241 case scUnknown:
242 return cast<SCEVUnknown>(this)->getType();
243 case scCouldNotCompute:
244 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
245 return 0;
246 default: break;
247 }
248 llvm_unreachable("Unknown SCEV kind!");
249 return 0;
250}
251
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000252bool SCEV::isZero() const {
253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
254 return SC->getValue()->isZero();
255 return false;
256}
257
Dan Gohman70a1fe72009-05-18 15:22:39 +0000258bool SCEV::isOne() const {
259 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
260 return SC->getValue()->isOne();
261 return false;
262}
Chris Lattner53e677a2004-04-02 20:23:17 +0000263
Dan Gohman4d289bf2009-06-24 00:30:26 +0000264bool SCEV::isAllOnesValue() const {
265 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
266 return SC->getValue()->isAllOnesValue();
267 return false;
268}
269
Owen Anderson753ad612009-06-22 21:57:23 +0000270SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000271 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000272
Chris Lattner53e677a2004-04-02 20:23:17 +0000273bool SCEVCouldNotCompute::classof(const SCEV *S) {
274 return S->getSCEVType() == scCouldNotCompute;
275}
276
Dan Gohman0bba49c2009-07-07 17:06:11 +0000277const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000278 FoldingSetNodeID ID;
279 ID.AddInteger(scConstant);
280 ID.AddPointer(V);
281 void *IP = 0;
282 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000283 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000284 UniqueSCEVs.InsertNode(S, IP);
285 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000286}
Chris Lattner53e677a2004-04-02 20:23:17 +0000287
Dan Gohman0bba49c2009-07-07 17:06:11 +0000288const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000289 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000290}
291
Dan Gohman0bba49c2009-07-07 17:06:11 +0000292const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000293ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000294 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
295 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000296}
297
Dan Gohman3bf63762010-06-18 19:54:20 +0000298SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000299 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000300 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000301
Dan Gohman3bf63762010-06-18 19:54:20 +0000302SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000303 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000304 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000305 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
306 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000307 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
Chris Lattner53e677a2004-04-02 20:23:17 +0000309
Dan Gohman3bf63762010-06-18 19:54:20 +0000310SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000311 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000312 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000313 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
314 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316}
317
Dan Gohman3bf63762010-06-18 19:54:20 +0000318SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000319 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000320 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000321 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
322 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000323 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000324}
325
Dan Gohmanab37f502010-08-02 23:49:30 +0000326void SCEVUnknown::deleted() {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000327 // Clear this SCEVUnknown from various maps.
Dan Gohmanab37f502010-08-02 23:49:30 +0000328 SE->ValuesAtScopes.erase(this);
Dan Gohman714b5292010-11-17 23:21:44 +0000329 SE->LoopDispositions.erase(this);
Dan Gohman6678e7b2010-11-17 02:44:44 +0000330 SE->UnsignedRanges.erase(this);
331 SE->SignedRanges.erase(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000332
333 // Remove this SCEVUnknown from the uniquing map.
334 SE->UniqueSCEVs.RemoveNode(this);
335
336 // Release the value.
337 setValPtr(0);
338}
339
340void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000341 // Clear this SCEVUnknown from various maps.
Dan Gohmanab37f502010-08-02 23:49:30 +0000342 SE->ValuesAtScopes.erase(this);
Dan Gohman714b5292010-11-17 23:21:44 +0000343 SE->LoopDispositions.erase(this);
Dan Gohman6678e7b2010-11-17 02:44:44 +0000344 SE->UnsignedRanges.erase(this);
345 SE->SignedRanges.erase(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000346
347 // Remove this SCEVUnknown from the uniquing map.
348 SE->UniqueSCEVs.RemoveNode(this);
349
350 // Update this SCEVUnknown to point to the new value. This is needed
351 // because there may still be outstanding SCEVs which still point to
352 // this SCEVUnknown.
353 setValPtr(New);
354}
355
Dan Gohman0f5efe52010-01-28 02:15:55 +0000356bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000357 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000358 if (VCE->getOpcode() == Instruction::PtrToInt)
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000360 if (CE->getOpcode() == Instruction::GetElementPtr &&
361 CE->getOperand(0)->isNullValue() &&
362 CE->getNumOperands() == 2)
363 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
364 if (CI->isOne()) {
365 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
366 ->getElementType();
367 return true;
368 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000369
370 return false;
371}
372
373bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000374 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000375 if (VCE->getOpcode() == Instruction::PtrToInt)
376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000377 if (CE->getOpcode() == Instruction::GetElementPtr &&
378 CE->getOperand(0)->isNullValue()) {
379 const Type *Ty =
380 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
381 if (const StructType *STy = dyn_cast<StructType>(Ty))
382 if (!STy->isPacked() &&
383 CE->getNumOperands() == 3 &&
384 CE->getOperand(1)->isNullValue()) {
385 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
386 if (CI->isOne() &&
387 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000388 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000389 AllocTy = STy->getElementType(1);
390 return true;
391 }
392 }
393 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000394
395 return false;
396}
397
Dan Gohman4f8eea82010-02-01 18:27:38 +0000398bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000399 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000400 if (VCE->getOpcode() == Instruction::PtrToInt)
401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
402 if (CE->getOpcode() == Instruction::GetElementPtr &&
403 CE->getNumOperands() == 3 &&
404 CE->getOperand(0)->isNullValue() &&
405 CE->getOperand(1)->isNullValue()) {
406 const Type *Ty =
407 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
408 // Ignore vector types here so that ScalarEvolutionExpander doesn't
409 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000410 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000411 CTy = Ty;
412 FieldNo = CE->getOperand(2);
413 return true;
414 }
415 }
416
417 return false;
418}
419
Chris Lattner8d741b82004-06-20 06:23:15 +0000420//===----------------------------------------------------------------------===//
421// SCEV Utilities
422//===----------------------------------------------------------------------===//
423
424namespace {
425 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
426 /// than the complexity of the RHS. This comparator is used to canonicalize
427 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000428 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000429 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000430 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000431 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000432
Dan Gohman67ef74e2010-08-27 15:26:01 +0000433 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000434 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman67ef74e2010-08-27 15:26:01 +0000435 return compare(LHS, RHS) < 0;
436 }
437
438 // Return negative, zero, or positive, if LHS is less than, equal to, or
439 // greater than RHS, respectively. A three-way result allows recursive
440 // comparisons to be more efficient.
441 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000442 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
443 if (LHS == RHS)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000444 return 0;
Dan Gohman42214892009-08-31 21:15:23 +0000445
Dan Gohman72861302009-05-07 14:39:04 +0000446 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000447 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
448 if (LType != RType)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000449 return (int)LType - (int)RType;
Dan Gohman72861302009-05-07 14:39:04 +0000450
Dan Gohman3bf63762010-06-18 19:54:20 +0000451 // Aside from the getSCEVType() ordering, the particular ordering
452 // isn't very important except that it's beneficial to be consistent,
453 // so that (a + b) and (b + a) don't end up as different expressions.
Dan Gohman67ef74e2010-08-27 15:26:01 +0000454 switch (LType) {
455 case scUnknown: {
456 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000457 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000458
459 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
460 // not as complete as it could be.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000461 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000462
463 // Order pointer values after integer values. This helps SCEVExpander
464 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000465 bool LIsPointer = LV->getType()->isPointerTy(),
466 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000467 if (LIsPointer != RIsPointer)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000468 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000469
470 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000471 unsigned LID = LV->getValueID(),
472 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000473 if (LID != RID)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000474 return (int)LID - (int)RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000475
476 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000477 if (const Argument *LA = dyn_cast<Argument>(LV)) {
478 const Argument *RA = cast<Argument>(RV);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000479 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
480 return (int)LArgNo - (int)RArgNo;
Dan Gohman3bf63762010-06-18 19:54:20 +0000481 }
482
Dan Gohman67ef74e2010-08-27 15:26:01 +0000483 // For instructions, compare their loop depth, and their operand
484 // count. This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000485 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
486 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000487
488 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000489 const BasicBlock *LParent = LInst->getParent(),
490 *RParent = RInst->getParent();
491 if (LParent != RParent) {
492 unsigned LDepth = LI->getLoopDepth(LParent),
493 RDepth = LI->getLoopDepth(RParent);
494 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000495 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000496 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000497
498 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000499 unsigned LNumOps = LInst->getNumOperands(),
500 RNumOps = RInst->getNumOperands();
Dan Gohman67ef74e2010-08-27 15:26:01 +0000501 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000502 }
503
Dan Gohman67ef74e2010-08-27 15:26:01 +0000504 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000505 }
506
Dan Gohman67ef74e2010-08-27 15:26:01 +0000507 case scConstant: {
508 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000509 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000510
511 // Compare constant values.
Dan Gohmane28d7922010-08-16 16:25:35 +0000512 const APInt &LA = LC->getValue()->getValue();
513 const APInt &RA = RC->getValue()->getValue();
514 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman304a7a62010-07-23 21:20:52 +0000515 if (LBitWidth != RBitWidth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000516 return (int)LBitWidth - (int)RBitWidth;
517 return LA.ult(RA) ? -1 : 1;
Dan Gohman3bf63762010-06-18 19:54:20 +0000518 }
519
Dan Gohman67ef74e2010-08-27 15:26:01 +0000520 case scAddRecExpr: {
521 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000522 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000523
524 // Compare addrec loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000525 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
526 if (LLoop != RLoop) {
527 unsigned LDepth = LLoop->getLoopDepth(),
528 RDepth = RLoop->getLoopDepth();
529 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000530 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000531 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000532
533 // Addrec complexity grows with operand count.
534 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
535 if (LNumOps != RNumOps)
536 return (int)LNumOps - (int)RNumOps;
537
538 // Lexicographically compare.
539 for (unsigned i = 0; i != LNumOps; ++i) {
540 long X = compare(LA->getOperand(i), RA->getOperand(i));
541 if (X != 0)
542 return X;
543 }
544
545 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000546 }
547
Dan Gohman67ef74e2010-08-27 15:26:01 +0000548 case scAddExpr:
549 case scMulExpr:
550 case scSMaxExpr:
551 case scUMaxExpr: {
552 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000553 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000554
555 // Lexicographically compare n-ary expressions.
Dan Gohman304a7a62010-07-23 21:20:52 +0000556 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
557 for (unsigned i = 0; i != LNumOps; ++i) {
558 if (i >= RNumOps)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000559 return 1;
560 long X = compare(LC->getOperand(i), RC->getOperand(i));
561 if (X != 0)
562 return X;
Dan Gohman3bf63762010-06-18 19:54:20 +0000563 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000564 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000565 }
566
Dan Gohman67ef74e2010-08-27 15:26:01 +0000567 case scUDivExpr: {
568 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000569 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000570
571 // Lexicographically compare udiv expressions.
572 long X = compare(LC->getLHS(), RC->getLHS());
573 if (X != 0)
574 return X;
575 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman3bf63762010-06-18 19:54:20 +0000576 }
577
Dan Gohman67ef74e2010-08-27 15:26:01 +0000578 case scTruncate:
579 case scZeroExtend:
580 case scSignExtend: {
581 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000582 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000583
584 // Compare cast expressions by operand.
585 return compare(LC->getOperand(), RC->getOperand());
586 }
587
588 default:
589 break;
Dan Gohman3bf63762010-06-18 19:54:20 +0000590 }
591
592 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman67ef74e2010-08-27 15:26:01 +0000593 return 0;
Chris Lattner8d741b82004-06-20 06:23:15 +0000594 }
595 };
596}
597
598/// GroupByComplexity - Given a list of SCEV objects, order them by their
599/// complexity, and group objects of the same complexity together by value.
600/// When this routine is finished, we know that any duplicates in the vector are
601/// consecutive and that complexity is monotonically increasing.
602///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000603/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000604/// results from this routine. In other words, we don't want the results of
605/// this to depend on where the addresses of various SCEV objects happened to
606/// land in memory.
607///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000608static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000609 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000610 if (Ops.size() < 2) return; // Noop
611 if (Ops.size() == 2) {
612 // This is the common case, which also happens to be trivially simple.
613 // Special case it.
Dan Gohmanc6a8e992010-08-29 15:07:13 +0000614 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
615 if (SCEVComplexityCompare(LI)(RHS, LHS))
616 std::swap(LHS, RHS);
Chris Lattner8d741b82004-06-20 06:23:15 +0000617 return;
618 }
619
Dan Gohman3bf63762010-06-18 19:54:20 +0000620 // Do the rough sort by complexity.
621 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
622
623 // Now that we are sorted by complexity, group elements of the same
624 // complexity. Note that this is, at worst, N^2, but the vector is likely to
625 // be extremely short in practice. Note that we take this approach because we
626 // do not want to depend on the addresses of the objects we are grouping.
627 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
628 const SCEV *S = Ops[i];
629 unsigned Complexity = S->getSCEVType();
630
631 // If there are any objects of the same complexity and same value as this
632 // one, group them.
633 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
634 if (Ops[j] == S) { // Found a duplicate.
635 // Move it to immediately after i'th element.
636 std::swap(Ops[i+1], Ops[j]);
637 ++i; // no need to rescan it.
638 if (i == e-2) return; // Done!
639 }
640 }
641 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000642}
643
Chris Lattner53e677a2004-04-02 20:23:17 +0000644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645
646//===----------------------------------------------------------------------===//
647// Simple SCEV method implementations
648//===----------------------------------------------------------------------===//
649
Eli Friedmanb42a6262008-08-04 23:49:06 +0000650/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000651/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000652static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000653 ScalarEvolution &SE,
654 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000655 // Handle the simplest case efficiently.
656 if (K == 1)
657 return SE.getTruncateOrZeroExtend(It, ResultTy);
658
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000659 // We are using the following formula for BC(It, K):
660 //
661 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
662 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000663 // Suppose, W is the bitwidth of the return value. We must be prepared for
664 // overflow. Hence, we must assure that the result of our computation is
665 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
666 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000667 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000668 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000669 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000670 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
671 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000672 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000673 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000675 // This formula is trivially equivalent to the previous formula. However,
676 // this formula can be implemented much more efficiently. The trick is that
677 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
678 // arithmetic. To do exact division in modular arithmetic, all we have
679 // to do is multiply by the inverse. Therefore, this step can be done at
680 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000681 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000682 // The next issue is how to safely do the division by 2^T. The way this
683 // is done is by doing the multiplication step at a width of at least W + T
684 // bits. This way, the bottom W+T bits of the product are accurate. Then,
685 // when we perform the division by 2^T (which is equivalent to a right shift
686 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
687 // truncated out after the division by 2^T.
688 //
689 // In comparison to just directly using the first formula, this technique
690 // is much more efficient; using the first formula requires W * K bits,
691 // but this formula less than W + K bits. Also, the first formula requires
692 // a division step, whereas this formula only requires multiplies and shifts.
693 //
694 // It doesn't matter whether the subtraction step is done in the calculation
695 // width or the input iteration count's width; if the subtraction overflows,
696 // the result must be zero anyway. We prefer here to do it in the width of
697 // the induction variable because it helps a lot for certain cases; CodeGen
698 // isn't smart enough to ignore the overflow, which leads to much less
699 // efficient code if the width of the subtraction is wider than the native
700 // register width.
701 //
702 // (It's possible to not widen at all by pulling out factors of 2 before
703 // the multiplication; for example, K=2 can be calculated as
704 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
705 // extra arithmetic, so it's not an obvious win, and it gets
706 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000707
Eli Friedmanb42a6262008-08-04 23:49:06 +0000708 // Protection from insane SCEVs; this bound is conservative,
709 // but it probably doesn't matter.
710 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000711 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000712
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000713 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000714
Eli Friedmanb42a6262008-08-04 23:49:06 +0000715 // Calculate K! / 2^T and T; we divide out the factors of two before
716 // multiplying for calculating K! / 2^T to avoid overflow.
717 // Other overflow doesn't matter because we only care about the bottom
718 // W bits of the result.
719 APInt OddFactorial(W, 1);
720 unsigned T = 1;
721 for (unsigned i = 3; i <= K; ++i) {
722 APInt Mult(W, i);
723 unsigned TwoFactors = Mult.countTrailingZeros();
724 T += TwoFactors;
725 Mult = Mult.lshr(TwoFactors);
726 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000727 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000728
Eli Friedmanb42a6262008-08-04 23:49:06 +0000729 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000730 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000731
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000732 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000733 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
734
735 // Calculate the multiplicative inverse of K! / 2^T;
736 // this multiplication factor will perform the exact division by
737 // K! / 2^T.
738 APInt Mod = APInt::getSignedMinValue(W+1);
739 APInt MultiplyFactor = OddFactorial.zext(W+1);
740 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
741 MultiplyFactor = MultiplyFactor.trunc(W);
742
743 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000744 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
745 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000746 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000747 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000748 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000749 Dividend = SE.getMulExpr(Dividend,
750 SE.getTruncateOrZeroExtend(S, CalculationTy));
751 }
752
753 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000754 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000755
756 // Truncate the result, and divide by K! / 2^T.
757
758 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
759 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000760}
761
Chris Lattner53e677a2004-04-02 20:23:17 +0000762/// evaluateAtIteration - Return the value of this chain of recurrences at
763/// the specified iteration number. We can evaluate this recurrence by
764/// multiplying each element in the chain by the binomial coefficient
765/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
766///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000767/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000768///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000769/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000770///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000771const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000772 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000773 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000775 // The computation is correct in the face of overflow provided that the
776 // multiplication is performed _after_ the evaluation of the binomial
777 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000778 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000779 if (isa<SCEVCouldNotCompute>(Coeff))
780 return Coeff;
781
782 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000783 }
784 return Result;
785}
786
Chris Lattner53e677a2004-04-02 20:23:17 +0000787//===----------------------------------------------------------------------===//
788// SCEV Expression folder implementations
789//===----------------------------------------------------------------------===//
790
Dan Gohman0bba49c2009-07-07 17:06:11 +0000791const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000792 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000793 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000794 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000795 assert(isSCEVable(Ty) &&
796 "This is not a conversion to a SCEVable type!");
797 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000798
Dan Gohmanc050fd92009-07-13 20:50:19 +0000799 FoldingSetNodeID ID;
800 ID.AddInteger(scTruncate);
801 ID.AddPointer(Op);
802 ID.AddPointer(Ty);
803 void *IP = 0;
804 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
805
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000806 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000807 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000808 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000809 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
810 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000811
Dan Gohman20900ca2009-04-22 16:20:48 +0000812 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000813 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000814 return getTruncateExpr(ST->getOperand(), Ty);
815
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000816 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000817 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000818 return getTruncateOrSignExtend(SS->getOperand(), Ty);
819
820 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000821 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000822 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
823
Dan Gohman6864db62009-06-18 16:24:47 +0000824 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000825 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000826 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000827 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000828 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
829 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000830 }
831
Dan Gohmanf53462d2010-07-15 20:02:11 +0000832 // As a special case, fold trunc(undef) to undef. We don't want to
833 // know too much about SCEVUnknowns, but this special case is handy
834 // and harmless.
835 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
836 if (isa<UndefValue>(U->getValue()))
837 return getSCEV(UndefValue::get(Ty));
838
Dan Gohman420ab912010-06-25 18:47:08 +0000839 // The cast wasn't folded; create an explicit cast node. We can reuse
840 // the existing insert position since if we get here, we won't have
841 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000842 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
843 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000844 UniqueSCEVs.InsertNode(S, IP);
845 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000846}
847
Dan Gohman0bba49c2009-07-07 17:06:11 +0000848const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000849 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000850 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000851 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000852 assert(isSCEVable(Ty) &&
853 "This is not a conversion to a SCEVable type!");
854 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000855
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000856 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000857 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
858 return getConstant(
859 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
860 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000861
Dan Gohman20900ca2009-04-22 16:20:48 +0000862 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000863 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000864 return getZeroExtendExpr(SZ->getOperand(), Ty);
865
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000866 // Before doing any expensive analysis, check to see if we've already
867 // computed a SCEV for this Op and Ty.
868 FoldingSetNodeID ID;
869 ID.AddInteger(scZeroExtend);
870 ID.AddPointer(Op);
871 ID.AddPointer(Ty);
872 void *IP = 0;
873 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
874
Dan Gohman01ecca22009-04-27 20:16:15 +0000875 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000876 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000877 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000878 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000879 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000880 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000881 const SCEV *Start = AR->getStart();
882 const SCEV *Step = AR->getStepRecurrence(*this);
883 unsigned BitWidth = getTypeSizeInBits(AR->getType());
884 const Loop *L = AR->getLoop();
885
Dan Gohmaneb490a72009-07-25 01:22:26 +0000886 // If we have special knowledge that this addrec won't overflow,
887 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000888 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000889 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
890 getZeroExtendExpr(Step, Ty),
891 L);
892
Dan Gohman01ecca22009-04-27 20:16:15 +0000893 // Check whether the backedge-taken count is SCEVCouldNotCompute.
894 // Note that this serves two purposes: It filters out loops that are
895 // simply not analyzable, and it covers the case where this code is
896 // being called from within backedge-taken count analysis, such that
897 // attempting to ask for the backedge-taken count would likely result
898 // in infinite recursion. In the later case, the analysis code will
899 // cope with a conservative value, and it will take care to purge
900 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000901 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000902 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000903 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000904 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000905
906 // Check whether the backedge-taken count can be losslessly casted to
907 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000908 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000909 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000910 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000911 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
912 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000913 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000914 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000915 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000916 const SCEV *Add = getAddExpr(Start, ZMul);
917 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000918 getAddExpr(getZeroExtendExpr(Start, WideTy),
919 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
920 getZeroExtendExpr(Step, WideTy)));
921 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000922 // Return the expression with the addrec on the outside.
923 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
924 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000925 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000926
927 // Similar to above, only this time treat the step value as signed.
928 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000929 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000930 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000931 OperandExtendedAdd =
932 getAddExpr(getZeroExtendExpr(Start, WideTy),
933 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
934 getSignExtendExpr(Step, WideTy)));
935 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000936 // Return the expression with the addrec on the outside.
937 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
938 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000939 L);
940 }
941
942 // If the backedge is guarded by a comparison with the pre-inc value
943 // the addrec is safe. Also, if the entry is guarded by a comparison
944 // with the start value and the backedge is guarded by a comparison
945 // with the post-inc value, the addrec is safe.
946 if (isKnownPositive(Step)) {
947 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
948 getUnsignedRange(Step).getUnsignedMax());
949 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000950 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000951 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
952 AR->getPostIncExpr(*this), N)))
953 // Return the expression with the addrec on the outside.
954 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
955 getZeroExtendExpr(Step, Ty),
956 L);
957 } else if (isKnownNegative(Step)) {
958 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
959 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000960 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
961 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000962 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
963 AR->getPostIncExpr(*this), N)))
964 // Return the expression with the addrec on the outside.
965 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
966 getSignExtendExpr(Step, Ty),
967 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000968 }
969 }
970 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000971
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000972 // The cast wasn't folded; create an explicit cast node.
973 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000974 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000975 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
976 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000977 UniqueSCEVs.InsertNode(S, IP);
978 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000979}
980
Dan Gohman0bba49c2009-07-07 17:06:11 +0000981const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000982 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000983 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000984 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000985 assert(isSCEVable(Ty) &&
986 "This is not a conversion to a SCEVable type!");
987 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000988
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000989 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000990 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
991 return getConstant(
992 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
993 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +0000994
Dan Gohman20900ca2009-04-22 16:20:48 +0000995 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000996 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000997 return getSignExtendExpr(SS->getOperand(), Ty);
998
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000999 // Before doing any expensive analysis, check to see if we've already
1000 // computed a SCEV for this Op and Ty.
1001 FoldingSetNodeID ID;
1002 ID.AddInteger(scSignExtend);
1003 ID.AddPointer(Op);
1004 ID.AddPointer(Ty);
1005 void *IP = 0;
1006 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1007
Dan Gohman01ecca22009-04-27 20:16:15 +00001008 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001009 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001010 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001011 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001012 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001013 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001014 const SCEV *Start = AR->getStart();
1015 const SCEV *Step = AR->getStepRecurrence(*this);
1016 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1017 const Loop *L = AR->getLoop();
1018
Dan Gohmaneb490a72009-07-25 01:22:26 +00001019 // If we have special knowledge that this addrec won't overflow,
1020 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001021 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001022 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1023 getSignExtendExpr(Step, Ty),
1024 L);
1025
Dan Gohman01ecca22009-04-27 20:16:15 +00001026 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1027 // Note that this serves two purposes: It filters out loops that are
1028 // simply not analyzable, and it covers the case where this code is
1029 // being called from within backedge-taken count analysis, such that
1030 // attempting to ask for the backedge-taken count would likely result
1031 // in infinite recursion. In the later case, the analysis code will
1032 // cope with a conservative value, and it will take care to purge
1033 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001034 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001035 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001036 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001037 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001038
1039 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001040 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001041 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001042 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001043 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001044 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1045 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001046 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001047 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001048 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001049 const SCEV *Add = getAddExpr(Start, SMul);
1050 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001051 getAddExpr(getSignExtendExpr(Start, WideTy),
1052 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1053 getSignExtendExpr(Step, WideTy)));
1054 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001055 // Return the expression with the addrec on the outside.
1056 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1057 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001058 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001059
1060 // Similar to above, only this time treat the step value as unsigned.
1061 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001062 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001063 Add = getAddExpr(Start, UMul);
1064 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001065 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001066 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1067 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001068 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001069 // Return the expression with the addrec on the outside.
1070 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1071 getZeroExtendExpr(Step, Ty),
1072 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001073 }
1074
1075 // If the backedge is guarded by a comparison with the pre-inc value
1076 // the addrec is safe. Also, if the entry is guarded by a comparison
1077 // with the start value and the backedge is guarded by a comparison
1078 // with the post-inc value, the addrec is safe.
1079 if (isKnownPositive(Step)) {
1080 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1081 getSignedRange(Step).getSignedMax());
1082 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001083 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001084 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1085 AR->getPostIncExpr(*this), N)))
1086 // Return the expression with the addrec on the outside.
1087 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1088 getSignExtendExpr(Step, Ty),
1089 L);
1090 } else if (isKnownNegative(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1092 getSignedRange(Step).getSignedMin());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001094 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
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);
Dan Gohman01ecca22009-04-27 20:16:15 +00001101 }
1102 }
1103 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001104
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001105 // The cast wasn't folded; create an explicit cast node.
1106 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001107 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001108 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1109 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001110 UniqueSCEVs.InsertNode(S, IP);
1111 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001112}
1113
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001114/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1115/// unspecified bits out to the given type.
1116///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001117const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001118 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001119 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1120 "This is not an extending conversion!");
1121 assert(isSCEVable(Ty) &&
1122 "This is not a conversion to a SCEVable type!");
1123 Ty = getEffectiveSCEVType(Ty);
1124
1125 // Sign-extend negative constants.
1126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1127 if (SC->getValue()->getValue().isNegative())
1128 return getSignExtendExpr(Op, Ty);
1129
1130 // Peel off a truncate cast.
1131 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001132 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001133 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1134 return getAnyExtendExpr(NewOp, Ty);
1135 return getTruncateOrNoop(NewOp, Ty);
1136 }
1137
1138 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001139 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001140 if (!isa<SCEVZeroExtendExpr>(ZExt))
1141 return ZExt;
1142
1143 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001144 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001145 if (!isa<SCEVSignExtendExpr>(SExt))
1146 return SExt;
1147
Dan Gohmana10756e2010-01-21 02:09:26 +00001148 // Force the cast to be folded into the operands of an addrec.
1149 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1150 SmallVector<const SCEV *, 4> Ops;
1151 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1152 I != E; ++I)
1153 Ops.push_back(getAnyExtendExpr(*I, Ty));
1154 return getAddRecExpr(Ops, AR->getLoop());
1155 }
1156
Dan Gohmanf53462d2010-07-15 20:02:11 +00001157 // As a special case, fold anyext(undef) to undef. We don't want to
1158 // know too much about SCEVUnknowns, but this special case is handy
1159 // and harmless.
1160 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1161 if (isa<UndefValue>(U->getValue()))
1162 return getSCEV(UndefValue::get(Ty));
1163
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001164 // If the expression is obviously signed, use the sext cast value.
1165 if (isa<SCEVSMaxExpr>(Op))
1166 return SExt;
1167
1168 // Absent any other information, use the zext cast value.
1169 return ZExt;
1170}
1171
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001172/// CollectAddOperandsWithScales - Process the given Ops list, which is
1173/// a list of operands to be added under the given scale, update the given
1174/// map. This is a helper function for getAddRecExpr. As an example of
1175/// what it does, given a sequence of operands that would form an add
1176/// expression like this:
1177///
1178/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1179///
1180/// where A and B are constants, update the map with these values:
1181///
1182/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1183///
1184/// and add 13 + A*B*29 to AccumulatedConstant.
1185/// This will allow getAddRecExpr to produce this:
1186///
1187/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1188///
1189/// This form often exposes folding opportunities that are hidden in
1190/// the original operand list.
1191///
1192/// Return true iff it appears that any interesting folding opportunities
1193/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1194/// the common case where no interesting opportunities are present, and
1195/// is also used as a check to avoid infinite recursion.
1196///
1197static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001198CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1199 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001200 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001201 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001202 const APInt &Scale,
1203 ScalarEvolution &SE) {
1204 bool Interesting = false;
1205
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001206 // Iterate over the add operands. They are sorted, with constants first.
1207 unsigned i = 0;
1208 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1209 ++i;
1210 // Pull a buried constant out to the outside.
1211 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1212 Interesting = true;
1213 AccumulatedConstant += Scale * C->getValue()->getValue();
1214 }
1215
1216 // Next comes everything else. We're especially interested in multiplies
1217 // here, but they're in the middle, so just visit the rest with one loop.
1218 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001219 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1220 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1221 APInt NewScale =
1222 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1223 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1224 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001225 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001226 Interesting |=
1227 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001228 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001229 NewScale, SE);
1230 } else {
1231 // A multiplication of a constant with some other value. Update
1232 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001233 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1234 const SCEV *Key = SE.getMulExpr(MulOps);
1235 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001236 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001237 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001238 NewOps.push_back(Pair.first->first);
1239 } else {
1240 Pair.first->second += NewScale;
1241 // The map already had an entry for this value, which may indicate
1242 // a folding opportunity.
1243 Interesting = true;
1244 }
1245 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001246 } else {
1247 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001248 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001249 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001250 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001251 NewOps.push_back(Pair.first->first);
1252 } else {
1253 Pair.first->second += Scale;
1254 // The map already had an entry for this value, which may indicate
1255 // a folding opportunity.
1256 Interesting = true;
1257 }
1258 }
1259 }
1260
1261 return Interesting;
1262}
1263
1264namespace {
1265 struct APIntCompare {
1266 bool operator()(const APInt &LHS, const APInt &RHS) const {
1267 return LHS.ult(RHS);
1268 }
1269 };
1270}
1271
Dan Gohman6c0866c2009-05-24 23:45:28 +00001272/// getAddExpr - Get a canonical add expression, or something simpler if
1273/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001274const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1275 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001276 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001277 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001278#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001279 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001280 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001281 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001282 "SCEVAddExpr operand types don't match!");
1283#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001284
Dan Gohmana10756e2010-01-21 02:09:26 +00001285 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1286 if (!HasNUW && HasNSW) {
1287 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001288 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1289 E = Ops.end(); I != E; ++I)
1290 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001291 All = false;
1292 break;
1293 }
1294 if (All) HasNUW = true;
1295 }
1296
Chris Lattner53e677a2004-04-02 20:23:17 +00001297 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001298 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001299
1300 // If there are any constants, fold them together.
1301 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001302 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001304 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001305 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001306 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001307 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1308 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001309 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001310 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001311 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001312 }
1313
1314 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001315 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001316 Ops.erase(Ops.begin());
1317 --Idx;
1318 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001319
Dan Gohmanbca091d2010-04-12 23:08:18 +00001320 if (Ops.size() == 1) return Ops[0];
1321 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001322
Dan Gohman68ff7762010-08-27 21:39:59 +00001323 // Okay, check to see if the same value occurs in the operand list more than
1324 // once. If so, merge them together into an multiply expression. Since we
1325 // sorted the list, these values are required to be adjacent.
Chris Lattner53e677a2004-04-02 20:23:17 +00001326 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001327 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001328 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001330 // Scan ahead to count how many equal operands there are.
1331 unsigned Count = 2;
1332 while (i+Count != e && Ops[i+Count] == Ops[i])
1333 ++Count;
1334 // Merge the values into a multiply.
1335 const SCEV *Scale = getConstant(Ty, Count);
1336 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1337 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001339 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001340 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001341 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001342 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001343 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001344 if (FoundMatch)
1345 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001346
Dan Gohman728c7f32009-05-08 21:03:19 +00001347 // Check for truncates. If all the operands are truncated from the same
1348 // type, see if factoring out the truncate would permit the result to be
1349 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1350 // if the contents of the resulting outer trunc fold to something simple.
1351 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1352 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1353 const Type *DstType = Trunc->getType();
1354 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001355 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001356 bool Ok = true;
1357 // Check all the operands to see if they can be represented in the
1358 // source type of the truncate.
1359 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1360 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1361 if (T->getOperand()->getType() != SrcType) {
1362 Ok = false;
1363 break;
1364 }
1365 LargeOps.push_back(T->getOperand());
1366 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001367 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001368 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001369 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001370 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1371 if (const SCEVTruncateExpr *T =
1372 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1373 if (T->getOperand()->getType() != SrcType) {
1374 Ok = false;
1375 break;
1376 }
1377 LargeMulOps.push_back(T->getOperand());
1378 } else if (const SCEVConstant *C =
1379 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001380 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001381 } else {
1382 Ok = false;
1383 break;
1384 }
1385 }
1386 if (Ok)
1387 LargeOps.push_back(getMulExpr(LargeMulOps));
1388 } else {
1389 Ok = false;
1390 break;
1391 }
1392 }
1393 if (Ok) {
1394 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001395 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001396 // If it folds to something simple, use it. Otherwise, don't.
1397 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1398 return getTruncateExpr(Fold, DstType);
1399 }
1400 }
1401
1402 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1404 ++Idx;
1405
1406 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001407 if (Idx < Ops.size()) {
1408 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001409 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 // If we have an add, expand the add operands onto the end of the operands
1411 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001412 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001413 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001414 DeletedAdd = true;
1415 }
1416
1417 // If we deleted at least one add, we added operands to the end of the list,
1418 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001419 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001420 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001421 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001422 }
1423
1424 // Skip over the add expression until we get to a multiply.
1425 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1426 ++Idx;
1427
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001428 // Check to see if there are any folding opportunities present with
1429 // operands multiplied by constant values.
1430 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1431 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001432 DenseMap<const SCEV *, APInt> M;
1433 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001434 APInt AccumulatedConstant(BitWidth, 0);
1435 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001436 Ops.data(), Ops.size(),
1437 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001438 // Some interesting folding opportunity is present, so its worthwhile to
1439 // re-generate the operands list. Group the operands by constant scale,
1440 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001441 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001442 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001443 E = NewOps.end(); I != E; ++I)
1444 MulOpLists[M.find(*I)->second].push_back(*I);
1445 // Re-generate the operands list.
1446 Ops.clear();
1447 if (AccumulatedConstant != 0)
1448 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001449 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1450 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001451 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001452 Ops.push_back(getMulExpr(getConstant(I->first),
1453 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001454 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001455 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001456 if (Ops.size() == 1)
1457 return Ops[0];
1458 return getAddExpr(Ops);
1459 }
1460 }
1461
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 // If we are adding something to a multiply expression, make sure the
1463 // something is not already an operand of the multiply. If so, merge it into
1464 // the multiply.
1465 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001466 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001468 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001469 if (isa<SCEVConstant>(MulOpSCEV))
1470 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001472 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001473 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001474 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001475 if (Mul->getNumOperands() != 2) {
1476 // If the multiply has more than two operands, we must get the
1477 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001478 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1479 Mul->op_begin()+MulOp);
1480 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001481 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001482 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001483 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001484 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001485 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 if (Ops.size() == 2) return OuterMul;
1487 if (AddOp < Idx) {
1488 Ops.erase(Ops.begin()+AddOp);
1489 Ops.erase(Ops.begin()+Idx-1);
1490 } else {
1491 Ops.erase(Ops.begin()+Idx);
1492 Ops.erase(Ops.begin()+AddOp-1);
1493 }
1494 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001495 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001497
Chris Lattner53e677a2004-04-02 20:23:17 +00001498 // Check this multiply against other multiplies being added together.
1499 for (unsigned OtherMulIdx = Idx+1;
1500 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1501 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001502 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 // If MulOp occurs in OtherMul, we can fold the two multiplies
1504 // together.
1505 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1506 OMulOp != e; ++OMulOp)
1507 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1508 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001509 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001511 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001512 Mul->op_begin()+MulOp);
1513 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001514 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001516 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001517 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001518 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001519 OtherMul->op_begin()+OMulOp);
1520 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001521 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001522 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001523 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1524 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001525 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001526 Ops.erase(Ops.begin()+Idx);
1527 Ops.erase(Ops.begin()+OtherMulIdx-1);
1528 Ops.push_back(OuterMul);
1529 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001530 }
1531 }
1532 }
1533 }
1534
1535 // If there are any add recurrences in the operands list, see if any other
1536 // added values are loop invariant. If so, we can fold them into the
1537 // recurrence.
1538 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1539 ++Idx;
1540
1541 // Scan over all recurrences, trying to fold loop invariants into them.
1542 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1543 // Scan all of the other operands to this add and add them to the vector if
1544 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001545 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001546 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001547 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001549 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 LIOps.push_back(Ops[i]);
1551 Ops.erase(Ops.begin()+i);
1552 --i; --e;
1553 }
1554
1555 // If we found some loop invariants, fold them into the recurrence.
1556 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001557 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 LIOps.push_back(AddRec->getStart());
1559
Dan Gohman0bba49c2009-07-07 17:06:11 +00001560 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001561 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001562 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001563
Dan Gohmanb9f96512010-06-30 07:16:37 +00001564 // Build the new addrec. Propagate the NUW and NSW flags if both the
1565 // outer add and the inner addrec are guaranteed to have no overflow.
1566 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1567 HasNUW && AddRec->hasNoUnsignedWrap(),
1568 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001569
Chris Lattner53e677a2004-04-02 20:23:17 +00001570 // If all of the other operands were loop invariant, we are done.
1571 if (Ops.size() == 1) return NewRec;
1572
1573 // Otherwise, add the folded AddRec by the non-liv parts.
1574 for (unsigned i = 0;; ++i)
1575 if (Ops[i] == AddRec) {
1576 Ops[i] = NewRec;
1577 break;
1578 }
Dan Gohman246b2562007-10-22 18:31:58 +00001579 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 }
1581
1582 // Okay, if there weren't any loop invariants to be folded, check to see if
1583 // there are multiple AddRec's with the same loop induction variable being
1584 // added together. If so, we can fold them.
1585 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001586 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1587 ++OtherIdx)
1588 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1589 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1590 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1591 AddRec->op_end());
1592 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1593 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001594 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001595 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001596 if (OtherAddRec->getLoop() == AddRecLoop) {
1597 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1598 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001599 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001600 AddRecOps.append(OtherAddRec->op_begin()+i,
1601 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001602 break;
1603 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001604 AddRecOps[i] = getAddExpr(AddRecOps[i],
1605 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001606 }
1607 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001608 }
Dan Gohman32527152010-08-27 20:45:56 +00001609 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop);
1610 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001611 }
1612
1613 // Otherwise couldn't fold anything into this recurrence. Move onto the
1614 // next one.
1615 }
1616
1617 // Okay, it looks like we really DO need an add expr. Check to see if we
1618 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001619 FoldingSetNodeID ID;
1620 ID.AddInteger(scAddExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001621 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1622 ID.AddPointer(Ops[i]);
1623 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001624 SCEVAddExpr *S =
1625 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1626 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001627 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1628 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001629 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1630 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001631 UniqueSCEVs.InsertNode(S, IP);
1632 }
Dan Gohman3645b012009-10-09 00:10:36 +00001633 if (HasNUW) S->setHasNoUnsignedWrap(true);
1634 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001635 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001636}
1637
Dan Gohman6c0866c2009-05-24 23:45:28 +00001638/// getMulExpr - Get a canonical multiply expression, or something simpler if
1639/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001640const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1641 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001642 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001643 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001644#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001645 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001646 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001647 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001648 "SCEVMulExpr operand types don't match!");
1649#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001650
Dan Gohmana10756e2010-01-21 02:09:26 +00001651 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1652 if (!HasNUW && HasNSW) {
1653 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001654 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1655 E = Ops.end(); I != E; ++I)
1656 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001657 All = false;
1658 break;
1659 }
1660 if (All) HasNUW = true;
1661 }
1662
Chris Lattner53e677a2004-04-02 20:23:17 +00001663 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001664 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001665
1666 // If there are any constants, fold them together.
1667 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001668 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001669
1670 // C1*(C2+V) -> C1*C2 + C1*V
1671 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001672 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 if (Add->getNumOperands() == 2 &&
1674 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001675 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1676 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001677
Chris Lattner53e677a2004-04-02 20:23:17 +00001678 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001679 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001681 ConstantInt *Fold = ConstantInt::get(getContext(),
1682 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001683 RHSC->getValue()->getValue());
1684 Ops[0] = getConstant(Fold);
1685 Ops.erase(Ops.begin()+1); // Erase the folded element
1686 if (Ops.size() == 1) return Ops[0];
1687 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001688 }
1689
1690 // If we are left with a constant one being multiplied, strip it off.
1691 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1692 Ops.erase(Ops.begin());
1693 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001694 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001695 // If we have a multiply of zero, it will always be zero.
1696 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001697 } else if (Ops[0]->isAllOnesValue()) {
1698 // If we have a mul by -1 of an add, try distributing the -1 among the
1699 // add operands.
1700 if (Ops.size() == 2)
1701 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1702 SmallVector<const SCEV *, 4> NewOps;
1703 bool AnyFolded = false;
1704 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1705 I != E; ++I) {
1706 const SCEV *Mul = getMulExpr(Ops[0], *I);
1707 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1708 NewOps.push_back(Mul);
1709 }
1710 if (AnyFolded)
1711 return getAddExpr(NewOps);
1712 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001713 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001714
1715 if (Ops.size() == 1)
1716 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001717 }
1718
1719 // Skip over the add expression until we get to a multiply.
1720 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1721 ++Idx;
1722
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 // If there are mul operands inline them all into this expression.
1724 if (Idx < Ops.size()) {
1725 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001726 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001727 // If we have an mul, expand the mul operands onto the end of the operands
1728 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001729 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001730 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001731 DeletedMul = true;
1732 }
1733
1734 // If we deleted at least one mul, we added operands to the end of the list,
1735 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001736 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001738 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001739 }
1740
1741 // If there are any add recurrences in the operands list, see if any other
1742 // added values are loop invariant. If so, we can fold them into the
1743 // recurrence.
1744 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1745 ++Idx;
1746
1747 // Scan over all recurrences, trying to fold loop invariants into them.
1748 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1749 // Scan all of the other operands to this mul and add them to the vector if
1750 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001751 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001752 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001753 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001754 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001755 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001756 LIOps.push_back(Ops[i]);
1757 Ops.erase(Ops.begin()+i);
1758 --i; --e;
1759 }
1760
1761 // If we found some loop invariants, fold them into the recurrence.
1762 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001763 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001764 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001765 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001766 const SCEV *Scale = getMulExpr(LIOps);
1767 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1768 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001769
Dan Gohmanb9f96512010-06-30 07:16:37 +00001770 // Build the new addrec. Propagate the NUW and NSW flags if both the
1771 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohman0f32ae32010-08-29 14:55:19 +00001772 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop,
Dan Gohmana10756e2010-01-21 02:09:26 +00001773 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001774 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001775
1776 // If all of the other operands were loop invariant, we are done.
1777 if (Ops.size() == 1) return NewRec;
1778
1779 // Otherwise, multiply the folded AddRec by the non-liv parts.
1780 for (unsigned i = 0;; ++i)
1781 if (Ops[i] == AddRec) {
1782 Ops[i] = NewRec;
1783 break;
1784 }
Dan Gohman246b2562007-10-22 18:31:58 +00001785 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 }
1787
1788 // Okay, if there weren't any loop invariants to be folded, check to see if
1789 // there are multiple AddRec's with the same loop induction variable being
1790 // multiplied together. If so, we can fold them.
1791 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001792 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1793 ++OtherIdx)
1794 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1795 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1796 // {A*C,+,F*D + G*B + B*D}<L>
1797 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1798 ++OtherIdx)
1799 if (const SCEVAddRecExpr *OtherAddRec =
1800 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1801 if (OtherAddRec->getLoop() == AddRecLoop) {
1802 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1803 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1804 const SCEV *B = F->getStepRecurrence(*this);
1805 const SCEV *D = G->getStepRecurrence(*this);
1806 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1807 getMulExpr(G, B),
1808 getMulExpr(B, D));
1809 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1810 F->getLoop());
1811 if (Ops.size() == 2) return NewAddRec;
1812 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1813 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1814 }
1815 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001816 }
1817
1818 // Otherwise couldn't fold anything into this recurrence. Move onto the
1819 // next one.
1820 }
1821
1822 // Okay, it looks like we really DO need an mul expr. Check to see if we
1823 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001824 FoldingSetNodeID ID;
1825 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001826 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1827 ID.AddPointer(Ops[i]);
1828 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001829 SCEVMulExpr *S =
1830 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1831 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001832 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1833 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001834 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1835 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001836 UniqueSCEVs.InsertNode(S, IP);
1837 }
Dan Gohman3645b012009-10-09 00:10:36 +00001838 if (HasNUW) S->setHasNoUnsignedWrap(true);
1839 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001840 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001841}
1842
Andreas Bolka8a11c982009-08-07 22:55:26 +00001843/// getUDivExpr - Get a canonical unsigned division expression, or something
1844/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001845const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1846 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001847 assert(getEffectiveSCEVType(LHS->getType()) ==
1848 getEffectiveSCEVType(RHS->getType()) &&
1849 "SCEVUDivExpr operand types don't match!");
1850
Dan Gohman622ed672009-05-04 22:02:23 +00001851 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001852 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001853 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001854 // If the denominator is zero, the result of the udiv is undefined. Don't
1855 // try to analyze it, because the resolution chosen here may differ from
1856 // the resolution chosen in other parts of the compiler.
1857 if (!RHSC->getValue()->isZero()) {
1858 // Determine if the division can be folded into the operands of
1859 // its operands.
1860 // TODO: Generalize this to non-constants by using known-bits information.
1861 const Type *Ty = LHS->getType();
1862 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001863 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001864 // For non-power-of-two values, effectively round the value up to the
1865 // nearest power of two.
1866 if (!RHSC->getValue()->getValue().isPowerOf2())
1867 ++MaxShiftAmt;
1868 const IntegerType *ExtTy =
1869 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1870 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1871 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1872 if (const SCEVConstant *Step =
1873 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1874 if (!Step->getValue()->getValue()
1875 .urem(RHSC->getValue()->getValue()) &&
1876 getZeroExtendExpr(AR, ExtTy) ==
1877 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1878 getZeroExtendExpr(Step, ExtTy),
1879 AR->getLoop())) {
1880 SmallVector<const SCEV *, 4> Operands;
1881 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1882 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1883 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001884 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001885 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1886 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1887 SmallVector<const SCEV *, 4> Operands;
1888 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1889 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1890 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1891 // Find an operand that's safely divisible.
1892 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1893 const SCEV *Op = M->getOperand(i);
1894 const SCEV *Div = getUDivExpr(Op, RHSC);
1895 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1896 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1897 M->op_end());
1898 Operands[i] = Div;
1899 return getMulExpr(Operands);
1900 }
1901 }
Dan Gohman185cf032009-05-08 20:18:49 +00001902 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001903 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1904 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1905 SmallVector<const SCEV *, 4> Operands;
1906 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1907 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1908 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1909 Operands.clear();
1910 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1911 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1912 if (isa<SCEVUDivExpr>(Op) ||
1913 getMulExpr(Op, RHS) != A->getOperand(i))
1914 break;
1915 Operands.push_back(Op);
1916 }
1917 if (Operands.size() == A->getNumOperands())
1918 return getAddExpr(Operands);
1919 }
1920 }
Dan Gohman185cf032009-05-08 20:18:49 +00001921
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001922 // Fold if both operands are constant.
1923 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1924 Constant *LHSCV = LHSC->getValue();
1925 Constant *RHSCV = RHSC->getValue();
1926 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1927 RHSCV)));
1928 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001929 }
1930 }
1931
Dan Gohman1c343752009-06-27 21:21:31 +00001932 FoldingSetNodeID ID;
1933 ID.AddInteger(scUDivExpr);
1934 ID.AddPointer(LHS);
1935 ID.AddPointer(RHS);
1936 void *IP = 0;
1937 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001938 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1939 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001940 UniqueSCEVs.InsertNode(S, IP);
1941 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001942}
1943
1944
Dan Gohman6c0866c2009-05-24 23:45:28 +00001945/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1946/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001947const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001948 const SCEV *Step, const Loop *L,
1949 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001950 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001951 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001952 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001953 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001954 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001955 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001956 }
1957
1958 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001959 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001960}
1961
Dan Gohman6c0866c2009-05-24 23:45:28 +00001962/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1963/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001964const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001965ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001966 const Loop *L,
1967 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001968 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001969#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001970 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001971 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001972 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001973 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00001974 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001975 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00001976 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001977#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001978
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001979 if (Operands.back()->isZero()) {
1980 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001981 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001982 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001983
Dan Gohmanbc028532010-02-19 18:49:22 +00001984 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1985 // use that information to infer NUW and NSW flags. However, computing a
1986 // BE count requires calling getAddRecExpr, so we may not yet have a
1987 // meaningful BE count at this point (and if we don't, we'd be stuck
1988 // with a SCEVCouldNotCompute as the cached BE count).
1989
Dan Gohmana10756e2010-01-21 02:09:26 +00001990 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1991 if (!HasNUW && HasNSW) {
1992 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001993 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
1994 E = Operands.end(); I != E; ++I)
1995 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001996 All = false;
1997 break;
1998 }
1999 if (All) HasNUW = true;
2000 }
2001
Dan Gohmand9cc7492008-08-08 18:33:12 +00002002 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002003 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002004 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002005 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002006 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002007 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002008 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002009 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002010 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002011 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002012 // AddRecs require their operands be loop-invariant with respect to their
2013 // loops. Don't perform this transformation if it would break this
2014 // requirement.
2015 bool AllInvariant = true;
2016 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002017 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002018 AllInvariant = false;
2019 break;
2020 }
2021 if (AllInvariant) {
2022 NestedOperands[0] = getAddRecExpr(Operands, L);
2023 AllInvariant = true;
2024 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002025 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002026 AllInvariant = false;
2027 break;
2028 }
2029 if (AllInvariant)
2030 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002031 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002032 }
2033 // Reset Operands to its original state.
2034 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002035 }
2036 }
2037
Dan Gohman67847532010-01-19 22:27:22 +00002038 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2039 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002040 FoldingSetNodeID ID;
2041 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002042 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2043 ID.AddPointer(Operands[i]);
2044 ID.AddPointer(L);
2045 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002046 SCEVAddRecExpr *S =
2047 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2048 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002049 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2050 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002051 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2052 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002053 UniqueSCEVs.InsertNode(S, IP);
2054 }
Dan Gohman3645b012009-10-09 00:10:36 +00002055 if (HasNUW) S->setHasNoUnsignedWrap(true);
2056 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002057 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002058}
2059
Dan Gohman9311ef62009-06-24 14:49:00 +00002060const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2061 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002062 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002063 Ops.push_back(LHS);
2064 Ops.push_back(RHS);
2065 return getSMaxExpr(Ops);
2066}
2067
Dan Gohman0bba49c2009-07-07 17:06:11 +00002068const SCEV *
2069ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002070 assert(!Ops.empty() && "Cannot get empty smax!");
2071 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002072#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002073 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002074 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002075 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002076 "SCEVSMaxExpr operand types don't match!");
2077#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002078
2079 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002080 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002081
2082 // If there are any constants, fold them together.
2083 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002084 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002085 ++Idx;
2086 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002087 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002088 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002089 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002090 APIntOps::smax(LHSC->getValue()->getValue(),
2091 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002092 Ops[0] = getConstant(Fold);
2093 Ops.erase(Ops.begin()+1); // Erase the folded element
2094 if (Ops.size() == 1) return Ops[0];
2095 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002096 }
2097
Dan Gohmane5aceed2009-06-24 14:46:22 +00002098 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002099 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2100 Ops.erase(Ops.begin());
2101 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002102 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2103 // If we have an smax with a constant maximum-int, it will always be
2104 // maximum-int.
2105 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002106 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002107
Dan Gohman3ab13122010-04-13 16:49:23 +00002108 if (Ops.size() == 1) return Ops[0];
2109 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002110
2111 // Find the first SMax
2112 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2113 ++Idx;
2114
2115 // Check to see if one of the operands is an SMax. If so, expand its operands
2116 // onto our operand list, and recurse to simplify.
2117 if (Idx < Ops.size()) {
2118 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002119 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002120 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002121 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002122 DeletedSMax = true;
2123 }
2124
2125 if (DeletedSMax)
2126 return getSMaxExpr(Ops);
2127 }
2128
2129 // Okay, check to see if the same value occurs in the operand list twice. If
2130 // so, delete one. Since we sorted the list, these values are required to
2131 // be adjacent.
2132 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002133 // X smax Y smax Y --> X smax Y
2134 // X smax Y --> X, if X is always greater than Y
2135 if (Ops[i] == Ops[i+1] ||
2136 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2137 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2138 --i; --e;
2139 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002140 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2141 --i; --e;
2142 }
2143
2144 if (Ops.size() == 1) return Ops[0];
2145
2146 assert(!Ops.empty() && "Reduced smax down to nothing!");
2147
Nick Lewycky3e630762008-02-20 06:48:22 +00002148 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002149 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002150 FoldingSetNodeID ID;
2151 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002152 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2153 ID.AddPointer(Ops[i]);
2154 void *IP = 0;
2155 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002156 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2157 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002158 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2159 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002160 UniqueSCEVs.InsertNode(S, IP);
2161 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002162}
2163
Dan Gohman9311ef62009-06-24 14:49:00 +00002164const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2165 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002166 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002167 Ops.push_back(LHS);
2168 Ops.push_back(RHS);
2169 return getUMaxExpr(Ops);
2170}
2171
Dan Gohman0bba49c2009-07-07 17:06:11 +00002172const SCEV *
2173ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002174 assert(!Ops.empty() && "Cannot get empty umax!");
2175 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002176#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002177 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002178 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002179 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002180 "SCEVUMaxExpr operand types don't match!");
2181#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002182
2183 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002184 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002185
2186 // If there are any constants, fold them together.
2187 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002188 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002189 ++Idx;
2190 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002191 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002192 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002193 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002194 APIntOps::umax(LHSC->getValue()->getValue(),
2195 RHSC->getValue()->getValue()));
2196 Ops[0] = getConstant(Fold);
2197 Ops.erase(Ops.begin()+1); // Erase the folded element
2198 if (Ops.size() == 1) return Ops[0];
2199 LHSC = cast<SCEVConstant>(Ops[0]);
2200 }
2201
Dan Gohmane5aceed2009-06-24 14:46:22 +00002202 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002203 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2204 Ops.erase(Ops.begin());
2205 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002206 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2207 // If we have an umax with a constant maximum-int, it will always be
2208 // maximum-int.
2209 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002210 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002211
Dan Gohman3ab13122010-04-13 16:49:23 +00002212 if (Ops.size() == 1) return Ops[0];
2213 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002214
2215 // Find the first UMax
2216 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2217 ++Idx;
2218
2219 // Check to see if one of the operands is a UMax. If so, expand its operands
2220 // onto our operand list, and recurse to simplify.
2221 if (Idx < Ops.size()) {
2222 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002223 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002224 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002225 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002226 DeletedUMax = true;
2227 }
2228
2229 if (DeletedUMax)
2230 return getUMaxExpr(Ops);
2231 }
2232
2233 // Okay, check to see if the same value occurs in the operand list twice. If
2234 // so, delete one. Since we sorted the list, these values are required to
2235 // be adjacent.
2236 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002237 // X umax Y umax Y --> X umax Y
2238 // X umax Y --> X, if X is always greater than Y
2239 if (Ops[i] == Ops[i+1] ||
2240 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2241 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2242 --i; --e;
2243 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002244 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2245 --i; --e;
2246 }
2247
2248 if (Ops.size() == 1) return Ops[0];
2249
2250 assert(!Ops.empty() && "Reduced umax down to nothing!");
2251
2252 // Okay, it looks like we really DO need a umax expr. Check to see if we
2253 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002254 FoldingSetNodeID ID;
2255 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002256 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2257 ID.AddPointer(Ops[i]);
2258 void *IP = 0;
2259 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002260 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2261 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002262 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2263 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002264 UniqueSCEVs.InsertNode(S, IP);
2265 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002266}
2267
Dan Gohman9311ef62009-06-24 14:49:00 +00002268const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2269 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002270 // ~smax(~x, ~y) == smin(x, y).
2271 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2272}
2273
Dan Gohman9311ef62009-06-24 14:49:00 +00002274const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2275 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002276 // ~umax(~x, ~y) == umin(x, y)
2277 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2278}
2279
Dan Gohman4f8eea82010-02-01 18:27:38 +00002280const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002281 // If we have TargetData, we can bypass creating a target-independent
2282 // constant expression and then folding it back into a ConstantInt.
2283 // This is just a compile-time optimization.
2284 if (TD)
2285 return getConstant(TD->getIntPtrType(getContext()),
2286 TD->getTypeAllocSize(AllocTy));
2287
Dan Gohman4f8eea82010-02-01 18:27:38 +00002288 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2289 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002290 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2291 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002292 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2293 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2294}
2295
2296const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2297 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2298 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002299 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2300 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002301 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2302 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2303}
2304
2305const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2306 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002307 // If we have TargetData, we can bypass creating a target-independent
2308 // constant expression and then folding it back into a ConstantInt.
2309 // This is just a compile-time optimization.
2310 if (TD)
2311 return getConstant(TD->getIntPtrType(getContext()),
2312 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2313
Dan Gohman0f5efe52010-01-28 02:15:55 +00002314 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002316 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2317 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002318 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002319 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002320}
2321
Dan Gohman4f8eea82010-02-01 18:27:38 +00002322const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2323 Constant *FieldNo) {
2324 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002326 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2327 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002328 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002329 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002330}
2331
Dan Gohman0bba49c2009-07-07 17:06:11 +00002332const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002333 // Don't attempt to do anything other than create a SCEVUnknown object
2334 // here. createSCEV only calls getUnknown after checking for all other
2335 // interesting possibilities, and any other code that calls getUnknown
2336 // is doing so in order to hide a value from SCEV canonicalization.
2337
Dan Gohman1c343752009-06-27 21:21:31 +00002338 FoldingSetNodeID ID;
2339 ID.AddInteger(scUnknown);
2340 ID.AddPointer(V);
2341 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002342 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2343 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2344 "Stale SCEVUnknown in uniquing map!");
2345 return S;
2346 }
2347 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2348 FirstUnknown);
2349 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002350 UniqueSCEVs.InsertNode(S, IP);
2351 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002352}
2353
Chris Lattner53e677a2004-04-02 20:23:17 +00002354//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002355// Basic SCEV Analysis and PHI Idiom Recognition Code
2356//
2357
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002358/// isSCEVable - Test if values of the given type are analyzable within
2359/// the SCEV framework. This primarily includes integer types, and it
2360/// can optionally include pointer types if the ScalarEvolution class
2361/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002362bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002363 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002364 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002365}
2366
2367/// getTypeSizeInBits - Return the size in bits of the specified type,
2368/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002369uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002370 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2371
2372 // If we have a TargetData, use it!
2373 if (TD)
2374 return TD->getTypeSizeInBits(Ty);
2375
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002376 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002377 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002378 return Ty->getPrimitiveSizeInBits();
2379
2380 // The only other support type is pointer. Without TargetData, conservatively
2381 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002382 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002383 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002384}
2385
2386/// getEffectiveSCEVType - Return a type with the same bitwidth as
2387/// the given type and which represents how SCEV will treat the given
2388/// type, for which isSCEVable must return true. For pointer types,
2389/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002390const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002391 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2392
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002393 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002394 return Ty;
2395
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002396 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002397 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002398 if (TD) return TD->getIntPtrType(getContext());
2399
2400 // Without TargetData, conservatively assume pointers are 64-bit.
2401 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002402}
Chris Lattner53e677a2004-04-02 20:23:17 +00002403
Dan Gohman0bba49c2009-07-07 17:06:11 +00002404const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002405 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002406}
2407
Chris Lattner53e677a2004-04-02 20:23:17 +00002408/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2409/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002410const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002411 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002412
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002413 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2414 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002415 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002416
2417 // The process of creating a SCEV for V may have caused other SCEVs
2418 // to have been created, so it's necessary to insert the new entry
2419 // from scratch, rather than trying to remember the insert position
2420 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002421 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002422 return S;
2423}
2424
Dan Gohman2d1be872009-04-16 03:18:22 +00002425/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2426///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002427const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002428 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002429 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002430 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002431
2432 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002433 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002434 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002435 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002436}
2437
2438/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002439const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002440 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002441 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002442 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002443
2444 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002445 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002446 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002447 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002448 return getMinusSCEV(AllOnes, V);
2449}
2450
2451/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2452///
Dan Gohman9311ef62009-06-24 14:49:00 +00002453const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2454 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002455 // Fast path: X - X --> 0.
2456 if (LHS == RHS)
2457 return getConstant(LHS->getType(), 0);
2458
Dan Gohman2d1be872009-04-16 03:18:22 +00002459 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002460 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002461}
2462
2463/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2464/// input value to the specified type. If the type must be extended, it is zero
2465/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002466const SCEV *
2467ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002468 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002469 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002470 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2471 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002472 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002473 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002474 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002475 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002476 return getTruncateExpr(V, Ty);
2477 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002478}
2479
2480/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2481/// input value to the specified type. If the type must be extended, it is sign
2482/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002483const SCEV *
2484ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002485 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002486 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002487 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2488 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002489 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002490 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002491 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002492 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002493 return getTruncateExpr(V, Ty);
2494 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002495}
2496
Dan Gohman467c4302009-05-13 03:46:30 +00002497/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2498/// input value to the specified type. If the type must be extended, it is zero
2499/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002500const SCEV *
2501ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002502 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002505 "Cannot noop or zero extend with non-integer arguments!");
2506 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2507 "getNoopOrZeroExtend cannot truncate!");
2508 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2509 return V; // No conversion
2510 return getZeroExtendExpr(V, Ty);
2511}
2512
2513/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2514/// input value to the specified type. If the type must be extended, it is sign
2515/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002516const SCEV *
2517ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002518 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002519 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2520 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002521 "Cannot noop or sign extend with non-integer arguments!");
2522 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2523 "getNoopOrSignExtend cannot truncate!");
2524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2525 return V; // No conversion
2526 return getSignExtendExpr(V, Ty);
2527}
2528
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002529/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2530/// the input value to the specified type. If the type must be extended,
2531/// it is extended with unspecified bits. The conversion must not be
2532/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002533const SCEV *
2534ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002535 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002536 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2537 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002538 "Cannot noop or any extend with non-integer arguments!");
2539 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2540 "getNoopOrAnyExtend cannot truncate!");
2541 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2542 return V; // No conversion
2543 return getAnyExtendExpr(V, Ty);
2544}
2545
Dan Gohman467c4302009-05-13 03:46:30 +00002546/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2547/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002548const SCEV *
2549ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002550 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002551 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2552 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002553 "Cannot truncate or noop with non-integer arguments!");
2554 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2555 "getTruncateOrNoop cannot extend!");
2556 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2557 return V; // No conversion
2558 return getTruncateExpr(V, Ty);
2559}
2560
Dan Gohmana334aa72009-06-22 00:31:57 +00002561/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2562/// the types using zero-extension, and then perform a umax operation
2563/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002564const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2565 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002566 const SCEV *PromotedLHS = LHS;
2567 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002568
2569 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2570 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2571 else
2572 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2573
2574 return getUMaxExpr(PromotedLHS, PromotedRHS);
2575}
2576
Dan Gohmanc9759e82009-06-22 15:03:27 +00002577/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2578/// the types using zero-extension, and then perform a umin operation
2579/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002580const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2581 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002582 const SCEV *PromotedLHS = LHS;
2583 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002584
2585 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2586 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2587 else
2588 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2589
2590 return getUMinExpr(PromotedLHS, PromotedRHS);
2591}
2592
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002593/// PushDefUseChildren - Push users of the given Instruction
2594/// onto the given Worklist.
2595static void
2596PushDefUseChildren(Instruction *I,
2597 SmallVectorImpl<Instruction *> &Worklist) {
2598 // Push the def-use children onto the Worklist stack.
2599 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2600 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002601 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002602}
2603
2604/// ForgetSymbolicValue - This looks up computed SCEV values for all
2605/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002606/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002607/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002608void
Dan Gohman85669632010-02-25 06:57:05 +00002609ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002610 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002611 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002612
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002613 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002614 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002615 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002616 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002617 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002618
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002619 ValueExprMapType::iterator It =
2620 ValueExprMap.find(static_cast<Value *>(I));
2621 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002622 const SCEV *Old = It->second;
2623
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002624 // Short-circuit the def-use traversal if the symbolic name
2625 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002626 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002627 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002628
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002629 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002630 // structure, it's a PHI that's in the progress of being computed
2631 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2632 // additional loop trip count information isn't going to change anything.
2633 // In the second case, createNodeForPHI will perform the necessary
2634 // updates on its own when it gets to that point. In the third, we do
2635 // want to forget the SCEVUnknown.
2636 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002637 !isa<SCEVUnknown>(Old) ||
2638 (I != PN && Old == SymName)) {
2639 ValuesAtScopes.erase(Old);
Dan Gohman714b5292010-11-17 23:21:44 +00002640 LoopDispositions.erase(Old);
Dan Gohman6678e7b2010-11-17 02:44:44 +00002641 UnsignedRanges.erase(Old);
2642 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002643 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002644 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002645 }
2646
2647 PushDefUseChildren(I, Worklist);
2648 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002649}
Chris Lattner53e677a2004-04-02 20:23:17 +00002650
2651/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2652/// a loop header, making it a potential recurrence, or it doesn't.
2653///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002654const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002655 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2656 if (L->getHeader() == PN->getParent()) {
2657 // The loop may have multiple entrances or multiple exits; we can analyze
2658 // this phi as an addrec if it has a unique entry value and a unique
2659 // backedge value.
2660 Value *BEValueV = 0, *StartValueV = 0;
2661 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2662 Value *V = PN->getIncomingValue(i);
2663 if (L->contains(PN->getIncomingBlock(i))) {
2664 if (!BEValueV) {
2665 BEValueV = V;
2666 } else if (BEValueV != V) {
2667 BEValueV = 0;
2668 break;
2669 }
2670 } else if (!StartValueV) {
2671 StartValueV = V;
2672 } else if (StartValueV != V) {
2673 StartValueV = 0;
2674 break;
2675 }
2676 }
2677 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002678 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002679 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002680 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002681 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002682 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002683
2684 // Using this symbolic name for the PHI, analyze the value coming around
2685 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002686 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002687
2688 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2689 // has a special value for the first iteration of the loop.
2690
2691 // If the value coming around the backedge is an add with the symbolic
2692 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002693 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002694 // If there is a single occurrence of the symbolic value, replace it
2695 // with a recurrence.
2696 unsigned FoundIndex = Add->getNumOperands();
2697 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2698 if (Add->getOperand(i) == SymbolicName)
2699 if (FoundIndex == e) {
2700 FoundIndex = i;
2701 break;
2702 }
2703
2704 if (FoundIndex != Add->getNumOperands()) {
2705 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002706 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002707 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2708 if (i != FoundIndex)
2709 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002710 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002711
2712 // This is not a valid addrec if the step amount is varying each
2713 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002714 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002715 (isa<SCEVAddRecExpr>(Accum) &&
2716 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002717 bool HasNUW = false;
2718 bool HasNSW = false;
2719
2720 // If the increment doesn't overflow, then neither the addrec nor
2721 // the post-increment will overflow.
2722 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2723 if (OBO->hasNoUnsignedWrap())
2724 HasNUW = true;
2725 if (OBO->hasNoSignedWrap())
2726 HasNSW = true;
2727 }
2728
Dan Gohman27dead42010-04-12 07:49:36 +00002729 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002730 const SCEV *PHISCEV =
2731 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002732
Dan Gohmana10756e2010-01-21 02:09:26 +00002733 // Since the no-wrap flags are on the increment, they apply to the
2734 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002735 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00002736 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2737 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002738
2739 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002740 // to be symbolic. We now need to go back and purge all of the
2741 // entries for the scalars that use the symbolic expression.
2742 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002743 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002744 return PHISCEV;
2745 }
2746 }
Dan Gohman622ed672009-05-04 22:02:23 +00002747 } else if (const SCEVAddRecExpr *AddRec =
2748 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002749 // Otherwise, this could be a loop like this:
2750 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2751 // In this case, j = {1,+,1} and BEValue is j.
2752 // Because the other in-value of i (0) fits the evolution of BEValue
2753 // i really is an addrec evolution.
2754 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002755 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002756
2757 // If StartVal = j.start - j.stride, we can use StartVal as the
2758 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002759 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002760 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002761 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002762 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002763
2764 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002765 // to be symbolic. We now need to go back and purge all of the
2766 // entries for the scalars that use the symbolic expression.
2767 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002768 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002769 return PHISCEV;
2770 }
2771 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002772 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002773 }
Dan Gohman27dead42010-04-12 07:49:36 +00002774 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002775
Dan Gohman85669632010-02-25 06:57:05 +00002776 // If the PHI has a single incoming value, follow that value, unless the
2777 // PHI's incoming blocks are in a different loop, in which case doing so
2778 // risks breaking LCSSA form. Instcombine would normally zap these, but
2779 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsa0c52442010-11-17 04:18:45 +00002780 if (Value *V = SimplifyInstruction(PN, TD, DT)) {
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002781 Instruction *I = dyn_cast<Instruction>(V);
2782 // Only instructions are problematic for preserving LCSSA form.
2783 if (!I)
Dan Gohman85669632010-02-25 06:57:05 +00002784 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002785
2786 // If the instruction is not defined in a loop, then it can be used freely.
2787 Loop *ILoop = LI->getLoopFor(I->getParent());
2788 if (!ILoop)
2789 return getSCEV(I);
2790
2791 // If the instruction is defined in the same loop as the phi node, or in a
2792 // loop that contains the phi node loop as an inner loop, then using it as
2793 // a replacement for the phi node will not break LCSSA form.
2794 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2795 if (ILoop->contains(PNLoop))
2796 return getSCEV(I);
Dan Gohman85669632010-02-25 06:57:05 +00002797 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002798
Chris Lattner53e677a2004-04-02 20:23:17 +00002799 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002800 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002801}
2802
Dan Gohman26466c02009-05-08 20:26:55 +00002803/// createNodeForGEP - Expand GEP instructions into add and multiply
2804/// operations. This allows them to be analyzed by regular SCEV code.
2805///
Dan Gohmand281ed22009-12-18 02:09:29 +00002806const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002807
Dan Gohmanb9f96512010-06-30 07:16:37 +00002808 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2809 // Add expression, because the Instruction may be guarded by control flow
2810 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002811 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002812
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002813 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002814 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002815 // Don't attempt to analyze GEPs over unsized objects.
2816 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2817 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002818 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002819 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002820 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002821 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002822 I != E; ++I) {
2823 Value *Index = *I;
2824 // Compute the (potentially symbolic) offset in bytes for this index.
2825 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2826 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002827 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002828 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2829
Dan Gohmanb9f96512010-06-30 07:16:37 +00002830 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002831 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002832 } else {
2833 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002834 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2835 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002836 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002837 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2838
Dan Gohmanb9f96512010-06-30 07:16:37 +00002839 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002840 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002841
2842 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002843 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002844 }
2845 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002846
2847 // Get the SCEV for the GEP base.
2848 const SCEV *BaseS = getSCEV(Base);
2849
Dan Gohmanb9f96512010-06-30 07:16:37 +00002850 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002851 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002852}
2853
Nick Lewycky83bb0052007-11-22 07:59:40 +00002854/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2855/// guaranteed to end in (at every loop iteration). It is, at the same time,
2856/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2857/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002858uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002859ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002860 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002861 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002862
Dan Gohman622ed672009-05-04 22:02:23 +00002863 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002864 return std::min(GetMinTrailingZeros(T->getOperand()),
2865 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002866
Dan Gohman622ed672009-05-04 22:02:23 +00002867 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002868 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2869 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2870 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002871 }
2872
Dan Gohman622ed672009-05-04 22:02:23 +00002873 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002874 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2875 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2876 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002877 }
2878
Dan Gohman622ed672009-05-04 22:02:23 +00002879 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002880 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002881 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002882 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002883 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002884 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002885 }
2886
Dan Gohman622ed672009-05-04 22:02:23 +00002887 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002888 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002889 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2890 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002891 for (unsigned i = 1, e = M->getNumOperands();
2892 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002893 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002894 BitWidth);
2895 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002896 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002897
Dan Gohman622ed672009-05-04 22:02:23 +00002898 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002899 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002900 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002901 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002902 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002903 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002904 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002905
Dan Gohman622ed672009-05-04 22:02:23 +00002906 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002907 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002908 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002909 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002910 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002911 return MinOpRes;
2912 }
2913
Dan Gohman622ed672009-05-04 22:02:23 +00002914 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002915 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002916 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002917 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002918 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002919 return MinOpRes;
2920 }
2921
Dan Gohman2c364ad2009-06-19 23:29:04 +00002922 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2923 // For a SCEVUnknown, ask ValueTracking.
2924 unsigned BitWidth = getTypeSizeInBits(U->getType());
2925 APInt Mask = APInt::getAllOnesValue(BitWidth);
2926 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2927 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2928 return Zeros.countTrailingOnes();
2929 }
2930
2931 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002932 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002933}
Chris Lattner53e677a2004-04-02 20:23:17 +00002934
Dan Gohman85b05a22009-07-13 21:35:55 +00002935/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2936///
2937ConstantRange
2938ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002939 // See if we've computed this range already.
2940 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
2941 if (I != UnsignedRanges.end())
2942 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002943
2944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002945 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002947 unsigned BitWidth = getTypeSizeInBits(S->getType());
2948 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2949
2950 // If the value has known zeros, the maximum unsigned value will have those
2951 // known zeros as well.
2952 uint32_t TZ = GetMinTrailingZeros(S);
2953 if (TZ != 0)
2954 ConservativeResult =
2955 ConstantRange(APInt::getMinValue(BitWidth),
2956 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2957
Dan Gohman85b05a22009-07-13 21:35:55 +00002958 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2959 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2960 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2961 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002962 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002963 }
2964
2965 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2966 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2967 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2968 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002969 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002970 }
2971
2972 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2973 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2974 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2975 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002976 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002977 }
2978
2979 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2980 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2981 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2982 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002983 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002984 }
2985
2986 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2987 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2988 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002989 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002990 }
2991
2992 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002994 return setUnsignedRange(ZExt,
2995 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002996 }
2997
2998 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2999 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003000 return setUnsignedRange(SExt,
3001 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003002 }
3003
3004 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3005 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003006 return setUnsignedRange(Trunc,
3007 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003008 }
3009
Dan Gohman85b05a22009-07-13 21:35:55 +00003010 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003011 // If there's no unsigned wrap, the value will never be less than its
3012 // initial value.
3013 if (AddRec->hasNoUnsignedWrap())
3014 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003015 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003016 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003017 ConservativeResult.intersectWith(
3018 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003019
3020 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003021 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003022 const Type *Ty = AddRec->getType();
3023 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003024 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3025 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003026 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3027
3028 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003029 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003030
3031 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003032 ConstantRange StepRange = getSignedRange(Step);
3033 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3034 ConstantRange EndRange =
3035 StartRange.add(MaxBECountRange.multiply(StepRange));
3036
3037 // Check for overflow. This must be done with ConstantRange arithmetic
3038 // because we could be called from within the ScalarEvolution overflow
3039 // checking code.
3040 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3041 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3042 ConstantRange ExtMaxBECountRange =
3043 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3044 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3045 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3046 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003047 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003048
Dan Gohman85b05a22009-07-13 21:35:55 +00003049 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3050 EndRange.getUnsignedMin());
3051 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3052 EndRange.getUnsignedMax());
3053 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003054 return setUnsignedRange(AddRec, ConservativeResult);
3055 return setUnsignedRange(AddRec,
3056 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003057 }
3058 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003059
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003060 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003061 }
3062
3063 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3064 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003065 APInt Mask = APInt::getAllOnesValue(BitWidth);
3066 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3067 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003068 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003069 return setUnsignedRange(U, ConservativeResult);
3070 return setUnsignedRange(U,
3071 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003072 }
3073
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003074 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003075}
3076
Dan Gohman85b05a22009-07-13 21:35:55 +00003077/// getSignedRange - Determine the signed range for a particular SCEV.
3078///
3079ConstantRange
3080ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003081 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3082 if (I != SignedRanges.end())
3083 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003084
Dan Gohman85b05a22009-07-13 21:35:55 +00003085 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003086 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003087
Dan Gohman52fddd32010-01-26 04:40:18 +00003088 unsigned BitWidth = getTypeSizeInBits(S->getType());
3089 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3090
3091 // If the value has known zeros, the maximum signed value will have those
3092 // known zeros as well.
3093 uint32_t TZ = GetMinTrailingZeros(S);
3094 if (TZ != 0)
3095 ConservativeResult =
3096 ConstantRange(APInt::getSignedMinValue(BitWidth),
3097 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3098
Dan Gohman85b05a22009-07-13 21:35:55 +00003099 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3100 ConstantRange X = getSignedRange(Add->getOperand(0));
3101 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3102 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003103 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003104 }
3105
Dan Gohman85b05a22009-07-13 21:35:55 +00003106 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3107 ConstantRange X = getSignedRange(Mul->getOperand(0));
3108 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3109 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003110 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003111 }
3112
Dan Gohman85b05a22009-07-13 21:35:55 +00003113 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3114 ConstantRange X = getSignedRange(SMax->getOperand(0));
3115 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3116 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003117 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003118 }
Dan Gohman62849c02009-06-24 01:05:09 +00003119
Dan Gohman85b05a22009-07-13 21:35:55 +00003120 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3121 ConstantRange X = getSignedRange(UMax->getOperand(0));
3122 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3123 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003124 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003125 }
Dan Gohman62849c02009-06-24 01:05:09 +00003126
Dan Gohman85b05a22009-07-13 21:35:55 +00003127 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3128 ConstantRange X = getSignedRange(UDiv->getLHS());
3129 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003130 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003131 }
Dan Gohman62849c02009-06-24 01:05:09 +00003132
Dan Gohman85b05a22009-07-13 21:35:55 +00003133 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3134 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003135 return setSignedRange(ZExt,
3136 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003137 }
3138
3139 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3140 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003141 return setSignedRange(SExt,
3142 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003143 }
3144
3145 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3146 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003147 return setSignedRange(Trunc,
3148 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003149 }
3150
Dan Gohman85b05a22009-07-13 21:35:55 +00003151 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003152 // If there's no signed wrap, and all the operands have the same sign or
3153 // zero, the value won't ever change sign.
3154 if (AddRec->hasNoSignedWrap()) {
3155 bool AllNonNeg = true;
3156 bool AllNonPos = true;
3157 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3158 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3159 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3160 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003161 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003162 ConservativeResult = ConservativeResult.intersectWith(
3163 ConstantRange(APInt(BitWidth, 0),
3164 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003165 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003166 ConservativeResult = ConservativeResult.intersectWith(
3167 ConstantRange(APInt::getSignedMinValue(BitWidth),
3168 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003169 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003170
3171 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003172 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003173 const Type *Ty = AddRec->getType();
3174 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003175 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3176 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003177 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3178
3179 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003180 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003181
3182 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003183 ConstantRange StepRange = getSignedRange(Step);
3184 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3185 ConstantRange EndRange =
3186 StartRange.add(MaxBECountRange.multiply(StepRange));
3187
3188 // Check for overflow. This must be done with ConstantRange arithmetic
3189 // because we could be called from within the ScalarEvolution overflow
3190 // checking code.
3191 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3192 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3193 ConstantRange ExtMaxBECountRange =
3194 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3195 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3196 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3197 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003198 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003199
Dan Gohman85b05a22009-07-13 21:35:55 +00003200 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3201 EndRange.getSignedMin());
3202 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3203 EndRange.getSignedMax());
3204 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003205 return setSignedRange(AddRec, ConservativeResult);
3206 return setSignedRange(AddRec,
3207 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003208 }
Dan Gohman62849c02009-06-24 01:05:09 +00003209 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003210
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003211 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003212 }
3213
Dan Gohman2c364ad2009-06-19 23:29:04 +00003214 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3215 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003216 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003217 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003218 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3219 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003220 return setSignedRange(U, ConservativeResult);
3221 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003222 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003223 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003224 }
3225
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003226 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003227}
3228
Chris Lattner53e677a2004-04-02 20:23:17 +00003229/// createSCEV - We know that there is no SCEV for the specified value.
3230/// Analyze the expression.
3231///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003232const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003233 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003234 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003235
Dan Gohman6c459a22008-06-22 19:56:46 +00003236 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003237 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003238 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003239
3240 // Don't attempt to analyze instructions in blocks that aren't
3241 // reachable. Such instructions don't matter, and they aren't required
3242 // to obey basic rules for definitions dominating uses which this
3243 // analysis depends on.
3244 if (!DT->isReachableFromEntry(I->getParent()))
3245 return getUnknown(V);
3246 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003247 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003248 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3249 return getConstant(CI);
3250 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003251 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003252 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3253 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003254 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003255 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003256
Dan Gohmanca178902009-07-17 20:47:02 +00003257 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003258 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003259 case Instruction::Add: {
3260 // The simple thing to do would be to just call getSCEV on both operands
3261 // and call getAddExpr with the result. However if we're looking at a
3262 // bunch of things all added together, this can be quite inefficient,
3263 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3264 // Instead, gather up all the operands and make a single getAddExpr call.
3265 // LLVM IR canonical form means we need only traverse the left operands.
3266 SmallVector<const SCEV *, 4> AddOps;
3267 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003268 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3269 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3270 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3271 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003272 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003273 const SCEV *Op1 = getSCEV(U->getOperand(1));
3274 if (Opcode == Instruction::Sub)
3275 AddOps.push_back(getNegativeSCEV(Op1));
3276 else
3277 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003278 }
3279 AddOps.push_back(getSCEV(U->getOperand(0)));
3280 return getAddExpr(AddOps);
3281 }
3282 case Instruction::Mul: {
3283 // See the Add code above.
3284 SmallVector<const SCEV *, 4> MulOps;
3285 MulOps.push_back(getSCEV(U->getOperand(1)));
3286 for (Value *Op = U->getOperand(0);
3287 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3288 Op = U->getOperand(0)) {
3289 U = cast<Operator>(Op);
3290 MulOps.push_back(getSCEV(U->getOperand(1)));
3291 }
3292 MulOps.push_back(getSCEV(U->getOperand(0)));
3293 return getMulExpr(MulOps);
3294 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003295 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003296 return getUDivExpr(getSCEV(U->getOperand(0)),
3297 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003298 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003299 return getMinusSCEV(getSCEV(U->getOperand(0)),
3300 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003301 case Instruction::And:
3302 // For an expression like x&255 that merely masks off the high bits,
3303 // use zext(trunc(x)) as the SCEV expression.
3304 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003305 if (CI->isNullValue())
3306 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003307 if (CI->isAllOnesValue())
3308 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003309 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003310
3311 // Instcombine's ShrinkDemandedConstant may strip bits out of
3312 // constants, obscuring what would otherwise be a low-bits mask.
3313 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3314 // knew about to reconstruct a low-bits mask value.
3315 unsigned LZ = A.countLeadingZeros();
3316 unsigned BitWidth = A.getBitWidth();
3317 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3318 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3319 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3320
3321 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3322
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003323 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003324 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003325 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003326 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003327 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003328 }
3329 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003330
Dan Gohman6c459a22008-06-22 19:56:46 +00003331 case Instruction::Or:
3332 // If the RHS of the Or is a constant, we may have something like:
3333 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3334 // optimizations will transparently handle this case.
3335 //
3336 // In order for this transformation to be safe, the LHS must be of the
3337 // form X*(2^n) and the Or constant must be less than 2^n.
3338 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003339 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003340 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003341 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003342 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3343 // Build a plain add SCEV.
3344 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3345 // If the LHS of the add was an addrec and it has no-wrap flags,
3346 // transfer the no-wrap flags, since an or won't introduce a wrap.
3347 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3348 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3349 if (OldAR->hasNoUnsignedWrap())
3350 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3351 if (OldAR->hasNoSignedWrap())
3352 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3353 }
3354 return S;
3355 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003356 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003357 break;
3358 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003359 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003360 // If the RHS of the xor is a signbit, then this is just an add.
3361 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003362 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003363 return getAddExpr(getSCEV(U->getOperand(0)),
3364 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003365
3366 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003367 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003368 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003369
3370 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3371 // This is a variant of the check for xor with -1, and it handles
3372 // the case where instcombine has trimmed non-demanded bits out
3373 // of an xor with -1.
3374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3375 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3376 if (BO->getOpcode() == Instruction::And &&
3377 LCI->getValue() == CI->getValue())
3378 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003379 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003380 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003381 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003382 const Type *Z0Ty = Z0->getType();
3383 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3384
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003385 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003386 // mask off the high bits. Complement the operand and
3387 // re-apply the zext.
3388 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3389 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3390
3391 // If C is a single bit, it may be in the sign-bit position
3392 // before the zero-extend. In this case, represent the xor
3393 // using an add, which is equivalent, and re-apply the zext.
3394 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3395 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3396 Trunc.isSignBit())
3397 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3398 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003399 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003400 }
3401 break;
3402
3403 case Instruction::Shl:
3404 // Turn shift left of a constant amount into a multiply.
3405 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003406 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003407
3408 // If the shift count is not less than the bitwidth, the result of
3409 // the shift is undefined. Don't try to analyze it, because the
3410 // resolution chosen here may differ from the resolution chosen in
3411 // other parts of the compiler.
3412 if (SA->getValue().uge(BitWidth))
3413 break;
3414
Owen Andersoneed707b2009-07-24 23:12:02 +00003415 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003416 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003417 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003418 }
3419 break;
3420
Nick Lewycky01eaf802008-07-07 06:15:49 +00003421 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003422 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003423 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003424 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003425
3426 // If the shift count is not less than the bitwidth, the result of
3427 // the shift is undefined. Don't try to analyze it, because the
3428 // resolution chosen here may differ from the resolution chosen in
3429 // other parts of the compiler.
3430 if (SA->getValue().uge(BitWidth))
3431 break;
3432
Owen Andersoneed707b2009-07-24 23:12:02 +00003433 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003434 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003435 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003436 }
3437 break;
3438
Dan Gohman4ee29af2009-04-21 02:26:00 +00003439 case Instruction::AShr:
3440 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3441 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003442 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003443 if (L->getOpcode() == Instruction::Shl &&
3444 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003445 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3446
3447 // If the shift count is not less than the bitwidth, the result of
3448 // the shift is undefined. Don't try to analyze it, because the
3449 // resolution chosen here may differ from the resolution chosen in
3450 // other parts of the compiler.
3451 if (CI->getValue().uge(BitWidth))
3452 break;
3453
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003454 uint64_t Amt = BitWidth - CI->getZExtValue();
3455 if (Amt == BitWidth)
3456 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003457 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003458 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003459 IntegerType::get(getContext(),
3460 Amt)),
3461 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003462 }
3463 break;
3464
Dan Gohman6c459a22008-06-22 19:56:46 +00003465 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003466 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003467
3468 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003469 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003470
3471 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003472 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003473
3474 case Instruction::BitCast:
3475 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003476 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003477 return getSCEV(U->getOperand(0));
3478 break;
3479
Dan Gohman4f8eea82010-02-01 18:27:38 +00003480 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3481 // lead to pointer expressions which cannot safely be expanded to GEPs,
3482 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3483 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003484
Dan Gohman26466c02009-05-08 20:26:55 +00003485 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003486 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003487
Dan Gohman6c459a22008-06-22 19:56:46 +00003488 case Instruction::PHI:
3489 return createNodeForPHI(cast<PHINode>(U));
3490
3491 case Instruction::Select:
3492 // This could be a smax or umax that was lowered earlier.
3493 // Try to recover it.
3494 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3495 Value *LHS = ICI->getOperand(0);
3496 Value *RHS = ICI->getOperand(1);
3497 switch (ICI->getPredicate()) {
3498 case ICmpInst::ICMP_SLT:
3499 case ICmpInst::ICMP_SLE:
3500 std::swap(LHS, RHS);
3501 // fall through
3502 case ICmpInst::ICMP_SGT:
3503 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003504 // a >s b ? a+x : b+x -> smax(a, b)+x
3505 // a >s b ? b+x : a+x -> smin(a, b)+x
3506 if (LHS->getType() == U->getType()) {
3507 const SCEV *LS = getSCEV(LHS);
3508 const SCEV *RS = getSCEV(RHS);
3509 const SCEV *LA = getSCEV(U->getOperand(1));
3510 const SCEV *RA = getSCEV(U->getOperand(2));
3511 const SCEV *LDiff = getMinusSCEV(LA, LS);
3512 const SCEV *RDiff = getMinusSCEV(RA, RS);
3513 if (LDiff == RDiff)
3514 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3515 LDiff = getMinusSCEV(LA, RS);
3516 RDiff = getMinusSCEV(RA, LS);
3517 if (LDiff == RDiff)
3518 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3519 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003520 break;
3521 case ICmpInst::ICMP_ULT:
3522 case ICmpInst::ICMP_ULE:
3523 std::swap(LHS, RHS);
3524 // fall through
3525 case ICmpInst::ICMP_UGT:
3526 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003527 // a >u b ? a+x : b+x -> umax(a, b)+x
3528 // a >u b ? b+x : a+x -> umin(a, b)+x
3529 if (LHS->getType() == U->getType()) {
3530 const SCEV *LS = getSCEV(LHS);
3531 const SCEV *RS = getSCEV(RHS);
3532 const SCEV *LA = getSCEV(U->getOperand(1));
3533 const SCEV *RA = getSCEV(U->getOperand(2));
3534 const SCEV *LDiff = getMinusSCEV(LA, LS);
3535 const SCEV *RDiff = getMinusSCEV(RA, RS);
3536 if (LDiff == RDiff)
3537 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3538 LDiff = getMinusSCEV(LA, RS);
3539 RDiff = getMinusSCEV(RA, LS);
3540 if (LDiff == RDiff)
3541 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3542 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003543 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003544 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003545 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3546 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003547 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003548 cast<ConstantInt>(RHS)->isZero()) {
3549 const SCEV *One = getConstant(LHS->getType(), 1);
3550 const SCEV *LS = getSCEV(LHS);
3551 const SCEV *LA = getSCEV(U->getOperand(1));
3552 const SCEV *RA = getSCEV(U->getOperand(2));
3553 const SCEV *LDiff = getMinusSCEV(LA, LS);
3554 const SCEV *RDiff = getMinusSCEV(RA, One);
3555 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003556 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003557 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003558 break;
3559 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003560 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3561 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003562 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003563 cast<ConstantInt>(RHS)->isZero()) {
3564 const SCEV *One = getConstant(LHS->getType(), 1);
3565 const SCEV *LS = getSCEV(LHS);
3566 const SCEV *LA = getSCEV(U->getOperand(1));
3567 const SCEV *RA = getSCEV(U->getOperand(2));
3568 const SCEV *LDiff = getMinusSCEV(LA, One);
3569 const SCEV *RDiff = getMinusSCEV(RA, LS);
3570 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003571 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003572 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003573 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003574 default:
3575 break;
3576 }
3577 }
3578
3579 default: // We cannot analyze this expression.
3580 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003581 }
3582
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003583 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003584}
3585
3586
3587
3588//===----------------------------------------------------------------------===//
3589// Iteration Count Computation Code
3590//
3591
Dan Gohman46bdfb02009-02-24 18:55:53 +00003592/// getBackedgeTakenCount - If the specified loop has a predictable
3593/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3594/// object. The backedge-taken count is the number of times the loop header
3595/// will be branched to from within the loop. This is one less than the
3596/// trip count of the loop, since it doesn't count the first iteration,
3597/// when the header is branched to from outside the loop.
3598///
3599/// Note that it is not valid to call this method on a loop without a
3600/// loop-invariant backedge-taken count (see
3601/// hasLoopInvariantBackedgeTakenCount).
3602///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003603const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003604 return getBackedgeTakenInfo(L).Exact;
3605}
3606
3607/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3608/// return the least SCEV value that is known never to be less than the
3609/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003610const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003611 return getBackedgeTakenInfo(L).Max;
3612}
3613
Dan Gohman59ae6b92009-07-08 19:23:34 +00003614/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3615/// onto the given Worklist.
3616static void
3617PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3618 BasicBlock *Header = L->getHeader();
3619
3620 // Push all Loop-header PHIs onto the Worklist stack.
3621 for (BasicBlock::iterator I = Header->begin();
3622 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3623 Worklist.push_back(PN);
3624}
3625
Dan Gohmana1af7572009-04-30 20:47:05 +00003626const ScalarEvolution::BackedgeTakenInfo &
3627ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003628 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003629 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003630 // update the value. The temporary CouldNotCompute value tells SCEV
3631 // code elsewhere that it shouldn't attempt to request a new
3632 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003633 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003634 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3635 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003636 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3637 if (BECount.Exact != getCouldNotCompute()) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00003638 assert(isLoopInvariant(BECount.Exact, L) &&
3639 isLoopInvariant(BECount.Max, L) &&
Dan Gohman93dacad2010-01-26 16:46:18 +00003640 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003641 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003642
Dan Gohman01ecca22009-04-27 20:16:15 +00003643 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003644 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003645 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003646 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003647 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003648 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003649 if (isa<PHINode>(L->getHeader()->begin()))
3650 // Only count loops that have phi nodes as not being computable.
3651 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003652 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003653
3654 // Now that we know more about the trip count for this loop, forget any
3655 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003656 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003657 // information. This is similar to the code in forgetLoop, except that
3658 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003659 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003660 SmallVector<Instruction *, 16> Worklist;
3661 PushLoopPHIs(L, Worklist);
3662
3663 SmallPtrSet<Instruction *, 8> Visited;
3664 while (!Worklist.empty()) {
3665 Instruction *I = Worklist.pop_back_val();
3666 if (!Visited.insert(I)) continue;
3667
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003668 ValueExprMapType::iterator It =
3669 ValueExprMap.find(static_cast<Value *>(I));
3670 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003671 const SCEV *Old = It->second;
3672
Dan Gohman59ae6b92009-07-08 19:23:34 +00003673 // SCEVUnknown for a PHI either means that it has an unrecognized
3674 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003675 // by createNodeForPHI. In the former case, additional loop trip
3676 // count information isn't going to change anything. In the later
3677 // case, createNodeForPHI will perform the necessary updates on its
3678 // own when it gets to that point.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003679 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3680 ValuesAtScopes.erase(Old);
Dan Gohman714b5292010-11-17 23:21:44 +00003681 LoopDispositions.erase(Old);
Dan Gohman6678e7b2010-11-17 02:44:44 +00003682 UnsignedRanges.erase(Old);
3683 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003684 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003685 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003686 if (PHINode *PN = dyn_cast<PHINode>(I))
3687 ConstantEvolutionLoopExitValue.erase(PN);
3688 }
3689
3690 PushDefUseChildren(I, Worklist);
3691 }
3692 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003693 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003694 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003695}
3696
Dan Gohman4c7279a2009-10-31 15:04:55 +00003697/// forgetLoop - This method should be called by the client when it has
3698/// changed a loop in a way that may effect ScalarEvolution's ability to
3699/// compute a trip count, or if the loop is deleted.
3700void ScalarEvolution::forgetLoop(const Loop *L) {
3701 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003702 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003703
Dan Gohman4c7279a2009-10-31 15:04:55 +00003704 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003705 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003706 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003707
Dan Gohman59ae6b92009-07-08 19:23:34 +00003708 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003709 while (!Worklist.empty()) {
3710 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003711 if (!Visited.insert(I)) continue;
3712
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003713 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3714 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003715 const SCEV *Old = It->second;
3716 ValuesAtScopes.erase(Old);
Dan Gohman714b5292010-11-17 23:21:44 +00003717 LoopDispositions.erase(Old);
Dan Gohman6678e7b2010-11-17 02:44:44 +00003718 UnsignedRanges.erase(Old);
3719 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003720 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003721 if (PHINode *PN = dyn_cast<PHINode>(I))
3722 ConstantEvolutionLoopExitValue.erase(PN);
3723 }
3724
3725 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003726 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00003727
3728 // Forget all contained loops too, to avoid dangling entries in the
3729 // ValuesAtScopes map.
3730 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3731 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00003732}
3733
Eric Christophere6cbfa62010-07-29 01:25:38 +00003734/// forgetValue - This method should be called by the client when it has
3735/// changed a value in a way that may effect its value, or which may
3736/// disconnect it from a def-use chain linking it to a loop.
3737void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003738 Instruction *I = dyn_cast<Instruction>(V);
3739 if (!I) return;
3740
3741 // Drop information about expressions based on loop-header PHIs.
3742 SmallVector<Instruction *, 16> Worklist;
3743 Worklist.push_back(I);
3744
3745 SmallPtrSet<Instruction *, 8> Visited;
3746 while (!Worklist.empty()) {
3747 I = Worklist.pop_back_val();
3748 if (!Visited.insert(I)) continue;
3749
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003750 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3751 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003752 const SCEV *Old = It->second;
3753 ValuesAtScopes.erase(Old);
Dan Gohman714b5292010-11-17 23:21:44 +00003754 LoopDispositions.erase(Old);
Dan Gohman6678e7b2010-11-17 02:44:44 +00003755 UnsignedRanges.erase(Old);
3756 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003757 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003758 if (PHINode *PN = dyn_cast<PHINode>(I))
3759 ConstantEvolutionLoopExitValue.erase(PN);
3760 }
3761
3762 PushDefUseChildren(I, Worklist);
3763 }
3764}
3765
Dan Gohman46bdfb02009-02-24 18:55:53 +00003766/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3767/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003768ScalarEvolution::BackedgeTakenInfo
3769ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003770 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003771 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003772
Dan Gohmana334aa72009-06-22 00:31:57 +00003773 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003774 const SCEV *BECount = getCouldNotCompute();
3775 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003776 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003777 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3778 BackedgeTakenInfo NewBTI =
3779 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003780
Dan Gohman1c343752009-06-27 21:21:31 +00003781 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003782 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003783 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003784 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003785 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003786 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003787 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003788 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003789 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003790 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003791 }
Dan Gohman1c343752009-06-27 21:21:31 +00003792 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003793 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003794 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003795 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003796 }
3797
3798 return BackedgeTakenInfo(BECount, MaxBECount);
3799}
3800
3801/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3802/// of the specified loop will execute if it exits via the specified block.
3803ScalarEvolution::BackedgeTakenInfo
3804ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3805 BasicBlock *ExitingBlock) {
3806
3807 // Okay, we've chosen an exiting block. See what condition causes us to
3808 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003809 //
3810 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003811 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003812 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003813 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003814
Chris Lattner8b0e3602007-01-07 02:24:26 +00003815 // At this point, we know we have a conditional branch that determines whether
3816 // the loop is exited. However, we don't know if the branch is executed each
3817 // time through the loop. If not, then the execution count of the branch will
3818 // not be equal to the trip count of the loop.
3819 //
3820 // Currently we check for this by checking to see if the Exit branch goes to
3821 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003822 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003823 // loop header. This is common for un-rotated loops.
3824 //
3825 // If both of those tests fail, walk up the unique predecessor chain to the
3826 // header, stopping if there is an edge that doesn't exit the loop. If the
3827 // header is reached, the execution count of the branch will be equal to the
3828 // trip count of the loop.
3829 //
3830 // More extensive analysis could be done to handle more cases here.
3831 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003832 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003833 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003834 ExitBr->getParent() != L->getHeader()) {
3835 // The simple checks failed, try climbing the unique predecessor chain
3836 // up to the header.
3837 bool Ok = false;
3838 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3839 BasicBlock *Pred = BB->getUniquePredecessor();
3840 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003841 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003842 TerminatorInst *PredTerm = Pred->getTerminator();
3843 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3844 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3845 if (PredSucc == BB)
3846 continue;
3847 // If the predecessor has a successor that isn't BB and isn't
3848 // outside the loop, assume the worst.
3849 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003850 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003851 }
3852 if (Pred == L->getHeader()) {
3853 Ok = true;
3854 break;
3855 }
3856 BB = Pred;
3857 }
3858 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003859 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003860 }
3861
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003862 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003863 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3864 ExitBr->getSuccessor(0),
3865 ExitBr->getSuccessor(1));
3866}
3867
3868/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3869/// backedge of the specified loop will execute if its exit condition
3870/// were a conditional branch of ExitCond, TBB, and FBB.
3871ScalarEvolution::BackedgeTakenInfo
3872ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3873 Value *ExitCond,
3874 BasicBlock *TBB,
3875 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003876 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003877 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3878 if (BO->getOpcode() == Instruction::And) {
3879 // Recurse on the operands of the and.
3880 BackedgeTakenInfo BTI0 =
3881 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3882 BackedgeTakenInfo BTI1 =
3883 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003884 const SCEV *BECount = getCouldNotCompute();
3885 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003886 if (L->contains(TBB)) {
3887 // Both conditions must be true for the loop to continue executing.
3888 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003889 if (BTI0.Exact == getCouldNotCompute() ||
3890 BTI1.Exact == getCouldNotCompute())
3891 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003892 else
3893 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003894 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003895 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003896 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003897 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003898 else
3899 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003900 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003901 // Both conditions must be true at the same time for the loop to exit.
3902 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003903 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003904 if (BTI0.Max == BTI1.Max)
3905 MaxBECount = BTI0.Max;
3906 if (BTI0.Exact == BTI1.Exact)
3907 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003908 }
3909
3910 return BackedgeTakenInfo(BECount, MaxBECount);
3911 }
3912 if (BO->getOpcode() == Instruction::Or) {
3913 // Recurse on the operands of the or.
3914 BackedgeTakenInfo BTI0 =
3915 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3916 BackedgeTakenInfo BTI1 =
3917 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003918 const SCEV *BECount = getCouldNotCompute();
3919 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003920 if (L->contains(FBB)) {
3921 // Both conditions must be false for the loop to continue executing.
3922 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003923 if (BTI0.Exact == getCouldNotCompute() ||
3924 BTI1.Exact == getCouldNotCompute())
3925 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003926 else
3927 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003928 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003929 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003930 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003931 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003932 else
3933 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003934 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003935 // Both conditions must be false at the same time for the loop to exit.
3936 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003937 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003938 if (BTI0.Max == BTI1.Max)
3939 MaxBECount = BTI0.Max;
3940 if (BTI0.Exact == BTI1.Exact)
3941 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003942 }
3943
3944 return BackedgeTakenInfo(BECount, MaxBECount);
3945 }
3946 }
3947
3948 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003949 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003950 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3951 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003952
Dan Gohman00cb5b72010-02-19 18:12:07 +00003953 // Check for a constant condition. These are normally stripped out by
3954 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3955 // preserve the CFG and is temporarily leaving constant conditions
3956 // in place.
3957 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3958 if (L->contains(FBB) == !CI->getZExtValue())
3959 // The backedge is always taken.
3960 return getCouldNotCompute();
3961 else
3962 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003963 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003964 }
3965
Eli Friedman361e54d2009-05-09 12:32:42 +00003966 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003967 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3968}
3969
3970/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3971/// backedge of the specified loop will execute if its exit condition
3972/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3973ScalarEvolution::BackedgeTakenInfo
3974ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3975 ICmpInst *ExitCond,
3976 BasicBlock *TBB,
3977 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003978
Reid Spencere4d87aa2006-12-23 06:05:41 +00003979 // If the condition was exit on true, convert the condition to exit on false
3980 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003981 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003982 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003983 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003985
3986 // Handle common loops like: for (X = "string"; *X; ++X)
3987 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3988 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003989 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003990 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003991 if (ItCnt.hasAnyInfo())
3992 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003993 }
3994
Dan Gohman0bba49c2009-07-07 17:06:11 +00003995 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3996 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003997
3998 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003999 LHS = getSCEVAtScope(LHS, L);
4000 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004001
Dan Gohman64a845e2009-06-24 04:48:43 +00004002 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004003 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00004004 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004005 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004006 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004007 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004008 }
4009
Dan Gohman03557dc2010-05-03 16:35:17 +00004010 // Simplify the operands before analyzing them.
4011 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4012
Chris Lattner53e677a2004-04-02 20:23:17 +00004013 // If we have a comparison of a chrec against a constant, try to use value
4014 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004015 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4016 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004017 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004018 // Form the constant range.
4019 ConstantRange CompRange(
4020 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004021
Dan Gohman0bba49c2009-07-07 17:06:11 +00004022 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004023 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004024 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004025
Chris Lattner53e677a2004-04-02 20:23:17 +00004026 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004027 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004028 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004029 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4030 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004031 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004032 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004033 case ICmpInst::ICMP_EQ: { // while (X == Y)
4034 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004035 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4036 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004037 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004038 }
4039 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004040 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4041 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004042 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004043 }
4044 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004045 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4046 getNotSCEV(RHS), L, true);
4047 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004048 break;
4049 }
4050 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004051 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4052 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004053 break;
4054 }
4055 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004056 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4057 getNotSCEV(RHS), L, false);
4058 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004059 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004060 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004061 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004062#if 0
David Greene25e0e872009-12-23 22:18:14 +00004063 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004064 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004065 dbgs() << "[unsigned] ";
4066 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004067 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004068 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004069#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004070 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004071 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004072 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004073 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004074}
4075
Chris Lattner673e02b2004-10-12 01:49:27 +00004076static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004077EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4078 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004079 const SCEV *InVal = SE.getConstant(C);
4080 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004081 assert(isa<SCEVConstant>(Val) &&
4082 "Evaluation of SCEV at constant didn't fold correctly?");
4083 return cast<SCEVConstant>(Val)->getValue();
4084}
4085
4086/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4087/// and a GEP expression (missing the pointer index) indexing into it, return
4088/// the addressed element of the initializer or null if the index expression is
4089/// invalid.
4090static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004091GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004092 const std::vector<ConstantInt*> &Indices) {
4093 Constant *Init = GV->getInitializer();
4094 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004095 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004096 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4097 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4098 Init = cast<Constant>(CS->getOperand(Idx));
4099 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4100 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4101 Init = cast<Constant>(CA->getOperand(Idx));
4102 } else if (isa<ConstantAggregateZero>(Init)) {
4103 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4104 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004105 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004106 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4107 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004108 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004109 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004110 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004111 }
4112 return 0;
4113 } else {
4114 return 0; // Unknown initializer type
4115 }
4116 }
4117 return Init;
4118}
4119
Dan Gohman46bdfb02009-02-24 18:55:53 +00004120/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4121/// 'icmp op load X, cst', try to see if we can compute the backedge
4122/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004123ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004124ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4125 LoadInst *LI,
4126 Constant *RHS,
4127 const Loop *L,
4128 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004129 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004130
4131 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004132 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004133 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004134 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004135
4136 // Make sure that it is really a constant global we are gepping, with an
4137 // initializer, and make sure the first IDX is really 0.
4138 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004139 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004140 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4141 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004142 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004143
4144 // Okay, we allow one non-constant index into the GEP instruction.
4145 Value *VarIdx = 0;
4146 std::vector<ConstantInt*> Indexes;
4147 unsigned VarIdxNum = 0;
4148 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4149 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4150 Indexes.push_back(CI);
4151 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004152 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004153 VarIdx = GEP->getOperand(i);
4154 VarIdxNum = i-2;
4155 Indexes.push_back(0);
4156 }
4157
4158 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4159 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004160 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004161 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004162
4163 // We can only recognize very limited forms of loop index expressions, in
4164 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004165 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004166 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004167 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4168 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004169 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004170
4171 unsigned MaxSteps = MaxBruteForceIterations;
4172 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004173 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004174 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004175 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004176
4177 // Form the GEP offset.
4178 Indexes[VarIdxNum] = Val;
4179
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004180 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004181 if (Result == 0) break; // Cannot compute!
4182
4183 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004184 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004185 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004186 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004187#if 0
David Greene25e0e872009-12-23 22:18:14 +00004188 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004189 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4190 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004191#endif
4192 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004193 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004194 }
4195 }
Dan Gohman1c343752009-06-27 21:21:31 +00004196 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004197}
4198
4199
Chris Lattner3221ad02004-04-17 22:58:41 +00004200/// CanConstantFold - Return true if we can constant fold an instruction of the
4201/// specified type, assuming that all operands were constants.
4202static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004203 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004204 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4205 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004206
Chris Lattner3221ad02004-04-17 22:58:41 +00004207 if (const CallInst *CI = dyn_cast<CallInst>(I))
4208 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004209 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004210 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004211}
4212
Chris Lattner3221ad02004-04-17 22:58:41 +00004213/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4214/// in the loop that V is derived from. We allow arbitrary operations along the
4215/// way, but the operands of an operation must either be constants or a value
4216/// derived from a constant PHI. If this expression does not fit with these
4217/// constraints, return null.
4218static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4219 // If this is not an instruction, or if this is an instruction outside of the
4220 // loop, it can't be derived from a loop PHI.
4221 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004222 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004223
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004224 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004225 if (L->getHeader() == I->getParent())
4226 return PN;
4227 else
4228 // We don't currently keep track of the control flow needed to evaluate
4229 // PHIs, so we cannot handle PHIs inside of loops.
4230 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004231 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004232
4233 // If we won't be able to constant fold this expression even if the operands
4234 // are constants, return early.
4235 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004236
Chris Lattner3221ad02004-04-17 22:58:41 +00004237 // Otherwise, we can evaluate this instruction if all of its operands are
4238 // constant or derived from a PHI node themselves.
4239 PHINode *PHI = 0;
4240 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004241 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004242 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4243 if (P == 0) return 0; // Not evolving from PHI
4244 if (PHI == 0)
4245 PHI = P;
4246 else if (PHI != P)
4247 return 0; // Evolving from multiple different PHIs.
4248 }
4249
4250 // This is a expression evolving from a constant PHI!
4251 return PHI;
4252}
4253
4254/// EvaluateExpression - Given an expression that passes the
4255/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4256/// in the loop has the value PHIVal. If we can't fold this expression for some
4257/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004258static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4259 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004260 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004261 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004262 Instruction *I = cast<Instruction>(V);
4263
Dan Gohman9d4588f2010-06-22 13:15:46 +00004264 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004265
4266 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004267 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004268 if (Operands[i] == 0) return 0;
4269 }
4270
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004271 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004272 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004273 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004274 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004275 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004276}
4277
4278/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4279/// in the header of its containing loop, we know the loop executes a
4280/// constant number of times, and the PHI node is just a recurrence
4281/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004282Constant *
4283ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004284 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004285 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004286 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004287 ConstantEvolutionLoopExitValue.find(PN);
4288 if (I != ConstantEvolutionLoopExitValue.end())
4289 return I->second;
4290
Dan Gohmane0567812010-04-08 23:03:40 +00004291 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004292 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4293
4294 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4295
4296 // Since the loop is canonicalized, the PHI node must have two entries. One
4297 // entry must be a constant (coming in from outside of the loop), and the
4298 // second must be derived from the same PHI.
4299 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4300 Constant *StartCST =
4301 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4302 if (StartCST == 0)
4303 return RetVal = 0; // Must be a constant.
4304
4305 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004306 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4307 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004308 return RetVal = 0; // Not derived from same PHI.
4309
4310 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004311 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004312 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004313
Dan Gohman46bdfb02009-02-24 18:55:53 +00004314 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004315 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004316 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4317 if (IterationNum == NumIterations)
4318 return RetVal = PHIVal; // Got exit value!
4319
4320 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004321 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004322 if (NextPHI == PHIVal)
4323 return RetVal = NextPHI; // Stopped evolving!
4324 if (NextPHI == 0)
4325 return 0; // Couldn't evaluate!
4326 PHIVal = NextPHI;
4327 }
4328}
4329
Dan Gohman07ad19b2009-07-27 16:09:48 +00004330/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004331/// constant number of times (the condition evolves only from constants),
4332/// try to evaluate a few iterations of the loop until we get the exit
4333/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004334/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004335const SCEV *
4336ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4337 Value *Cond,
4338 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004339 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004340 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004341
Dan Gohmanb92654d2010-06-19 14:17:24 +00004342 // If the loop is canonicalized, the PHI will have exactly two entries.
4343 // That's the only form we support here.
4344 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4345
4346 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004347 // second must be derived from the same PHI.
4348 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4349 Constant *StartCST =
4350 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004351 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004352
4353 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004354 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4355 !isa<Constant>(BEValue))
4356 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004357
4358 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4359 // the loop symbolically to determine when the condition gets a value of
4360 // "ExitWhen".
4361 unsigned IterationNum = 0;
4362 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4363 for (Constant *PHIVal = StartCST;
4364 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004365 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004366 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004367
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004368 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004369 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004370
Reid Spencere8019bb2007-03-01 07:25:48 +00004371 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004372 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004373 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004374 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004375
Chris Lattner3221ad02004-04-17 22:58:41 +00004376 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004377 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004378 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004379 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004380 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004381 }
4382
4383 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004384 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004385}
4386
Dan Gohmane7125f42009-09-03 15:00:26 +00004387/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004388/// at the specified scope in the program. The L value specifies a loop
4389/// nest to evaluate the expression at, where null is the top-level or a
4390/// specified loop is immediately inside of the loop.
4391///
4392/// This method can be used to compute the exit value for a variable defined
4393/// in a loop by querying what the value will hold in the parent loop.
4394///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004395/// In the case that a relevant loop exit value cannot be computed, the
4396/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004397const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004398 // Check to see if we've folded this expression at this loop before.
4399 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4400 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4401 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4402 if (!Pair.second)
4403 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004404
Dan Gohman42214892009-08-31 21:15:23 +00004405 // Otherwise compute it.
4406 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004407 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004408 return C;
4409}
4410
4411const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004412 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004413
Nick Lewycky3e630762008-02-20 06:48:22 +00004414 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004415 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004416 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004417 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004418 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004419 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4420 if (PHINode *PN = dyn_cast<PHINode>(I))
4421 if (PN->getParent() == LI->getHeader()) {
4422 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004423 // to see if the loop that contains it has a known backedge-taken
4424 // count. If so, we may be able to force computation of the exit
4425 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004426 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004427 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004428 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004429 // Okay, we know how many times the containing loop executes. If
4430 // this is a constant evolving PHI node, get the final value at
4431 // the specified iteration number.
4432 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004433 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004434 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004435 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004436 }
4437 }
4438
Reid Spencer09906f32006-12-04 21:33:23 +00004439 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004440 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004441 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004442 // result. This is particularly useful for computing loop exit values.
4443 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004444 SmallVector<Constant *, 4> Operands;
4445 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004446 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4447 Value *Op = I->getOperand(i);
4448 if (Constant *C = dyn_cast<Constant>(Op)) {
4449 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004450 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004451 }
Dan Gohman11046452010-06-29 23:43:06 +00004452
4453 // If any of the operands is non-constant and if they are
4454 // non-integer and non-pointer, don't even try to analyze them
4455 // with scev techniques.
4456 if (!isSCEVable(Op->getType()))
4457 return V;
4458
4459 const SCEV *OrigV = getSCEV(Op);
4460 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4461 MadeImprovement |= OrigV != OpV;
4462
4463 Constant *C = 0;
4464 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4465 C = SC->getValue();
4466 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4467 C = dyn_cast<Constant>(SU->getValue());
4468 if (!C) return V;
4469 if (C->getType() != Op->getType())
4470 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4471 Op->getType(),
4472 false),
4473 C, Op->getType());
4474 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004475 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004476
Dan Gohman11046452010-06-29 23:43:06 +00004477 // Check to see if getSCEVAtScope actually made an improvement.
4478 if (MadeImprovement) {
4479 Constant *C = 0;
4480 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4481 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4482 Operands[0], Operands[1], TD);
4483 else
4484 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4485 &Operands[0], Operands.size(), TD);
4486 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004487 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004488 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004489 }
4490 }
4491
4492 // This is some other type of SCEVUnknown, just return it.
4493 return V;
4494 }
4495
Dan Gohman622ed672009-05-04 22:02:23 +00004496 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004497 // Avoid performing the look-up in the common case where the specified
4498 // expression has no loop-variant portions.
4499 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004500 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004501 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004502 // Okay, at least one of these operands is loop variant but might be
4503 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004504 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4505 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004506 NewOps.push_back(OpAtScope);
4507
4508 for (++i; i != e; ++i) {
4509 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004510 NewOps.push_back(OpAtScope);
4511 }
4512 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004513 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004514 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004515 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004516 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004517 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004518 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004519 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004520 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004521 }
4522 }
4523 // If we got here, all operands are loop invariant.
4524 return Comm;
4525 }
4526
Dan Gohman622ed672009-05-04 22:02:23 +00004527 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004528 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4529 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004530 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4531 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004532 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004533 }
4534
4535 // If this is a loop recurrence for a loop that does not contain L, then we
4536 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004537 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004538 // First, attempt to evaluate each operand.
4539 // Avoid performing the look-up in the common case where the specified
4540 // expression has no loop-variant portions.
4541 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4542 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4543 if (OpAtScope == AddRec->getOperand(i))
4544 continue;
4545
4546 // Okay, at least one of these operands is loop variant but might be
4547 // foldable. Build a new instance of the folded commutative expression.
4548 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4549 AddRec->op_begin()+i);
4550 NewOps.push_back(OpAtScope);
4551 for (++i; i != e; ++i)
4552 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4553
4554 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4555 break;
4556 }
4557
4558 // If the scope is outside the addrec's loop, evaluate it by using the
4559 // loop exit value of the addrec.
4560 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004561 // To evaluate this recurrence, we need to know how many times the AddRec
4562 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004563 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004564 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004565
Eli Friedmanb42a6262008-08-04 23:49:06 +00004566 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004567 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004568 }
Dan Gohman11046452010-06-29 23:43:06 +00004569
Dan Gohmand594e6f2009-05-24 23:25:42 +00004570 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004571 }
4572
Dan Gohman622ed672009-05-04 22:02:23 +00004573 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004574 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004575 if (Op == Cast->getOperand())
4576 return Cast; // must be loop invariant
4577 return getZeroExtendExpr(Op, Cast->getType());
4578 }
4579
Dan Gohman622ed672009-05-04 22:02:23 +00004580 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004581 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004582 if (Op == Cast->getOperand())
4583 return Cast; // must be loop invariant
4584 return getSignExtendExpr(Op, Cast->getType());
4585 }
4586
Dan Gohman622ed672009-05-04 22:02:23 +00004587 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004588 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004589 if (Op == Cast->getOperand())
4590 return Cast; // must be loop invariant
4591 return getTruncateExpr(Op, Cast->getType());
4592 }
4593
Torok Edwinc23197a2009-07-14 16:55:14 +00004594 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004595 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004596}
4597
Dan Gohman66a7e852009-05-08 20:38:54 +00004598/// getSCEVAtScope - This is a convenience function which does
4599/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004600const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004601 return getSCEVAtScope(getSCEV(V), L);
4602}
4603
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004604/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4605/// following equation:
4606///
4607/// A * X = B (mod N)
4608///
4609/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4610/// A and B isn't important.
4611///
4612/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004613static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004614 ScalarEvolution &SE) {
4615 uint32_t BW = A.getBitWidth();
4616 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4617 assert(A != 0 && "A must be non-zero.");
4618
4619 // 1. D = gcd(A, N)
4620 //
4621 // The gcd of A and N may have only one prime factor: 2. The number of
4622 // trailing zeros in A is its multiplicity
4623 uint32_t Mult2 = A.countTrailingZeros();
4624 // D = 2^Mult2
4625
4626 // 2. Check if B is divisible by D.
4627 //
4628 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4629 // is not less than multiplicity of this prime factor for D.
4630 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004631 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004632
4633 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4634 // modulo (N / D).
4635 //
4636 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4637 // bit width during computations.
4638 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4639 APInt Mod(BW + 1, 0);
4640 Mod.set(BW - Mult2); // Mod = N / D
4641 APInt I = AD.multiplicativeInverse(Mod);
4642
4643 // 4. Compute the minimum unsigned root of the equation:
4644 // I * (B / D) mod (N / D)
4645 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4646
4647 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4648 // bits.
4649 return SE.getConstant(Result.trunc(BW));
4650}
Chris Lattner53e677a2004-04-02 20:23:17 +00004651
4652/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4653/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4654/// might be the same) or two SCEVCouldNotCompute objects.
4655///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004656static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004657SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004658 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004659 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4660 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4661 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004662
Chris Lattner53e677a2004-04-02 20:23:17 +00004663 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004664 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004665 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004666 return std::make_pair(CNC, CNC);
4667 }
4668
Reid Spencere8019bb2007-03-01 07:25:48 +00004669 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004670 const APInt &L = LC->getValue()->getValue();
4671 const APInt &M = MC->getValue()->getValue();
4672 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004673 APInt Two(BitWidth, 2);
4674 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004675
Dan Gohman64a845e2009-06-24 04:48:43 +00004676 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004677 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004678 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004679 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4680 // The B coefficient is M-N/2
4681 APInt B(M);
4682 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004683
Reid Spencere8019bb2007-03-01 07:25:48 +00004684 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004685 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004686
Reid Spencere8019bb2007-03-01 07:25:48 +00004687 // Compute the B^2-4ac term.
4688 APInt SqrtTerm(B);
4689 SqrtTerm *= B;
4690 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004691
Reid Spencere8019bb2007-03-01 07:25:48 +00004692 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4693 // integer value or else APInt::sqrt() will assert.
4694 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004695
Dan Gohman64a845e2009-06-24 04:48:43 +00004696 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004697 // The divisions must be performed as signed divisions.
4698 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004699 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004700 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004701 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004702 return std::make_pair(CNC, CNC);
4703 }
4704
Owen Andersone922c022009-07-22 00:24:57 +00004705 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004706
4707 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004708 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004709 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004710 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004711
Dan Gohman64a845e2009-06-24 04:48:43 +00004712 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004713 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004714 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004715}
4716
4717/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004718/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004719ScalarEvolution::BackedgeTakenInfo
4720ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004721 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004722 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004723 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004724 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004725 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004726 }
4727
Dan Gohman35738ac2009-05-04 22:30:44 +00004728 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004729 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004730 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004731
4732 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004733 // If this is an affine expression, the execution count of this branch is
4734 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004735 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004736 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004737 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004738 // equivalent to:
4739 //
4740 // Step*N = -Start (mod 2^BW)
4741 //
4742 // where BW is the common bit width of Start and Step.
4743
Chris Lattner53e677a2004-04-02 20:23:17 +00004744 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004745 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4746 L->getParentLoop());
4747 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4748 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004749
Dan Gohman622ed672009-05-04 22:02:23 +00004750 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004751 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004752
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004753 // First, handle unitary steps.
4754 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004755 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004756 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4757 return Start; // N = Start (as unsigned)
4758
4759 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004760 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004761 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004762 -StartC->getValue()->getValue(),
4763 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004764 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004765 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004766 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4767 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004768 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004769 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004770 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4771 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004772 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004773#if 0
David Greene25e0e872009-12-23 22:18:14 +00004774 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004775 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004776#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004777 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004778 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004779 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004780 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004781 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004782 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004783
Chris Lattner53e677a2004-04-02 20:23:17 +00004784 // We can only use this value if the chrec ends up with an exact zero
4785 // value at this index. When solving for "X*X != 5", for example, we
4786 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004787 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004788 if (Val->isZero())
4789 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004790 }
4791 }
4792 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004793
Dan Gohman1c343752009-06-27 21:21:31 +00004794 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004795}
4796
4797/// HowFarToNonZero - Return the number of times a backedge checking the
4798/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004799/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004800ScalarEvolution::BackedgeTakenInfo
4801ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004802 // Loops that look like: while (X == 0) are very strange indeed. We don't
4803 // handle them yet except for the trivial case. This could be expanded in the
4804 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004805
Chris Lattner53e677a2004-04-02 20:23:17 +00004806 // If the value is a constant, check to see if it is known to be non-zero
4807 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004808 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004809 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004810 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004811 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004812 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004813
Chris Lattner53e677a2004-04-02 20:23:17 +00004814 // We could implement others, but I really doubt anyone writes loops like
4815 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004816 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004817}
4818
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004819/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4820/// (which may not be an immediate predecessor) which has exactly one
4821/// successor from which BB is reachable, or null if no such block is
4822/// found.
4823///
Dan Gohman005752b2010-04-15 16:19:08 +00004824std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004825ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004826 // If the block has a unique predecessor, then there is no path from the
4827 // predecessor to the block that does not go through the direct edge
4828 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004829 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004830 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004831
4832 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004833 // If the header has a unique predecessor outside the loop, it must be
4834 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004835 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004836 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004837
Dan Gohman005752b2010-04-15 16:19:08 +00004838 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004839}
4840
Dan Gohman763bad12009-06-20 00:35:32 +00004841/// HasSameValue - SCEV structural equivalence is usually sufficient for
4842/// testing whether two expressions are equal, however for the purposes of
4843/// looking for a condition guarding a loop, it can be useful to be a little
4844/// more general, since a front-end may have replicated the controlling
4845/// expression.
4846///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004847static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004848 // Quick check to see if they are the same SCEV.
4849 if (A == B) return true;
4850
4851 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4852 // two different instructions with the same value. Check for this case.
4853 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4854 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4855 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4856 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004857 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004858 return true;
4859
4860 // Otherwise assume they may have a different value.
4861 return false;
4862}
4863
Dan Gohmane9796502010-04-24 01:28:42 +00004864/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4865/// predicate Pred. Return true iff any changes were made.
4866///
4867bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4868 const SCEV *&LHS, const SCEV *&RHS) {
4869 bool Changed = false;
4870
4871 // Canonicalize a constant to the right side.
4872 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4873 // Check for both operands constant.
4874 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4875 if (ConstantExpr::getICmp(Pred,
4876 LHSC->getValue(),
4877 RHSC->getValue())->isNullValue())
4878 goto trivially_false;
4879 else
4880 goto trivially_true;
4881 }
4882 // Otherwise swap the operands to put the constant on the right.
4883 std::swap(LHS, RHS);
4884 Pred = ICmpInst::getSwappedPredicate(Pred);
4885 Changed = true;
4886 }
4887
4888 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004889 // addrec's loop, put the addrec on the left. Also make a dominance check,
4890 // as both operands could be addrecs loop-invariant in each other's loop.
4891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4892 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00004893 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00004894 std::swap(LHS, RHS);
4895 Pred = ICmpInst::getSwappedPredicate(Pred);
4896 Changed = true;
4897 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004898 }
Dan Gohmane9796502010-04-24 01:28:42 +00004899
4900 // If there's a constant operand, canonicalize comparisons with boundary
4901 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4902 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4903 const APInt &RA = RC->getValue()->getValue();
4904 switch (Pred) {
4905 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4906 case ICmpInst::ICMP_EQ:
4907 case ICmpInst::ICMP_NE:
4908 break;
4909 case ICmpInst::ICMP_UGE:
4910 if ((RA - 1).isMinValue()) {
4911 Pred = ICmpInst::ICMP_NE;
4912 RHS = getConstant(RA - 1);
4913 Changed = true;
4914 break;
4915 }
4916 if (RA.isMaxValue()) {
4917 Pred = ICmpInst::ICMP_EQ;
4918 Changed = true;
4919 break;
4920 }
4921 if (RA.isMinValue()) goto trivially_true;
4922
4923 Pred = ICmpInst::ICMP_UGT;
4924 RHS = getConstant(RA - 1);
4925 Changed = true;
4926 break;
4927 case ICmpInst::ICMP_ULE:
4928 if ((RA + 1).isMaxValue()) {
4929 Pred = ICmpInst::ICMP_NE;
4930 RHS = getConstant(RA + 1);
4931 Changed = true;
4932 break;
4933 }
4934 if (RA.isMinValue()) {
4935 Pred = ICmpInst::ICMP_EQ;
4936 Changed = true;
4937 break;
4938 }
4939 if (RA.isMaxValue()) goto trivially_true;
4940
4941 Pred = ICmpInst::ICMP_ULT;
4942 RHS = getConstant(RA + 1);
4943 Changed = true;
4944 break;
4945 case ICmpInst::ICMP_SGE:
4946 if ((RA - 1).isMinSignedValue()) {
4947 Pred = ICmpInst::ICMP_NE;
4948 RHS = getConstant(RA - 1);
4949 Changed = true;
4950 break;
4951 }
4952 if (RA.isMaxSignedValue()) {
4953 Pred = ICmpInst::ICMP_EQ;
4954 Changed = true;
4955 break;
4956 }
4957 if (RA.isMinSignedValue()) goto trivially_true;
4958
4959 Pred = ICmpInst::ICMP_SGT;
4960 RHS = getConstant(RA - 1);
4961 Changed = true;
4962 break;
4963 case ICmpInst::ICMP_SLE:
4964 if ((RA + 1).isMaxSignedValue()) {
4965 Pred = ICmpInst::ICMP_NE;
4966 RHS = getConstant(RA + 1);
4967 Changed = true;
4968 break;
4969 }
4970 if (RA.isMinSignedValue()) {
4971 Pred = ICmpInst::ICMP_EQ;
4972 Changed = true;
4973 break;
4974 }
4975 if (RA.isMaxSignedValue()) goto trivially_true;
4976
4977 Pred = ICmpInst::ICMP_SLT;
4978 RHS = getConstant(RA + 1);
4979 Changed = true;
4980 break;
4981 case ICmpInst::ICMP_UGT:
4982 if (RA.isMinValue()) {
4983 Pred = ICmpInst::ICMP_NE;
4984 Changed = true;
4985 break;
4986 }
4987 if ((RA + 1).isMaxValue()) {
4988 Pred = ICmpInst::ICMP_EQ;
4989 RHS = getConstant(RA + 1);
4990 Changed = true;
4991 break;
4992 }
4993 if (RA.isMaxValue()) goto trivially_false;
4994 break;
4995 case ICmpInst::ICMP_ULT:
4996 if (RA.isMaxValue()) {
4997 Pred = ICmpInst::ICMP_NE;
4998 Changed = true;
4999 break;
5000 }
5001 if ((RA - 1).isMinValue()) {
5002 Pred = ICmpInst::ICMP_EQ;
5003 RHS = getConstant(RA - 1);
5004 Changed = true;
5005 break;
5006 }
5007 if (RA.isMinValue()) goto trivially_false;
5008 break;
5009 case ICmpInst::ICMP_SGT:
5010 if (RA.isMinSignedValue()) {
5011 Pred = ICmpInst::ICMP_NE;
5012 Changed = true;
5013 break;
5014 }
5015 if ((RA + 1).isMaxSignedValue()) {
5016 Pred = ICmpInst::ICMP_EQ;
5017 RHS = getConstant(RA + 1);
5018 Changed = true;
5019 break;
5020 }
5021 if (RA.isMaxSignedValue()) goto trivially_false;
5022 break;
5023 case ICmpInst::ICMP_SLT:
5024 if (RA.isMaxSignedValue()) {
5025 Pred = ICmpInst::ICMP_NE;
5026 Changed = true;
5027 break;
5028 }
5029 if ((RA - 1).isMinSignedValue()) {
5030 Pred = ICmpInst::ICMP_EQ;
5031 RHS = getConstant(RA - 1);
5032 Changed = true;
5033 break;
5034 }
5035 if (RA.isMinSignedValue()) goto trivially_false;
5036 break;
5037 }
5038 }
5039
5040 // Check for obvious equality.
5041 if (HasSameValue(LHS, RHS)) {
5042 if (ICmpInst::isTrueWhenEqual(Pred))
5043 goto trivially_true;
5044 if (ICmpInst::isFalseWhenEqual(Pred))
5045 goto trivially_false;
5046 }
5047
Dan Gohman03557dc2010-05-03 16:35:17 +00005048 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5049 // adding or subtracting 1 from one of the operands.
5050 switch (Pred) {
5051 case ICmpInst::ICMP_SLE:
5052 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5053 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5054 /*HasNUW=*/false, /*HasNSW=*/true);
5055 Pred = ICmpInst::ICMP_SLT;
5056 Changed = true;
5057 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005058 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005059 /*HasNUW=*/false, /*HasNSW=*/true);
5060 Pred = ICmpInst::ICMP_SLT;
5061 Changed = true;
5062 }
5063 break;
5064 case ICmpInst::ICMP_SGE:
5065 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005066 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005067 /*HasNUW=*/false, /*HasNSW=*/true);
5068 Pred = ICmpInst::ICMP_SGT;
5069 Changed = true;
5070 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5071 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5072 /*HasNUW=*/false, /*HasNSW=*/true);
5073 Pred = ICmpInst::ICMP_SGT;
5074 Changed = true;
5075 }
5076 break;
5077 case ICmpInst::ICMP_ULE:
5078 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005079 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005080 /*HasNUW=*/true, /*HasNSW=*/false);
5081 Pred = ICmpInst::ICMP_ULT;
5082 Changed = true;
5083 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005084 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005085 /*HasNUW=*/true, /*HasNSW=*/false);
5086 Pred = ICmpInst::ICMP_ULT;
5087 Changed = true;
5088 }
5089 break;
5090 case ICmpInst::ICMP_UGE:
5091 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005092 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005093 /*HasNUW=*/true, /*HasNSW=*/false);
5094 Pred = ICmpInst::ICMP_UGT;
5095 Changed = true;
5096 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005097 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005098 /*HasNUW=*/true, /*HasNSW=*/false);
5099 Pred = ICmpInst::ICMP_UGT;
5100 Changed = true;
5101 }
5102 break;
5103 default:
5104 break;
5105 }
5106
Dan Gohmane9796502010-04-24 01:28:42 +00005107 // TODO: More simplifications are possible here.
5108
5109 return Changed;
5110
5111trivially_true:
5112 // Return 0 == 0.
5113 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5114 Pred = ICmpInst::ICMP_EQ;
5115 return true;
5116
5117trivially_false:
5118 // Return 0 != 0.
5119 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5120 Pred = ICmpInst::ICMP_NE;
5121 return true;
5122}
5123
Dan Gohman85b05a22009-07-13 21:35:55 +00005124bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5125 return getSignedRange(S).getSignedMax().isNegative();
5126}
5127
5128bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5129 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5130}
5131
5132bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5133 return !getSignedRange(S).getSignedMin().isNegative();
5134}
5135
5136bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5137 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5138}
5139
5140bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5141 return isKnownNegative(S) || isKnownPositive(S);
5142}
5143
5144bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5145 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005146 // Canonicalize the inputs first.
5147 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5148
Dan Gohman53c66ea2010-04-11 22:16:48 +00005149 // If LHS or RHS is an addrec, check to see if the condition is true in
5150 // every iteration of the loop.
5151 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5152 if (isLoopEntryGuardedByCond(
5153 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5154 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005155 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005156 return true;
5157 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5158 if (isLoopEntryGuardedByCond(
5159 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5160 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005161 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005162 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005163
Dan Gohman53c66ea2010-04-11 22:16:48 +00005164 // Otherwise see what can be done with known constant ranges.
5165 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5166}
5167
5168bool
5169ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5170 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005171 if (HasSameValue(LHS, RHS))
5172 return ICmpInst::isTrueWhenEqual(Pred);
5173
Dan Gohman53c66ea2010-04-11 22:16:48 +00005174 // This code is split out from isKnownPredicate because it is called from
5175 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005176 switch (Pred) {
5177 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005178 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005179 break;
5180 case ICmpInst::ICMP_SGT:
5181 Pred = ICmpInst::ICMP_SLT;
5182 std::swap(LHS, RHS);
5183 case ICmpInst::ICMP_SLT: {
5184 ConstantRange LHSRange = getSignedRange(LHS);
5185 ConstantRange RHSRange = getSignedRange(RHS);
5186 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5187 return true;
5188 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5189 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005190 break;
5191 }
5192 case ICmpInst::ICMP_SGE:
5193 Pred = ICmpInst::ICMP_SLE;
5194 std::swap(LHS, RHS);
5195 case ICmpInst::ICMP_SLE: {
5196 ConstantRange LHSRange = getSignedRange(LHS);
5197 ConstantRange RHSRange = getSignedRange(RHS);
5198 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5199 return true;
5200 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5201 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005202 break;
5203 }
5204 case ICmpInst::ICMP_UGT:
5205 Pred = ICmpInst::ICMP_ULT;
5206 std::swap(LHS, RHS);
5207 case ICmpInst::ICMP_ULT: {
5208 ConstantRange LHSRange = getUnsignedRange(LHS);
5209 ConstantRange RHSRange = getUnsignedRange(RHS);
5210 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5211 return true;
5212 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5213 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005214 break;
5215 }
5216 case ICmpInst::ICMP_UGE:
5217 Pred = ICmpInst::ICMP_ULE;
5218 std::swap(LHS, RHS);
5219 case ICmpInst::ICMP_ULE: {
5220 ConstantRange LHSRange = getUnsignedRange(LHS);
5221 ConstantRange RHSRange = getUnsignedRange(RHS);
5222 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5223 return true;
5224 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5225 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005226 break;
5227 }
5228 case ICmpInst::ICMP_NE: {
5229 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5230 return true;
5231 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5232 return true;
5233
5234 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5235 if (isKnownNonZero(Diff))
5236 return true;
5237 break;
5238 }
5239 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005240 // The check at the top of the function catches the case where
5241 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005242 break;
5243 }
5244 return false;
5245}
5246
5247/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5248/// protected by a conditional between LHS and RHS. This is used to
5249/// to eliminate casts.
5250bool
5251ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5252 ICmpInst::Predicate Pred,
5253 const SCEV *LHS, const SCEV *RHS) {
5254 // Interpret a null as meaning no loop, where there is obviously no guard
5255 // (interprocedural conditions notwithstanding).
5256 if (!L) return true;
5257
5258 BasicBlock *Latch = L->getLoopLatch();
5259 if (!Latch)
5260 return false;
5261
5262 BranchInst *LoopContinuePredicate =
5263 dyn_cast<BranchInst>(Latch->getTerminator());
5264 if (!LoopContinuePredicate ||
5265 LoopContinuePredicate->isUnconditional())
5266 return false;
5267
Dan Gohmanaf08a362010-08-10 23:46:30 +00005268 return isImpliedCond(Pred, LHS, RHS,
5269 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005270 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005271}
5272
Dan Gohman3948d0b2010-04-11 19:27:13 +00005273/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005274/// by a conditional between LHS and RHS. This is used to help avoid max
5275/// expressions in loop trip counts, and to eliminate casts.
5276bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005277ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5278 ICmpInst::Predicate Pred,
5279 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005280 // Interpret a null as meaning no loop, where there is obviously no guard
5281 // (interprocedural conditions notwithstanding).
5282 if (!L) return false;
5283
Dan Gohman859b4822009-05-18 15:36:09 +00005284 // Starting at the loop predecessor, climb up the predecessor chain, as long
5285 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005286 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005287 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005288 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005289 Pair.first;
5290 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005291
5292 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005293 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005294 if (!LoopEntryPredicate ||
5295 LoopEntryPredicate->isUnconditional())
5296 continue;
5297
Dan Gohmanaf08a362010-08-10 23:46:30 +00005298 if (isImpliedCond(Pred, LHS, RHS,
5299 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005300 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005301 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005302 }
5303
Dan Gohman38372182008-08-12 20:17:31 +00005304 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005305}
5306
Dan Gohman0f4b2852009-07-21 23:03:19 +00005307/// isImpliedCond - Test whether the condition described by Pred, LHS,
5308/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005309bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005310 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005311 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005312 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005313 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005314 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005315 if (BO->getOpcode() == Instruction::And) {
5316 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005317 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5318 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005319 } else if (BO->getOpcode() == Instruction::Or) {
5320 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005321 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5322 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005323 }
5324 }
5325
Dan Gohmanaf08a362010-08-10 23:46:30 +00005326 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005327 if (!ICI) return false;
5328
Dan Gohman85b05a22009-07-13 21:35:55 +00005329 // Bail if the ICmp's operands' types are wider than the needed type
5330 // before attempting to call getSCEV on them. This avoids infinite
5331 // recursion, since the analysis of widening casts can require loop
5332 // exit condition information for overflow checking, which would
5333 // lead back here.
5334 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005335 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005336 return false;
5337
Dan Gohman0f4b2852009-07-21 23:03:19 +00005338 // Now that we found a conditional branch that dominates the loop, check to
5339 // see if it is the comparison we are looking for.
5340 ICmpInst::Predicate FoundPred;
5341 if (Inverse)
5342 FoundPred = ICI->getInversePredicate();
5343 else
5344 FoundPred = ICI->getPredicate();
5345
5346 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5347 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005348
5349 // Balance the types. The case where FoundLHS' type is wider than
5350 // LHS' type is checked for above.
5351 if (getTypeSizeInBits(LHS->getType()) >
5352 getTypeSizeInBits(FoundLHS->getType())) {
5353 if (CmpInst::isSigned(Pred)) {
5354 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5355 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5356 } else {
5357 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5358 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5359 }
5360 }
5361
Dan Gohman0f4b2852009-07-21 23:03:19 +00005362 // Canonicalize the query to match the way instcombine will have
5363 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005364 if (SimplifyICmpOperands(Pred, LHS, RHS))
5365 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005366 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005367 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5368 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005369 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005370
5371 // Check to see if we can make the LHS or RHS match.
5372 if (LHS == FoundRHS || RHS == FoundLHS) {
5373 if (isa<SCEVConstant>(RHS)) {
5374 std::swap(FoundLHS, FoundRHS);
5375 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5376 } else {
5377 std::swap(LHS, RHS);
5378 Pred = ICmpInst::getSwappedPredicate(Pred);
5379 }
5380 }
5381
5382 // Check whether the found predicate is the same as the desired predicate.
5383 if (FoundPred == Pred)
5384 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5385
5386 // Check whether swapping the found predicate makes it the same as the
5387 // desired predicate.
5388 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5389 if (isa<SCEVConstant>(RHS))
5390 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5391 else
5392 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5393 RHS, LHS, FoundLHS, FoundRHS);
5394 }
5395
5396 // Check whether the actual condition is beyond sufficient.
5397 if (FoundPred == ICmpInst::ICMP_EQ)
5398 if (ICmpInst::isTrueWhenEqual(Pred))
5399 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5400 return true;
5401 if (Pred == ICmpInst::ICMP_NE)
5402 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5403 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5404 return true;
5405
5406 // Otherwise assume the worst.
5407 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005408}
5409
Dan Gohman0f4b2852009-07-21 23:03:19 +00005410/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005411/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005412/// and FoundRHS is true.
5413bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5414 const SCEV *LHS, const SCEV *RHS,
5415 const SCEV *FoundLHS,
5416 const SCEV *FoundRHS) {
5417 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5418 FoundLHS, FoundRHS) ||
5419 // ~x < ~y --> x > y
5420 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5421 getNotSCEV(FoundRHS),
5422 getNotSCEV(FoundLHS));
5423}
5424
5425/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005426/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005427/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005428bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005429ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5430 const SCEV *LHS, const SCEV *RHS,
5431 const SCEV *FoundLHS,
5432 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005433 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005434 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5435 case ICmpInst::ICMP_EQ:
5436 case ICmpInst::ICMP_NE:
5437 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5438 return true;
5439 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005440 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005441 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005442 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5443 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005444 return true;
5445 break;
5446 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005447 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005448 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5449 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005450 return true;
5451 break;
5452 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005453 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005454 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5455 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005456 return true;
5457 break;
5458 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005459 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005460 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5461 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005462 return true;
5463 break;
5464 }
5465
5466 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005467}
5468
Dan Gohman51f53b72009-06-21 23:46:38 +00005469/// getBECount - Subtract the end and start values and divide by the step,
5470/// rounding up, to get the number of times the backedge is executed. Return
5471/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005472const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005473 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005474 const SCEV *Step,
5475 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005476 assert(!isKnownNegative(Step) &&
5477 "This code doesn't handle negative strides yet!");
5478
Dan Gohman51f53b72009-06-21 23:46:38 +00005479 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005480 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005481 const SCEV *Diff = getMinusSCEV(End, Start);
5482 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005483
5484 // Add an adjustment to the difference between End and Start so that
5485 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005486 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005487
Dan Gohman1f96e672009-09-17 18:05:20 +00005488 if (!NoWrap) {
5489 // Check Add for unsigned overflow.
5490 // TODO: More sophisticated things could be done here.
5491 const Type *WideTy = IntegerType::get(getContext(),
5492 getTypeSizeInBits(Ty) + 1);
5493 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5494 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5495 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5496 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5497 return getCouldNotCompute();
5498 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005499
5500 return getUDivExpr(Add, Step);
5501}
5502
Chris Lattnerdb25de42005-08-15 23:33:51 +00005503/// HowManyLessThans - Return the number of times a backedge containing the
5504/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005505/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005506ScalarEvolution::BackedgeTakenInfo
5507ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5508 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005509 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005510 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005511
Dan Gohman35738ac2009-05-04 22:30:44 +00005512 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005513 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005514 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005515
Dan Gohman1f96e672009-09-17 18:05:20 +00005516 // Check to see if we have a flag which makes analysis easy.
5517 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5518 AddRec->hasNoUnsignedWrap();
5519
Chris Lattnerdb25de42005-08-15 23:33:51 +00005520 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005521 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005522 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005523
Dan Gohman52fddd32010-01-26 04:40:18 +00005524 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005525 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005526 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005527 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005528 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005529 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005530 // value and past the maximum value for its type in a single step.
5531 // Note that it's not sufficient to check NoWrap here, because even
5532 // though the value after a wrap is undefined, it's not undefined
5533 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005534 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005535 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005536 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005537 if (isSigned) {
5538 APInt Max = APInt::getSignedMaxValue(BitWidth);
5539 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5540 .slt(getSignedRange(RHS).getSignedMax()))
5541 return getCouldNotCompute();
5542 } else {
5543 APInt Max = APInt::getMaxValue(BitWidth);
5544 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5545 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5546 return getCouldNotCompute();
5547 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005548 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005549 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005550 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005551
Dan Gohmana1af7572009-04-30 20:47:05 +00005552 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5553 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5554 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005555 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005556
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005557 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005558 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005559
Dan Gohmana1af7572009-04-30 20:47:05 +00005560 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005561 const SCEV *MinStart = getConstant(isSigned ?
5562 getSignedRange(Start).getSignedMin() :
5563 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005564
Dan Gohmana1af7572009-04-30 20:47:05 +00005565 // If we know that the condition is true in order to enter the loop,
5566 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005567 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5568 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005569 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005570 if (!isLoopEntryGuardedByCond(L,
5571 isSigned ? ICmpInst::ICMP_SLT :
5572 ICmpInst::ICMP_ULT,
5573 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005574 End = isSigned ? getSMaxExpr(RHS, Start)
5575 : getUMaxExpr(RHS, Start);
5576
5577 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005578 const SCEV *MaxEnd = getConstant(isSigned ?
5579 getSignedRange(End).getSignedMax() :
5580 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005581
Dan Gohman52fddd32010-01-26 04:40:18 +00005582 // If MaxEnd is within a step of the maximum integer value in its type,
5583 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005584 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005585 // compute the correct value.
5586 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005587 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005588 MaxEnd = isSigned ?
5589 getSMinExpr(MaxEnd,
5590 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5591 StepMinusOne)) :
5592 getUMinExpr(MaxEnd,
5593 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5594 StepMinusOne));
5595
Dan Gohmana1af7572009-04-30 20:47:05 +00005596 // Finally, we subtract these two values and divide, rounding up, to get
5597 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005598 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005599
5600 // The maximum backedge count is similar, except using the minimum start
5601 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005602 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005603
5604 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005605 }
5606
Dan Gohman1c343752009-06-27 21:21:31 +00005607 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005608}
5609
Chris Lattner53e677a2004-04-02 20:23:17 +00005610/// getNumIterationsInRange - Return the number of iterations of this loop that
5611/// produce values in the specified constant range. Another way of looking at
5612/// this is that it returns the first iteration number where the value is not in
5613/// the condition, thus computing the exit count. If the iteration count can't
5614/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005615const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005616 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005617 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005618 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005619
5620 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005621 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005622 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005623 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005624 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005625 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005626 if (const SCEVAddRecExpr *ShiftedAddRec =
5627 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005628 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005629 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005630 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005631 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005632 }
5633
5634 // The only time we can solve this is when we have all constant indices.
5635 // Otherwise, we cannot determine the overflow conditions.
5636 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5637 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005638 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005639
5640
5641 // Okay at this point we know that all elements of the chrec are constants and
5642 // that the start element is zero.
5643
5644 // First check to see if the range contains zero. If not, the first
5645 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005646 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005647 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005648 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005649
Chris Lattner53e677a2004-04-02 20:23:17 +00005650 if (isAffine()) {
5651 // If this is an affine expression then we have this situation:
5652 // Solve {0,+,A} in Range === Ax in Range
5653
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005654 // We know that zero is in the range. If A is positive then we know that
5655 // the upper value of the range must be the first possible exit value.
5656 // If A is negative then the lower of the range is the last possible loop
5657 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005658 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005659 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5660 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005661
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005662 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005663 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005664 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005665
5666 // Evaluate at the exit value. If we really did fall out of the valid
5667 // range, then we computed our trip count, otherwise wrap around or other
5668 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005669 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005670 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005671 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005672
5673 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005674 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005675 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005676 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005677 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005678 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005679 } else if (isQuadratic()) {
5680 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5681 // quadratic equation to solve it. To do this, we must frame our problem in
5682 // terms of figuring out when zero is crossed, instead of when
5683 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005684 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005685 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005686 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005687
5688 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005689 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005690 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005691 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5692 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005693 if (R1) {
5694 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005695 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005696 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005697 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005698 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005699 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005700
Chris Lattner53e677a2004-04-02 20:23:17 +00005701 // Make sure the root is not off by one. The returned iteration should
5702 // not be in the range, but the previous one should be. When solving
5703 // for "X*X < 5", for example, we should not return a root of 2.
5704 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005705 R1->getValue(),
5706 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005707 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005708 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005709 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005710 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005711
Dan Gohman246b2562007-10-22 18:31:58 +00005712 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005713 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005714 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005715 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005716 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005717
Chris Lattner53e677a2004-04-02 20:23:17 +00005718 // If R1 was not in the range, then it is a good return value. Make
5719 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005720 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005721 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005722 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005723 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005724 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005725 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005726 }
5727 }
5728 }
5729
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005730 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005731}
5732
5733
5734
5735//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005736// SCEVCallbackVH Class Implementation
5737//===----------------------------------------------------------------------===//
5738
Dan Gohman1959b752009-05-19 19:22:47 +00005739void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005740 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005741 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5742 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005743 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00005744 // this now dangles!
5745}
5746
Dan Gohman81f91212010-07-28 01:09:07 +00005747void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005748 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005749
Dan Gohman35738ac2009-05-04 22:30:44 +00005750 // Forget all the expressions associated with users of the old value,
5751 // so that future queries will recompute the expressions using the new
5752 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005753 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005754 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005755 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005756 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5757 UI != UE; ++UI)
5758 Worklist.push_back(*UI);
5759 while (!Worklist.empty()) {
5760 User *U = Worklist.pop_back_val();
5761 // Deleting the Old value will cause this to dangle. Postpone
5762 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005763 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005764 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005765 if (!Visited.insert(U))
5766 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005767 if (PHINode *PN = dyn_cast<PHINode>(U))
5768 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005769 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00005770 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5771 UI != UE; ++UI)
5772 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005773 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005774 // Delete the Old value.
5775 if (PHINode *PN = dyn_cast<PHINode>(Old))
5776 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005777 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00005778 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005779}
5780
Dan Gohman1959b752009-05-19 19:22:47 +00005781ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005782 : CallbackVH(V), SE(se) {}
5783
5784//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005785// ScalarEvolution Class Implementation
5786//===----------------------------------------------------------------------===//
5787
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005788ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005789 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00005790 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005791}
5792
Chris Lattner53e677a2004-04-02 20:23:17 +00005793bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005794 this->F = &F;
5795 LI = &getAnalysis<LoopInfo>();
5796 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005797 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005798 return false;
5799}
5800
5801void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005802 // Iterate through all the SCEVUnknown instances and call their
5803 // destructors, so that they release their references to their values.
5804 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5805 U->~SCEVUnknown();
5806 FirstUnknown = 0;
5807
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005808 ValueExprMap.clear();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005809 BackedgeTakenCounts.clear();
5810 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005811 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00005812 LoopDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00005813 UnsignedRanges.clear();
5814 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005815 UniqueSCEVs.clear();
5816 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005817}
5818
5819void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5820 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005821 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005822 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005823}
5824
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005825bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005826 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005827}
5828
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005829static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005830 const Loop *L) {
5831 // Print all inner loops first
5832 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5833 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005834
Dan Gohman30733292010-01-09 18:17:45 +00005835 OS << "Loop ";
5836 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5837 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005838
Dan Gohman5d984912009-12-18 01:14:11 +00005839 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005840 L->getExitBlocks(ExitBlocks);
5841 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005842 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005843
Dan Gohman46bdfb02009-02-24 18:55:53 +00005844 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5845 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005846 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005847 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005848 }
5849
Dan Gohman30733292010-01-09 18:17:45 +00005850 OS << "\n"
5851 "Loop ";
5852 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5853 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005854
5855 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5856 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5857 } else {
5858 OS << "Unpredictable max backedge-taken count. ";
5859 }
5860
5861 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005862}
5863
Dan Gohman5d984912009-12-18 01:14:11 +00005864void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005865 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005866 // out SCEV values of all instructions that are interesting. Doing
5867 // this potentially causes it to create new SCEV objects though,
5868 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005869 // observable from outside the class though, so casting away the
5870 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005871 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005872
Dan Gohman30733292010-01-09 18:17:45 +00005873 OS << "Classifying expressions for: ";
5874 WriteAsOperand(OS, F, /*PrintType=*/false);
5875 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005876 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005877 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005878 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005879 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005880 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005881 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005882
Dan Gohman0c689c52009-06-19 17:49:54 +00005883 const Loop *L = LI->getLoopFor((*I).getParent());
5884
Dan Gohman0bba49c2009-07-07 17:06:11 +00005885 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005886 if (AtUse != SV) {
5887 OS << " --> ";
5888 AtUse->print(OS);
5889 }
5890
5891 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005892 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005893 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00005894 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005895 OS << "<<Unknown>>";
5896 } else {
5897 OS << *ExitValue;
5898 }
5899 }
5900
Chris Lattner53e677a2004-04-02 20:23:17 +00005901 OS << "\n";
5902 }
5903
Dan Gohman30733292010-01-09 18:17:45 +00005904 OS << "Determining loop execution counts for: ";
5905 WriteAsOperand(OS, F, /*PrintType=*/false);
5906 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005907 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5908 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005909}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005910
Dan Gohman714b5292010-11-17 23:21:44 +00005911ScalarEvolution::LoopDisposition
5912ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
5913 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
5914 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
5915 Values.insert(std::make_pair(L, LoopVariant));
5916 if (!Pair.second)
5917 return Pair.first->second;
5918
5919 LoopDisposition D = computeLoopDisposition(S, L);
5920 return LoopDispositions[S][L] = D;
5921}
5922
5923ScalarEvolution::LoopDisposition
5924ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00005925 switch (S->getSCEVType()) {
5926 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00005927 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005928 case scTruncate:
5929 case scZeroExtend:
5930 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00005931 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00005932 case scAddRecExpr: {
5933 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
5934
Dan Gohman714b5292010-11-17 23:21:44 +00005935 // If L is the addrec's loop, it's computable.
5936 if (AR->getLoop() == L)
5937 return LoopComputable;
5938
Dan Gohman17ead4f2010-11-17 21:23:15 +00005939 // Add recurrences are never invariant in the function-body (null loop).
5940 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00005941 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005942
5943 // This recurrence is variant w.r.t. L if L contains AR's loop.
5944 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00005945 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005946
5947 // This recurrence is invariant w.r.t. L if AR's loop contains L.
5948 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00005949 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005950
5951 // This recurrence is variant w.r.t. L if any of its operands
5952 // are variant.
5953 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
5954 I != E; ++I)
5955 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00005956 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005957
5958 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00005959 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005960 }
5961 case scAddExpr:
5962 case scMulExpr:
5963 case scUMaxExpr:
5964 case scSMaxExpr: {
5965 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00005966 bool HasVarying = false;
5967 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
5968 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00005969 LoopDisposition D = getLoopDisposition(*I, L);
5970 if (D == LoopVariant)
5971 return LoopVariant;
5972 if (D == LoopComputable)
5973 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005974 }
Dan Gohman714b5292010-11-17 23:21:44 +00005975 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005976 }
5977 case scUDivExpr: {
5978 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00005979 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
5980 if (LD == LoopVariant)
5981 return LoopVariant;
5982 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
5983 if (RD == LoopVariant)
5984 return LoopVariant;
5985 return (LD == LoopInvariant && RD == LoopInvariant) ?
5986 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005987 }
5988 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00005989 // All non-instruction values are loop invariant. All instructions are loop
5990 // invariant if they are not contained in the specified loop.
5991 // Instructions are never considered invariant in the function body
5992 // (null loop) because they are defined within the "loop".
5993 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
5994 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
5995 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005996 case scCouldNotCompute:
5997 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00005998 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005999 default: break;
6000 }
6001 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00006002 return LoopVariant;
6003}
6004
6005bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6006 return getLoopDisposition(S, L) == LoopInvariant;
6007}
6008
6009bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6010 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006011}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006012
6013bool ScalarEvolution::dominates(const SCEV *S, BasicBlock *BB) const {
6014 switch (S->getSCEVType()) {
6015 case scConstant:
6016 return true;
6017 case scTruncate:
6018 case scZeroExtend:
6019 case scSignExtend:
6020 return dominates(cast<SCEVCastExpr>(S)->getOperand(), BB);
6021 case scAddRecExpr: {
6022 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6023 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6024 return false;
6025 }
6026 // FALL THROUGH into SCEVNAryExpr handling.
6027 case scAddExpr:
6028 case scMulExpr:
6029 case scUMaxExpr:
6030 case scSMaxExpr: {
6031 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6032 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6033 I != E; ++I)
6034 if (!dominates(*I, BB))
6035 return false;
6036 return true;
6037 }
6038 case scUDivExpr: {
6039 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6040 return dominates(UDiv->getLHS(), BB) && dominates(UDiv->getRHS(), BB);
6041 }
6042 case scUnknown:
6043 if (Instruction *I =
6044 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6045 return DT->dominates(I->getParent(), BB);
6046 return true;
6047 case scCouldNotCompute:
6048 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6049 return false;
6050 default: break;
6051 }
6052 llvm_unreachable("Unknown SCEV kind!");
6053 return false;
6054}
6055
6056bool ScalarEvolution::properlyDominates(const SCEV *S, BasicBlock *BB) const {
6057 switch (S->getSCEVType()) {
6058 case scConstant:
6059 return true;
6060 case scTruncate:
6061 case scZeroExtend:
6062 case scSignExtend:
6063 return properlyDominates(cast<SCEVCastExpr>(S)->getOperand(), BB);
6064 case scAddRecExpr: {
6065 // This uses a "dominates" query instead of "properly dominates" query
6066 // because the instruction which produces the addrec's value is a PHI, and
6067 // a PHI effectively properly dominates its entire containing block.
6068 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6069 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6070 return false;
6071 }
6072 // FALL THROUGH into SCEVNAryExpr handling.
6073 case scAddExpr:
6074 case scMulExpr:
6075 case scUMaxExpr:
6076 case scSMaxExpr: {
6077 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6078 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6079 I != E; ++I)
6080 if (!properlyDominates(*I, BB))
6081 return false;
6082 return true;
6083 }
6084 case scUDivExpr: {
6085 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6086 return properlyDominates(UDiv->getLHS(), BB) &&
6087 properlyDominates(UDiv->getRHS(), BB);
6088 }
6089 case scUnknown:
6090 if (Instruction *I =
6091 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6092 return DT->properlyDominates(I->getParent(), BB);
6093 return true;
6094 case scCouldNotCompute:
6095 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6096 return false;
6097 default: break;
6098 }
6099 llvm_unreachable("Unknown SCEV kind!");
6100 return false;
6101}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006102
6103bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6104 switch (S->getSCEVType()) {
6105 case scConstant:
6106 return false;
6107 case scTruncate:
6108 case scZeroExtend:
6109 case scSignExtend: {
6110 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6111 const SCEV *CastOp = Cast->getOperand();
6112 return Op == CastOp || hasOperand(CastOp, Op);
6113 }
6114 case scAddRecExpr:
6115 case scAddExpr:
6116 case scMulExpr:
6117 case scUMaxExpr:
6118 case scSMaxExpr: {
6119 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6120 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6121 I != E; ++I) {
6122 const SCEV *NAryOp = *I;
6123 if (NAryOp == Op || hasOperand(NAryOp, Op))
6124 return true;
6125 }
6126 return false;
6127 }
6128 case scUDivExpr: {
6129 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6130 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6131 return LHS == Op || hasOperand(LHS, Op) ||
6132 RHS == Op || hasOperand(RHS, Op);
6133 }
6134 case scUnknown:
6135 return false;
6136 case scCouldNotCompute:
6137 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6138 return false;
6139 default: break;
6140 }
6141 llvm_unreachable("Unknown SCEV kind!");
6142 return false;
6143}