blob: ce4a724c0fc4c1d43b2ebd3d413f977fcbaf65bf [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 << "}<";
Andrew Trick3228cc22011-03-14 16:50:06 +0000160 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnerf1859892011-01-09 02:16:18 +0000161 OS << "nuw><";
Andrew Trick3228cc22011-03-14 16:50:06 +0000162 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnerf1859892011-01-09 02:16:18 +0000163 OS << "nsw><";
Andrew Trick3228cc22011-03-14 16:50:06 +0000164 if (AR->getNoWrapFlags(FlagNW) &&
165 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
166 OS << "nw><";
Dan Gohman4ce32db2010-11-17 22:27:42 +0000167 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
168 OS << ">";
169 return;
170 }
171 case scAddExpr:
172 case scMulExpr:
173 case scUMaxExpr:
174 case scSMaxExpr: {
175 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Benjamin Kramerb458b152010-11-19 11:37:26 +0000176 const char *OpStr = 0;
Dan Gohman4ce32db2010-11-17 22:27:42 +0000177 switch (NAry->getSCEVType()) {
178 case scAddExpr: OpStr = " + "; break;
179 case scMulExpr: OpStr = " * "; break;
180 case scUMaxExpr: OpStr = " umax "; break;
181 case scSMaxExpr: OpStr = " smax "; break;
182 }
183 OS << "(";
184 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
185 I != E; ++I) {
186 OS << **I;
187 if (llvm::next(I) != E)
188 OS << OpStr;
189 }
190 OS << ")";
191 return;
192 }
193 case scUDivExpr: {
194 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
195 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
196 return;
197 }
198 case scUnknown: {
199 const SCEVUnknown *U = cast<SCEVUnknown>(this);
200 const Type *AllocTy;
201 if (U->isSizeOf(AllocTy)) {
202 OS << "sizeof(" << *AllocTy << ")";
203 return;
204 }
205 if (U->isAlignOf(AllocTy)) {
206 OS << "alignof(" << *AllocTy << ")";
207 return;
208 }
Andrew Trick635f7182011-03-09 17:23:39 +0000209
Dan Gohman4ce32db2010-11-17 22:27:42 +0000210 const Type *CTy;
211 Constant *FieldNo;
212 if (U->isOffsetOf(CTy, FieldNo)) {
213 OS << "offsetof(" << *CTy << ", ";
214 WriteAsOperand(OS, FieldNo, false);
215 OS << ")";
216 return;
217 }
Andrew Trick635f7182011-03-09 17:23:39 +0000218
Dan Gohman4ce32db2010-11-17 22:27:42 +0000219 // Otherwise just print it normally.
220 WriteAsOperand(OS, U->getValue(), false);
221 return;
222 }
223 case scCouldNotCompute:
224 OS << "***COULDNOTCOMPUTE***";
225 return;
226 default: break;
227 }
228 llvm_unreachable("Unknown SCEV kind!");
229}
230
231const Type *SCEV::getType() const {
232 switch (getSCEVType()) {
233 case scConstant:
234 return cast<SCEVConstant>(this)->getType();
235 case scTruncate:
236 case scZeroExtend:
237 case scSignExtend:
238 return cast<SCEVCastExpr>(this)->getType();
239 case scAddRecExpr:
240 case scMulExpr:
241 case scUMaxExpr:
242 case scSMaxExpr:
243 return cast<SCEVNAryExpr>(this)->getType();
244 case scAddExpr:
245 return cast<SCEVAddExpr>(this)->getType();
246 case scUDivExpr:
247 return cast<SCEVUDivExpr>(this)->getType();
248 case scUnknown:
249 return cast<SCEVUnknown>(this)->getType();
250 case scCouldNotCompute:
251 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
252 return 0;
253 default: break;
254 }
255 llvm_unreachable("Unknown SCEV kind!");
256 return 0;
257}
258
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000259bool SCEV::isZero() const {
260 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
261 return SC->getValue()->isZero();
262 return false;
263}
264
Dan Gohman70a1fe72009-05-18 15:22:39 +0000265bool SCEV::isOne() const {
266 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
267 return SC->getValue()->isOne();
268 return false;
269}
Chris Lattner53e677a2004-04-02 20:23:17 +0000270
Dan Gohman4d289bf2009-06-24 00:30:26 +0000271bool SCEV::isAllOnesValue() const {
272 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
273 return SC->getValue()->isAllOnesValue();
274 return false;
275}
276
Owen Anderson753ad612009-06-22 21:57:23 +0000277SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000278 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000279
Chris Lattner53e677a2004-04-02 20:23:17 +0000280bool SCEVCouldNotCompute::classof(const SCEV *S) {
281 return S->getSCEVType() == scCouldNotCompute;
282}
283
Dan Gohman0bba49c2009-07-07 17:06:11 +0000284const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000285 FoldingSetNodeID ID;
286 ID.AddInteger(scConstant);
287 ID.AddPointer(V);
288 void *IP = 0;
289 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000290 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000291 UniqueSCEVs.InsertNode(S, IP);
292 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000293}
Chris Lattner53e677a2004-04-02 20:23:17 +0000294
Dan Gohman0bba49c2009-07-07 17:06:11 +0000295const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000296 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000297}
298
Dan Gohman0bba49c2009-07-07 17:06:11 +0000299const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000300ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000301 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
302 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000303}
304
Dan Gohman3bf63762010-06-18 19:54:20 +0000305SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000306 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000307 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000308
Dan Gohman3bf63762010-06-18 19:54:20 +0000309SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000310 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000311 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000312 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
313 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315}
Chris Lattner53e677a2004-04-02 20:23:17 +0000316
Dan Gohman3bf63762010-06-18 19:54:20 +0000317SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000318 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000319 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000320 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
321 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000323}
324
Dan Gohman3bf63762010-06-18 19:54:20 +0000325SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000326 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000327 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000328 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
329 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000330 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000331}
332
Dan Gohmanab37f502010-08-02 23:49:30 +0000333void SCEVUnknown::deleted() {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000334 // Clear this SCEVUnknown from various maps.
Dan Gohman56a75682010-11-17 23:28:48 +0000335 SE->forgetMemoizedResults(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000336
337 // Remove this SCEVUnknown from the uniquing map.
338 SE->UniqueSCEVs.RemoveNode(this);
339
340 // Release the value.
341 setValPtr(0);
342}
343
344void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000345 // Clear this SCEVUnknown from various maps.
Dan Gohman56a75682010-11-17 23:28:48 +0000346 SE->forgetMemoizedResults(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000347
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
350
351 // Update this SCEVUnknown to point to the new value. This is needed
352 // because there may still be outstanding SCEVs which still point to
353 // this SCEVUnknown.
354 setValPtr(New);
355}
356
Dan Gohman0f5efe52010-01-28 02:15:55 +0000357bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000358 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000359 if (VCE->getOpcode() == Instruction::PtrToInt)
360 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000361 if (CE->getOpcode() == Instruction::GetElementPtr &&
362 CE->getOperand(0)->isNullValue() &&
363 CE->getNumOperands() == 2)
364 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
365 if (CI->isOne()) {
366 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
367 ->getElementType();
368 return true;
369 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000370
371 return false;
372}
373
374bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000375 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000376 if (VCE->getOpcode() == Instruction::PtrToInt)
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000378 if (CE->getOpcode() == Instruction::GetElementPtr &&
379 CE->getOperand(0)->isNullValue()) {
380 const Type *Ty =
381 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
382 if (const StructType *STy = dyn_cast<StructType>(Ty))
383 if (!STy->isPacked() &&
384 CE->getNumOperands() == 3 &&
385 CE->getOperand(1)->isNullValue()) {
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
387 if (CI->isOne() &&
388 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000389 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000390 AllocTy = STy->getElementType(1);
391 return true;
392 }
393 }
394 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000395
396 return false;
397}
398
Dan Gohman4f8eea82010-02-01 18:27:38 +0000399bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000400 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000401 if (VCE->getOpcode() == Instruction::PtrToInt)
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
403 if (CE->getOpcode() == Instruction::GetElementPtr &&
404 CE->getNumOperands() == 3 &&
405 CE->getOperand(0)->isNullValue() &&
406 CE->getOperand(1)->isNullValue()) {
407 const Type *Ty =
408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
409 // Ignore vector types here so that ScalarEvolutionExpander doesn't
410 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000411 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000412 CTy = Ty;
413 FieldNo = CE->getOperand(2);
414 return true;
415 }
416 }
417
418 return false;
419}
420
Chris Lattner8d741b82004-06-20 06:23:15 +0000421//===----------------------------------------------------------------------===//
422// SCEV Utilities
423//===----------------------------------------------------------------------===//
424
425namespace {
426 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427 /// than the complexity of the RHS. This comparator is used to canonicalize
428 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000429 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000430 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000431 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000432 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000433
Dan Gohman67ef74e2010-08-27 15:26:01 +0000434 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000435 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman67ef74e2010-08-27 15:26:01 +0000436 return compare(LHS, RHS) < 0;
437 }
438
439 // Return negative, zero, or positive, if LHS is less than, equal to, or
440 // greater than RHS, respectively. A three-way result allows recursive
441 // comparisons to be more efficient.
442 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000443 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
444 if (LHS == RHS)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000445 return 0;
Dan Gohman42214892009-08-31 21:15:23 +0000446
Dan Gohman72861302009-05-07 14:39:04 +0000447 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000448 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
449 if (LType != RType)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000450 return (int)LType - (int)RType;
Dan Gohman72861302009-05-07 14:39:04 +0000451
Dan Gohman3bf63762010-06-18 19:54:20 +0000452 // Aside from the getSCEVType() ordering, the particular ordering
453 // isn't very important except that it's beneficial to be consistent,
454 // so that (a + b) and (b + a) don't end up as different expressions.
Dan Gohman67ef74e2010-08-27 15:26:01 +0000455 switch (LType) {
456 case scUnknown: {
457 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000458 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000459
460 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
461 // not as complete as it could be.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000462 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000463
464 // Order pointer values after integer values. This helps SCEVExpander
465 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000466 bool LIsPointer = LV->getType()->isPointerTy(),
467 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000468 if (LIsPointer != RIsPointer)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000469 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000470
471 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000472 unsigned LID = LV->getValueID(),
473 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000474 if (LID != RID)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000475 return (int)LID - (int)RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000476
477 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000478 if (const Argument *LA = dyn_cast<Argument>(LV)) {
479 const Argument *RA = cast<Argument>(RV);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000480 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
481 return (int)LArgNo - (int)RArgNo;
Dan Gohman3bf63762010-06-18 19:54:20 +0000482 }
483
Dan Gohman67ef74e2010-08-27 15:26:01 +0000484 // For instructions, compare their loop depth, and their operand
485 // count. This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000486 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
487 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000488
489 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000490 const BasicBlock *LParent = LInst->getParent(),
491 *RParent = RInst->getParent();
492 if (LParent != RParent) {
493 unsigned LDepth = LI->getLoopDepth(LParent),
494 RDepth = LI->getLoopDepth(RParent);
495 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000496 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000497 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000498
499 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000500 unsigned LNumOps = LInst->getNumOperands(),
501 RNumOps = RInst->getNumOperands();
Dan Gohman67ef74e2010-08-27 15:26:01 +0000502 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000503 }
504
Dan Gohman67ef74e2010-08-27 15:26:01 +0000505 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000506 }
507
Dan Gohman67ef74e2010-08-27 15:26:01 +0000508 case scConstant: {
509 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000510 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000511
512 // Compare constant values.
Dan Gohmane28d7922010-08-16 16:25:35 +0000513 const APInt &LA = LC->getValue()->getValue();
514 const APInt &RA = RC->getValue()->getValue();
515 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman304a7a62010-07-23 21:20:52 +0000516 if (LBitWidth != RBitWidth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000517 return (int)LBitWidth - (int)RBitWidth;
518 return LA.ult(RA) ? -1 : 1;
Dan Gohman3bf63762010-06-18 19:54:20 +0000519 }
520
Dan Gohman67ef74e2010-08-27 15:26:01 +0000521 case scAddRecExpr: {
522 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000523 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000524
525 // Compare addrec loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000526 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
527 if (LLoop != RLoop) {
528 unsigned LDepth = LLoop->getLoopDepth(),
529 RDepth = RLoop->getLoopDepth();
530 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000531 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000532 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000533
534 // Addrec complexity grows with operand count.
535 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
536 if (LNumOps != RNumOps)
537 return (int)LNumOps - (int)RNumOps;
538
539 // Lexicographically compare.
540 for (unsigned i = 0; i != LNumOps; ++i) {
541 long X = compare(LA->getOperand(i), RA->getOperand(i));
542 if (X != 0)
543 return X;
544 }
545
546 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000547 }
548
Dan Gohman67ef74e2010-08-27 15:26:01 +0000549 case scAddExpr:
550 case scMulExpr:
551 case scSMaxExpr:
552 case scUMaxExpr: {
553 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000554 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000555
556 // Lexicographically compare n-ary expressions.
Dan Gohman304a7a62010-07-23 21:20:52 +0000557 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
558 for (unsigned i = 0; i != LNumOps; ++i) {
559 if (i >= RNumOps)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000560 return 1;
561 long X = compare(LC->getOperand(i), RC->getOperand(i));
562 if (X != 0)
563 return X;
Dan Gohman3bf63762010-06-18 19:54:20 +0000564 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000565 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000566 }
567
Dan Gohman67ef74e2010-08-27 15:26:01 +0000568 case scUDivExpr: {
569 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000570 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000571
572 // Lexicographically compare udiv expressions.
573 long X = compare(LC->getLHS(), RC->getLHS());
574 if (X != 0)
575 return X;
576 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman3bf63762010-06-18 19:54:20 +0000577 }
578
Dan Gohman67ef74e2010-08-27 15:26:01 +0000579 case scTruncate:
580 case scZeroExtend:
581 case scSignExtend: {
582 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000583 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000584
585 // Compare cast expressions by operand.
586 return compare(LC->getOperand(), RC->getOperand());
587 }
588
589 default:
590 break;
Dan Gohman3bf63762010-06-18 19:54:20 +0000591 }
592
593 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman67ef74e2010-08-27 15:26:01 +0000594 return 0;
Chris Lattner8d741b82004-06-20 06:23:15 +0000595 }
596 };
597}
598
599/// GroupByComplexity - Given a list of SCEV objects, order them by their
600/// complexity, and group objects of the same complexity together by value.
601/// When this routine is finished, we know that any duplicates in the vector are
602/// consecutive and that complexity is monotonically increasing.
603///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000604/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000605/// results from this routine. In other words, we don't want the results of
606/// this to depend on where the addresses of various SCEV objects happened to
607/// land in memory.
608///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000609static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000610 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000611 if (Ops.size() < 2) return; // Noop
612 if (Ops.size() == 2) {
613 // This is the common case, which also happens to be trivially simple.
614 // Special case it.
Dan Gohmanc6a8e992010-08-29 15:07:13 +0000615 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
616 if (SCEVComplexityCompare(LI)(RHS, LHS))
617 std::swap(LHS, RHS);
Chris Lattner8d741b82004-06-20 06:23:15 +0000618 return;
619 }
620
Dan Gohman3bf63762010-06-18 19:54:20 +0000621 // Do the rough sort by complexity.
622 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
623
624 // Now that we are sorted by complexity, group elements of the same
625 // complexity. Note that this is, at worst, N^2, but the vector is likely to
626 // be extremely short in practice. Note that we take this approach because we
627 // do not want to depend on the addresses of the objects we are grouping.
628 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
629 const SCEV *S = Ops[i];
630 unsigned Complexity = S->getSCEVType();
631
632 // If there are any objects of the same complexity and same value as this
633 // one, group them.
634 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
635 if (Ops[j] == S) { // Found a duplicate.
636 // Move it to immediately after i'th element.
637 std::swap(Ops[i+1], Ops[j]);
638 ++i; // no need to rescan it.
639 if (i == e-2) return; // Done!
640 }
641 }
642 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000643}
644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645
Chris Lattner53e677a2004-04-02 20:23:17 +0000646
647//===----------------------------------------------------------------------===//
648// Simple SCEV method implementations
649//===----------------------------------------------------------------------===//
650
Eli Friedmanb42a6262008-08-04 23:49:06 +0000651/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000652/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000653static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000654 ScalarEvolution &SE,
655 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000656 // Handle the simplest case efficiently.
657 if (K == 1)
658 return SE.getTruncateOrZeroExtend(It, ResultTy);
659
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000660 // We are using the following formula for BC(It, K):
661 //
662 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
663 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000664 // Suppose, W is the bitwidth of the return value. We must be prepared for
665 // overflow. Hence, we must assure that the result of our computation is
666 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
667 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000668 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000669 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000670 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000671 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
672 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000673 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000674 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000675 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000676 // This formula is trivially equivalent to the previous formula. However,
677 // this formula can be implemented much more efficiently. The trick is that
678 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
679 // arithmetic. To do exact division in modular arithmetic, all we have
680 // to do is multiply by the inverse. Therefore, this step can be done at
681 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000682 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000683 // The next issue is how to safely do the division by 2^T. The way this
684 // is done is by doing the multiplication step at a width of at least W + T
685 // bits. This way, the bottom W+T bits of the product are accurate. Then,
686 // when we perform the division by 2^T (which is equivalent to a right shift
687 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
688 // truncated out after the division by 2^T.
689 //
690 // In comparison to just directly using the first formula, this technique
691 // is much more efficient; using the first formula requires W * K bits,
692 // but this formula less than W + K bits. Also, the first formula requires
693 // a division step, whereas this formula only requires multiplies and shifts.
694 //
695 // It doesn't matter whether the subtraction step is done in the calculation
696 // width or the input iteration count's width; if the subtraction overflows,
697 // the result must be zero anyway. We prefer here to do it in the width of
698 // the induction variable because it helps a lot for certain cases; CodeGen
699 // isn't smart enough to ignore the overflow, which leads to much less
700 // efficient code if the width of the subtraction is wider than the native
701 // register width.
702 //
703 // (It's possible to not widen at all by pulling out factors of 2 before
704 // the multiplication; for example, K=2 can be calculated as
705 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
706 // extra arithmetic, so it's not an obvious win, and it gets
707 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000708
Eli Friedmanb42a6262008-08-04 23:49:06 +0000709 // Protection from insane SCEVs; this bound is conservative,
710 // but it probably doesn't matter.
711 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000712 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000713
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000714 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000715
Eli Friedmanb42a6262008-08-04 23:49:06 +0000716 // Calculate K! / 2^T and T; we divide out the factors of two before
717 // multiplying for calculating K! / 2^T to avoid overflow.
718 // Other overflow doesn't matter because we only care about the bottom
719 // W bits of the result.
720 APInt OddFactorial(W, 1);
721 unsigned T = 1;
722 for (unsigned i = 3; i <= K; ++i) {
723 APInt Mult(W, i);
724 unsigned TwoFactors = Mult.countTrailingZeros();
725 T += TwoFactors;
726 Mult = Mult.lshr(TwoFactors);
727 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000728 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000729
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000731 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000732
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000733 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000734 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
735
736 // Calculate the multiplicative inverse of K! / 2^T;
737 // this multiplication factor will perform the exact division by
738 // K! / 2^T.
739 APInt Mod = APInt::getSignedMinValue(W+1);
740 APInt MultiplyFactor = OddFactorial.zext(W+1);
741 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
742 MultiplyFactor = MultiplyFactor.trunc(W);
743
744 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000745 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
746 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000747 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000748 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000749 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000750 Dividend = SE.getMulExpr(Dividend,
751 SE.getTruncateOrZeroExtend(S, CalculationTy));
752 }
753
754 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000755 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000756
757 // Truncate the result, and divide by K! / 2^T.
758
759 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
760 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000761}
762
Chris Lattner53e677a2004-04-02 20:23:17 +0000763/// evaluateAtIteration - Return the value of this chain of recurrences at
764/// the specified iteration number. We can evaluate this recurrence by
765/// multiplying each element in the chain by the binomial coefficient
766/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
767///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000768/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000769///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000770/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000771///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000772const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000773 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000774 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000775 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000776 // The computation is correct in the face of overflow provided that the
777 // multiplication is performed _after_ the evaluation of the binomial
778 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000779 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000780 if (isa<SCEVCouldNotCompute>(Coeff))
781 return Coeff;
782
783 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000784 }
785 return Result;
786}
787
Chris Lattner53e677a2004-04-02 20:23:17 +0000788//===----------------------------------------------------------------------===//
789// SCEV Expression folder implementations
790//===----------------------------------------------------------------------===//
791
Dan Gohman0bba49c2009-07-07 17:06:11 +0000792const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000793 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000794 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000795 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000796 assert(isSCEVable(Ty) &&
797 "This is not a conversion to a SCEVable type!");
798 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000799
Dan Gohmanc050fd92009-07-13 20:50:19 +0000800 FoldingSetNodeID ID;
801 ID.AddInteger(scTruncate);
802 ID.AddPointer(Op);
803 ID.AddPointer(Ty);
804 void *IP = 0;
805 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
806
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000807 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000808 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000809 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000810 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
811 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000812
Dan Gohman20900ca2009-04-22 16:20:48 +0000813 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000814 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000815 return getTruncateExpr(ST->getOperand(), Ty);
816
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000817 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000818 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000819 return getTruncateOrSignExtend(SS->getOperand(), Ty);
820
821 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000822 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000823 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
824
Nick Lewycky30aa8b12011-01-19 16:59:46 +0000825 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
826 // eliminate all the truncates.
827 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
828 SmallVector<const SCEV *, 4> Operands;
829 bool hasTrunc = false;
830 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
831 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
832 hasTrunc = isa<SCEVTruncateExpr>(S);
833 Operands.push_back(S);
834 }
835 if (!hasTrunc)
Andrew Trick3228cc22011-03-14 16:50:06 +0000836 return getAddExpr(Operands);
Nick Lewyckye19b7b82011-01-26 08:40:22 +0000837 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky30aa8b12011-01-19 16:59:46 +0000838 }
839
Nick Lewycky5c6fc1c2011-01-19 18:56:00 +0000840 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
841 // eliminate all the truncates.
842 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
843 SmallVector<const SCEV *, 4> Operands;
844 bool hasTrunc = false;
845 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
846 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
847 hasTrunc = isa<SCEVTruncateExpr>(S);
848 Operands.push_back(S);
849 }
850 if (!hasTrunc)
Andrew Trick3228cc22011-03-14 16:50:06 +0000851 return getMulExpr(Operands);
Nick Lewyckye19b7b82011-01-26 08:40:22 +0000852 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c6fc1c2011-01-19 18:56:00 +0000853 }
854
Dan Gohman6864db62009-06-18 16:24:47 +0000855 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000856 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000857 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000858 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000859 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Andrew Trick3228cc22011-03-14 16:50:06 +0000860 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +0000861 }
862
Dan Gohmanf53462d2010-07-15 20:02:11 +0000863 // As a special case, fold trunc(undef) to undef. We don't want to
864 // know too much about SCEVUnknowns, but this special case is handy
865 // and harmless.
866 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
867 if (isa<UndefValue>(U->getValue()))
868 return getSCEV(UndefValue::get(Ty));
869
Dan Gohman420ab912010-06-25 18:47:08 +0000870 // The cast wasn't folded; create an explicit cast node. We can reuse
871 // the existing insert position since if we get here, we won't have
872 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000873 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
874 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000875 UniqueSCEVs.InsertNode(S, IP);
876 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000877}
878
Dan Gohman0bba49c2009-07-07 17:06:11 +0000879const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000880 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000881 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000882 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000883 assert(isSCEVable(Ty) &&
884 "This is not a conversion to a SCEVable type!");
885 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000886
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000887 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000888 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
889 return getConstant(
890 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
891 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000892
Dan Gohman20900ca2009-04-22 16:20:48 +0000893 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000894 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000895 return getZeroExtendExpr(SZ->getOperand(), Ty);
896
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000897 // Before doing any expensive analysis, check to see if we've already
898 // computed a SCEV for this Op and Ty.
899 FoldingSetNodeID ID;
900 ID.AddInteger(scZeroExtend);
901 ID.AddPointer(Op);
902 ID.AddPointer(Ty);
903 void *IP = 0;
904 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
905
Nick Lewycky630d85a2011-01-23 06:20:19 +0000906 // zext(trunc(x)) --> zext(x) or x or trunc(x)
907 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
908 // It's possible the bits taken off by the truncate were all zero bits. If
909 // so, we should be able to simplify this further.
910 const SCEV *X = ST->getOperand();
911 ConstantRange CR = getUnsignedRange(X);
Nick Lewycky630d85a2011-01-23 06:20:19 +0000912 unsigned TruncBits = getTypeSizeInBits(ST->getType());
913 unsigned NewBits = getTypeSizeInBits(Ty);
914 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewycky76167af2011-01-23 20:06:05 +0000915 CR.zextOrTrunc(NewBits)))
916 return getTruncateOrZeroExtend(X, Ty);
Nick Lewycky630d85a2011-01-23 06:20:19 +0000917 }
918
Dan Gohman01ecca22009-04-27 20:16:15 +0000919 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000920 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000921 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000922 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000924 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000925 const SCEV *Start = AR->getStart();
926 const SCEV *Step = AR->getStepRecurrence(*this);
927 unsigned BitWidth = getTypeSizeInBits(AR->getType());
928 const Loop *L = AR->getLoop();
929
Dan Gohmaneb490a72009-07-25 01:22:26 +0000930 // If we have special knowledge that this addrec won't overflow,
931 // we don't need to do any further analysis.
Andrew Trick3228cc22011-03-14 16:50:06 +0000932 if (AR->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmaneb490a72009-07-25 01:22:26 +0000933 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
934 getZeroExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +0000935 // FIXME: Can use SCEV::FlagNUW
936 L, SCEV::FlagAnyWrap);
Dan Gohmaneb490a72009-07-25 01:22:26 +0000937
Dan Gohman01ecca22009-04-27 20:16:15 +0000938 // Check whether the backedge-taken count is SCEVCouldNotCompute.
939 // Note that this serves two purposes: It filters out loops that are
940 // simply not analyzable, and it covers the case where this code is
941 // being called from within backedge-taken count analysis, such that
942 // attempting to ask for the backedge-taken count would likely result
943 // in infinite recursion. In the later case, the analysis code will
944 // cope with a conservative value, and it will take care to purge
945 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000946 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000947 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000948 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000949 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000950
951 // Check whether the backedge-taken count can be losslessly casted to
952 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000953 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000954 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000955 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000956 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
957 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000958 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000959 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000960 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000961 const SCEV *Add = getAddExpr(Start, ZMul);
962 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000963 getAddExpr(getZeroExtendExpr(Start, WideTy),
964 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
965 getZeroExtendExpr(Step, WideTy)));
966 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000967 // Return the expression with the addrec on the outside.
968 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
969 getZeroExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +0000970 // FIXME: can use FlagNUW
971 L, SCEV::FlagAnyWrap);
Dan Gohman01ecca22009-04-27 20:16:15 +0000972
973 // Similar to above, only this time treat the step value as signed.
974 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000975 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000976 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000977 OperandExtendedAdd =
978 getAddExpr(getZeroExtendExpr(Start, WideTy),
979 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
980 getSignExtendExpr(Step, WideTy)));
981 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000982 // Return the expression with the addrec on the outside.
983 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
984 getSignExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +0000985 // FIXME: can use FlagNW
986 L, SCEV::FlagAnyWrap);
Dan Gohman85b05a22009-07-13 21:35:55 +0000987 }
988
989 // If the backedge is guarded by a comparison with the pre-inc value
990 // the addrec is safe. Also, if the entry is guarded by a comparison
991 // with the start value and the backedge is guarded by a comparison
992 // with the post-inc value, the addrec is safe.
993 if (isKnownPositive(Step)) {
994 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
995 getUnsignedRange(Step).getUnsignedMax());
996 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000997 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000998 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
999 AR->getPostIncExpr(*this), N)))
1000 // Return the expression with the addrec on the outside.
1001 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1002 getZeroExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001003 // FIXME: can use FlagNUW
1004 L, SCEV::FlagAnyWrap);
Dan Gohman85b05a22009-07-13 21:35:55 +00001005 } else if (isKnownNegative(Step)) {
1006 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1007 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +00001008 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1009 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001010 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1011 AR->getPostIncExpr(*this), N)))
Andrew Trick3228cc22011-03-14 16:50:06 +00001012 // Return the expression with the addrec on the outside. The
1013 // negative step causes unsigned wrap, but it still can't self-wrap.
Dan Gohman85b05a22009-07-13 21:35:55 +00001014 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1015 getSignExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001016 // FIXME: can use FlagNW
1017 L, SCEV::FlagAnyWrap);
Dan Gohman01ecca22009-04-27 20:16:15 +00001018 }
1019 }
1020 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001021
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001022 // The cast wasn't folded; create an explicit cast node.
1023 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001025 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1026 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001027 UniqueSCEVs.InsertNode(S, IP);
1028 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001029}
1030
Dan Gohman0bba49c2009-07-07 17:06:11 +00001031const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001032 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001033 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001034 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001035 assert(isSCEVable(Ty) &&
1036 "This is not a conversion to a SCEVable type!");
1037 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001038
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001039 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001040 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1041 return getConstant(
1042 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1043 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001044
Dan Gohman20900ca2009-04-22 16:20:48 +00001045 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001046 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001047 return getSignExtendExpr(SS->getOperand(), Ty);
1048
Nick Lewycky73f565e2011-01-19 15:56:12 +00001049 // sext(zext(x)) --> zext(x)
1050 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1051 return getZeroExtendExpr(SZ->getOperand(), Ty);
1052
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001053 // Before doing any expensive analysis, check to see if we've already
1054 // computed a SCEV for this Op and Ty.
1055 FoldingSetNodeID ID;
1056 ID.AddInteger(scSignExtend);
1057 ID.AddPointer(Op);
1058 ID.AddPointer(Ty);
1059 void *IP = 0;
1060 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1061
Nick Lewycky9b8d2c22011-01-22 22:06:21 +00001062 // If the input value is provably positive, build a zext instead.
1063 if (isKnownNonNegative(Op))
1064 return getZeroExtendExpr(Op, Ty);
1065
Nick Lewycky630d85a2011-01-23 06:20:19 +00001066 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1067 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1068 // It's possible the bits taken off by the truncate were all sign bits. If
1069 // so, we should be able to simplify this further.
1070 const SCEV *X = ST->getOperand();
1071 ConstantRange CR = getSignedRange(X);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001072 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1073 unsigned NewBits = getTypeSizeInBits(Ty);
1074 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewycky76167af2011-01-23 20:06:05 +00001075 CR.sextOrTrunc(NewBits)))
1076 return getTruncateOrSignExtend(X, Ty);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001077 }
1078
Dan Gohman01ecca22009-04-27 20:16:15 +00001079 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001080 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001081 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001082 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001083 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001084 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001085 const SCEV *Start = AR->getStart();
1086 const SCEV *Step = AR->getStepRecurrence(*this);
1087 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1088 const Loop *L = AR->getLoop();
1089
Dan Gohmaneb490a72009-07-25 01:22:26 +00001090 // If we have special knowledge that this addrec won't overflow,
1091 // we don't need to do any further analysis.
Andrew Trick3228cc22011-03-14 16:50:06 +00001092 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Dan Gohmaneb490a72009-07-25 01:22:26 +00001093 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1094 getSignExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001095 // FIXME: can use SCEV::FlagNSW
1096 L, SCEV::FlagAnyWrap);
Dan Gohmaneb490a72009-07-25 01:22:26 +00001097
Dan Gohman01ecca22009-04-27 20:16:15 +00001098 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1099 // Note that this serves two purposes: It filters out loops that are
1100 // simply not analyzable, and it covers the case where this code is
1101 // being called from within backedge-taken count analysis, such that
1102 // attempting to ask for the backedge-taken count would likely result
1103 // in infinite recursion. In the later case, the analysis code will
1104 // cope with a conservative value, and it will take care to purge
1105 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001106 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001107 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001108 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001109 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001110
1111 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001112 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001113 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001114 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001115 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001116 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1117 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001118 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001119 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001120 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001121 const SCEV *Add = getAddExpr(Start, SMul);
1122 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001123 getAddExpr(getSignExtendExpr(Start, WideTy),
1124 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1125 getSignExtendExpr(Step, WideTy)));
1126 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001127 // Return the expression with the addrec on the outside.
1128 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1129 getSignExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001130 // FIXME: can use SCEV::FlagNSW
1131 L, SCEV::FlagAnyWrap);
Dan Gohman850f7912009-07-16 17:34:36 +00001132
1133 // Similar to above, only this time treat the step value as unsigned.
1134 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001135 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001136 Add = getAddExpr(Start, UMul);
1137 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001138 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001139 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1140 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001141 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001142 // Return the expression with the addrec on the outside.
1143 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1144 getZeroExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001145 // FIXME: can use SCEV::FlagNSW
1146 L, SCEV::FlagAnyWrap);
Dan Gohman85b05a22009-07-13 21:35:55 +00001147 }
1148
1149 // If the backedge is guarded by a comparison with the pre-inc value
1150 // the addrec is safe. Also, if the entry is guarded by a comparison
1151 // with the start value and the backedge is guarded by a comparison
1152 // with the post-inc value, the addrec is safe.
1153 if (isKnownPositive(Step)) {
1154 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1155 getSignedRange(Step).getSignedMax());
1156 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001157 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001158 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1159 AR->getPostIncExpr(*this), N)))
1160 // Return the expression with the addrec on the outside.
1161 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1162 getSignExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001163 // FIXME: can use SCEV::FlagNSW
1164 L, SCEV::FlagAnyWrap);
Dan Gohman85b05a22009-07-13 21:35:55 +00001165 } else if (isKnownNegative(Step)) {
1166 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1167 getSignedRange(Step).getSignedMin());
1168 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001169 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001170 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1171 AR->getPostIncExpr(*this), N)))
1172 // Return the expression with the addrec on the outside.
1173 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1174 getSignExtendExpr(Step, Ty),
Andrew Trick3228cc22011-03-14 16:50:06 +00001175 // FIXME: can use SCEV::FlagNSW
1176 L, SCEV::FlagAnyWrap);
Dan Gohman01ecca22009-04-27 20:16:15 +00001177 }
1178 }
1179 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001180
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001181 // The cast wasn't folded; create an explicit cast node.
1182 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001183 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001184 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1185 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001186 UniqueSCEVs.InsertNode(S, IP);
1187 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001188}
1189
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001190/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1191/// unspecified bits out to the given type.
1192///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001193const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001194 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001195 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1196 "This is not an extending conversion!");
1197 assert(isSCEVable(Ty) &&
1198 "This is not a conversion to a SCEVable type!");
1199 Ty = getEffectiveSCEVType(Ty);
1200
1201 // Sign-extend negative constants.
1202 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1203 if (SC->getValue()->getValue().isNegative())
1204 return getSignExtendExpr(Op, Ty);
1205
1206 // Peel off a truncate cast.
1207 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001208 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001209 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1210 return getAnyExtendExpr(NewOp, Ty);
1211 return getTruncateOrNoop(NewOp, Ty);
1212 }
1213
1214 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001215 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001216 if (!isa<SCEVZeroExtendExpr>(ZExt))
1217 return ZExt;
1218
1219 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001220 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001221 if (!isa<SCEVSignExtendExpr>(SExt))
1222 return SExt;
1223
Dan Gohmana10756e2010-01-21 02:09:26 +00001224 // Force the cast to be folded into the operands of an addrec.
1225 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1226 SmallVector<const SCEV *, 4> Ops;
1227 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1228 I != E; ++I)
1229 Ops.push_back(getAnyExtendExpr(*I, Ty));
Andrew Trick3228cc22011-03-14 16:50:06 +00001230 // FIXME: can use AR->getNoWrapFlags(SCEV::FlagNW)
1231 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohmana10756e2010-01-21 02:09:26 +00001232 }
1233
Dan Gohmanf53462d2010-07-15 20:02:11 +00001234 // As a special case, fold anyext(undef) to undef. We don't want to
1235 // know too much about SCEVUnknowns, but this special case is handy
1236 // and harmless.
1237 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1238 if (isa<UndefValue>(U->getValue()))
1239 return getSCEV(UndefValue::get(Ty));
1240
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001241 // If the expression is obviously signed, use the sext cast value.
1242 if (isa<SCEVSMaxExpr>(Op))
1243 return SExt;
1244
1245 // Absent any other information, use the zext cast value.
1246 return ZExt;
1247}
1248
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001249/// CollectAddOperandsWithScales - Process the given Ops list, which is
1250/// a list of operands to be added under the given scale, update the given
1251/// map. This is a helper function for getAddRecExpr. As an example of
1252/// what it does, given a sequence of operands that would form an add
1253/// expression like this:
1254///
1255/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1256///
1257/// where A and B are constants, update the map with these values:
1258///
1259/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1260///
1261/// and add 13 + A*B*29 to AccumulatedConstant.
1262/// This will allow getAddRecExpr to produce this:
1263///
1264/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1265///
1266/// This form often exposes folding opportunities that are hidden in
1267/// the original operand list.
1268///
1269/// Return true iff it appears that any interesting folding opportunities
1270/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1271/// the common case where no interesting opportunities are present, and
1272/// is also used as a check to avoid infinite recursion.
1273///
1274static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001275CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1276 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001277 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001278 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001279 const APInt &Scale,
1280 ScalarEvolution &SE) {
1281 bool Interesting = false;
1282
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001283 // Iterate over the add operands. They are sorted, with constants first.
1284 unsigned i = 0;
1285 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1286 ++i;
1287 // Pull a buried constant out to the outside.
1288 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1289 Interesting = true;
1290 AccumulatedConstant += Scale * C->getValue()->getValue();
1291 }
1292
1293 // Next comes everything else. We're especially interested in multiplies
1294 // here, but they're in the middle, so just visit the rest with one loop.
1295 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001296 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1297 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1298 APInt NewScale =
1299 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1300 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1301 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001302 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001303 Interesting |=
1304 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001305 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001306 NewScale, SE);
1307 } else {
1308 // A multiplication of a constant with some other value. Update
1309 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001310 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1311 const SCEV *Key = SE.getMulExpr(MulOps);
1312 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001313 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001314 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001315 NewOps.push_back(Pair.first->first);
1316 } else {
1317 Pair.first->second += NewScale;
1318 // The map already had an entry for this value, which may indicate
1319 // a folding opportunity.
1320 Interesting = true;
1321 }
1322 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001323 } else {
1324 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001325 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001326 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001327 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001328 NewOps.push_back(Pair.first->first);
1329 } else {
1330 Pair.first->second += Scale;
1331 // The map already had an entry for this value, which may indicate
1332 // a folding opportunity.
1333 Interesting = true;
1334 }
1335 }
1336 }
1337
1338 return Interesting;
1339}
1340
1341namespace {
1342 struct APIntCompare {
1343 bool operator()(const APInt &LHS, const APInt &RHS) const {
1344 return LHS.ult(RHS);
1345 }
1346 };
1347}
1348
Dan Gohman6c0866c2009-05-24 23:45:28 +00001349/// getAddExpr - Get a canonical add expression, or something simpler if
1350/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001351const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001352 SCEV::NoWrapFlags Flags) {
1353 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1354 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001356 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001357#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001358 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001359 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001360 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001361 "SCEVAddExpr operand types don't match!");
1362#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001363
Andrew Trick3228cc22011-03-14 16:50:06 +00001364 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1365 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001366 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001367 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1368 E = Ops.end(); I != E; ++I)
1369 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001370 All = false;
1371 break;
1372 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001373 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00001374 }
1375
Chris Lattner53e677a2004-04-02 20:23:17 +00001376 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001377 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001378
1379 // If there are any constants, fold them together.
1380 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001381 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001383 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001384 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001385 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001386 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1387 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001388 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001389 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001390 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001391 }
1392
1393 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001394 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 Ops.erase(Ops.begin());
1396 --Idx;
1397 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001398
Dan Gohmanbca091d2010-04-12 23:08:18 +00001399 if (Ops.size() == 1) return Ops[0];
1400 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001401
Dan Gohman68ff7762010-08-27 21:39:59 +00001402 // Okay, check to see if the same value occurs in the operand list more than
1403 // once. If so, merge them together into an multiply expression. Since we
1404 // sorted the list, these values are required to be adjacent.
Chris Lattner53e677a2004-04-02 20:23:17 +00001405 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001406 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001407 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001408 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001409 // Scan ahead to count how many equal operands there are.
1410 unsigned Count = 2;
1411 while (i+Count != e && Ops[i+Count] == Ops[i])
1412 ++Count;
1413 // Merge the values into a multiply.
1414 const SCEV *Scale = getConstant(Ty, Count);
1415 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1416 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001417 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001418 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001419 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001420 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001421 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001422 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001423 if (FoundMatch)
Andrew Trick3228cc22011-03-14 16:50:06 +00001424 return getAddExpr(Ops, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001425
Dan Gohman728c7f32009-05-08 21:03:19 +00001426 // Check for truncates. If all the operands are truncated from the same
1427 // type, see if factoring out the truncate would permit the result to be
1428 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1429 // if the contents of the resulting outer trunc fold to something simple.
1430 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1431 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1432 const Type *DstType = Trunc->getType();
1433 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001434 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001435 bool Ok = true;
1436 // Check all the operands to see if they can be represented in the
1437 // source type of the truncate.
1438 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1439 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1440 if (T->getOperand()->getType() != SrcType) {
1441 Ok = false;
1442 break;
1443 }
1444 LargeOps.push_back(T->getOperand());
1445 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001446 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001447 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001448 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001449 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1450 if (const SCEVTruncateExpr *T =
1451 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1452 if (T->getOperand()->getType() != SrcType) {
1453 Ok = false;
1454 break;
1455 }
1456 LargeMulOps.push_back(T->getOperand());
1457 } else if (const SCEVConstant *C =
1458 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001459 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001460 } else {
1461 Ok = false;
1462 break;
1463 }
1464 }
1465 if (Ok)
1466 LargeOps.push_back(getMulExpr(LargeMulOps));
1467 } else {
1468 Ok = false;
1469 break;
1470 }
1471 }
1472 if (Ok) {
1473 // Evaluate the expression in the larger type.
Andrew Trick3228cc22011-03-14 16:50:06 +00001474 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman728c7f32009-05-08 21:03:19 +00001475 // If it folds to something simple, use it. Otherwise, don't.
1476 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1477 return getTruncateExpr(Fold, DstType);
1478 }
1479 }
1480
1481 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001482 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1483 ++Idx;
1484
1485 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 if (Idx < Ops.size()) {
1487 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001488 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 // If we have an add, expand the add operands onto the end of the operands
1490 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001491 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001492 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 DeletedAdd = true;
1494 }
1495
1496 // If we deleted at least one add, we added operands to the end of the list,
1497 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001498 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001499 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001500 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001501 }
1502
1503 // Skip over the add expression until we get to a multiply.
1504 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1505 ++Idx;
1506
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001507 // Check to see if there are any folding opportunities present with
1508 // operands multiplied by constant values.
1509 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1510 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001511 DenseMap<const SCEV *, APInt> M;
1512 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001513 APInt AccumulatedConstant(BitWidth, 0);
1514 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001515 Ops.data(), Ops.size(),
1516 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001517 // Some interesting folding opportunity is present, so its worthwhile to
1518 // re-generate the operands list. Group the operands by constant scale,
1519 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001520 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001521 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001522 E = NewOps.end(); I != E; ++I)
1523 MulOpLists[M.find(*I)->second].push_back(*I);
1524 // Re-generate the operands list.
1525 Ops.clear();
1526 if (AccumulatedConstant != 0)
1527 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001528 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1529 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001530 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001531 Ops.push_back(getMulExpr(getConstant(I->first),
1532 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001533 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001534 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001535 if (Ops.size() == 1)
1536 return Ops[0];
1537 return getAddExpr(Ops);
1538 }
1539 }
1540
Chris Lattner53e677a2004-04-02 20:23:17 +00001541 // If we are adding something to a multiply expression, make sure the
1542 // something is not already an operand of the multiply. If so, merge it into
1543 // the multiply.
1544 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001545 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001546 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001547 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001548 if (isa<SCEVConstant>(MulOpSCEV))
1549 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001551 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001553 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 if (Mul->getNumOperands() != 2) {
1555 // If the multiply has more than two operands, we must get the
1556 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001557 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1558 Mul->op_begin()+MulOp);
1559 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001560 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001561 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001562 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001563 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001564 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 if (Ops.size() == 2) return OuterMul;
1566 if (AddOp < Idx) {
1567 Ops.erase(Ops.begin()+AddOp);
1568 Ops.erase(Ops.begin()+Idx-1);
1569 } else {
1570 Ops.erase(Ops.begin()+Idx);
1571 Ops.erase(Ops.begin()+AddOp-1);
1572 }
1573 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001574 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001576
Chris Lattner53e677a2004-04-02 20:23:17 +00001577 // Check this multiply against other multiplies being added together.
1578 for (unsigned OtherMulIdx = Idx+1;
1579 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1580 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001581 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001582 // If MulOp occurs in OtherMul, we can fold the two multiplies
1583 // together.
1584 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1585 OMulOp != e; ++OMulOp)
1586 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1587 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001588 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001590 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001591 Mul->op_begin()+MulOp);
1592 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001593 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001594 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001595 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001597 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001598 OtherMul->op_begin()+OMulOp);
1599 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001600 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001601 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001602 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1603 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001604 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001605 Ops.erase(Ops.begin()+Idx);
1606 Ops.erase(Ops.begin()+OtherMulIdx-1);
1607 Ops.push_back(OuterMul);
1608 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001609 }
1610 }
1611 }
1612 }
1613
1614 // If there are any add recurrences in the operands list, see if any other
1615 // added values are loop invariant. If so, we can fold them into the
1616 // recurrence.
1617 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1618 ++Idx;
1619
1620 // Scan over all recurrences, trying to fold loop invariants into them.
1621 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1622 // Scan all of the other operands to this add and add them to the vector if
1623 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001624 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001625 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001626 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001628 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001629 LIOps.push_back(Ops[i]);
1630 Ops.erase(Ops.begin()+i);
1631 --i; --e;
1632 }
1633
1634 // If we found some loop invariants, fold them into the recurrence.
1635 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001636 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001637 LIOps.push_back(AddRec->getStart());
1638
Dan Gohman0bba49c2009-07-07 17:06:11 +00001639 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001640 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001641 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001642
Dan Gohmanb9f96512010-06-30 07:16:37 +00001643 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher87376832011-01-11 09:02:09 +00001644 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trick3228cc22011-03-14 16:50:06 +00001645 // FIXME: Always propagate NW
1646 // AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW))
1647 Flags = AddRec->getNoWrapFlags(Flags);
1648 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman59de33e2009-12-18 18:45:31 +00001649
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 // If all of the other operands were loop invariant, we are done.
1651 if (Ops.size() == 1) return NewRec;
1652
1653 // Otherwise, add the folded AddRec by the non-liv parts.
1654 for (unsigned i = 0;; ++i)
1655 if (Ops[i] == AddRec) {
1656 Ops[i] = NewRec;
1657 break;
1658 }
Dan Gohman246b2562007-10-22 18:31:58 +00001659 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001660 }
1661
1662 // Okay, if there weren't any loop invariants to be folded, check to see if
1663 // there are multiple AddRec's with the same loop induction variable being
1664 // added together. If so, we can fold them.
1665 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001666 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1667 ++OtherIdx)
1668 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1669 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1670 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1671 AddRec->op_end());
1672 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1673 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001674 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001675 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001676 if (OtherAddRec->getLoop() == AddRecLoop) {
1677 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1678 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001679 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001680 AddRecOps.append(OtherAddRec->op_begin()+i,
1681 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001682 break;
1683 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001684 AddRecOps[i] = getAddExpr(AddRecOps[i],
1685 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001686 }
1687 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001688 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001689 // Step size has changed, so we cannot guarantee no self-wraparound.
1690 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohman32527152010-08-27 20:45:56 +00001691 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001692 }
1693
1694 // Otherwise couldn't fold anything into this recurrence. Move onto the
1695 // next one.
1696 }
1697
1698 // Okay, it looks like we really DO need an add expr. Check to see if we
1699 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001700 FoldingSetNodeID ID;
1701 ID.AddInteger(scAddExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001702 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1703 ID.AddPointer(Ops[i]);
1704 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001705 SCEVAddExpr *S =
1706 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1707 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001708 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1709 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001710 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1711 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001712 UniqueSCEVs.InsertNode(S, IP);
1713 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001714 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001715 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001716}
1717
Dan Gohman6c0866c2009-05-24 23:45:28 +00001718/// getMulExpr - Get a canonical multiply expression, or something simpler if
1719/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001720const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001721 SCEV::NoWrapFlags Flags) {
1722 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1723 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001724 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001725 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001726#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001727 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001728 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001729 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001730 "SCEVMulExpr operand types don't match!");
1731#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001732
Andrew Trick3228cc22011-03-14 16:50:06 +00001733 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1734 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001735 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001736 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1737 E = Ops.end(); I != E; ++I)
1738 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001739 All = false;
1740 break;
1741 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001742 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00001743 }
1744
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001746 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001747
1748 // If there are any constants, fold them together.
1749 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001750 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001751
1752 // C1*(C2+V) -> C1*C2 + C1*V
1753 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001754 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001755 if (Add->getNumOperands() == 2 &&
1756 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001757 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1758 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001759
Chris Lattner53e677a2004-04-02 20:23:17 +00001760 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001761 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001762 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001763 ConstantInt *Fold = ConstantInt::get(getContext(),
1764 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001765 RHSC->getValue()->getValue());
1766 Ops[0] = getConstant(Fold);
1767 Ops.erase(Ops.begin()+1); // Erase the folded element
1768 if (Ops.size() == 1) return Ops[0];
1769 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001770 }
1771
1772 // If we are left with a constant one being multiplied, strip it off.
1773 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1774 Ops.erase(Ops.begin());
1775 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001776 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 // If we have a multiply of zero, it will always be zero.
1778 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001779 } else if (Ops[0]->isAllOnesValue()) {
1780 // If we have a mul by -1 of an add, try distributing the -1 among the
1781 // add operands.
Andrew Trick3228cc22011-03-14 16:50:06 +00001782 if (Ops.size() == 2) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001783 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1784 SmallVector<const SCEV *, 4> NewOps;
1785 bool AnyFolded = false;
Andrew Trick3228cc22011-03-14 16:50:06 +00001786 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1787 E = Add->op_end(); I != E; ++I) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001788 const SCEV *Mul = getMulExpr(Ops[0], *I);
1789 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1790 NewOps.push_back(Mul);
1791 }
1792 if (AnyFolded)
1793 return getAddExpr(NewOps);
1794 }
Andrew Tricka053b212011-03-14 17:38:54 +00001795 else if (const SCEVAddRecExpr *
1796 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1797 // Negation preserves a recurrence's no self-wrap property.
1798 SmallVector<const SCEV *, 4> Operands;
1799 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1800 E = AddRec->op_end(); I != E; ++I) {
1801 Operands.push_back(getMulExpr(Ops[0], *I));
1802 }
1803 return getAddRecExpr(Operands, AddRec->getLoop(),
1804 AddRec->getNoWrapFlags(SCEV::FlagNW));
1805 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001806 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001807 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001808
1809 if (Ops.size() == 1)
1810 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001811 }
1812
1813 // Skip over the add expression until we get to a multiply.
1814 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1815 ++Idx;
1816
Chris Lattner53e677a2004-04-02 20:23:17 +00001817 // If there are mul operands inline them all into this expression.
1818 if (Idx < Ops.size()) {
1819 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001820 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001821 // If we have an mul, expand the mul operands onto the end of the operands
1822 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001823 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001824 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001825 DeletedMul = true;
1826 }
1827
1828 // If we deleted at least one mul, we added operands to the end of the list,
1829 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001830 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001831 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001832 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001833 }
1834
1835 // If there are any add recurrences in the operands list, see if any other
1836 // added values are loop invariant. If so, we can fold them into the
1837 // recurrence.
1838 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1839 ++Idx;
1840
1841 // Scan over all recurrences, trying to fold loop invariants into them.
1842 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1843 // Scan all of the other operands to this mul and add them to the vector if
1844 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001845 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001846 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001847 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001849 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001850 LIOps.push_back(Ops[i]);
1851 Ops.erase(Ops.begin()+i);
1852 --i; --e;
1853 }
1854
1855 // If we found some loop invariants, fold them into the recurrence.
1856 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001857 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001858 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001859 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001860 const SCEV *Scale = getMulExpr(LIOps);
1861 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1862 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001863
Dan Gohmanb9f96512010-06-30 07:16:37 +00001864 // Build the new addrec. Propagate the NUW and NSW flags if both the
1865 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick3228cc22011-03-14 16:50:06 +00001866 //
1867 // No self-wrap cannot be guaranteed after changing the step size, but
1868 // will be infered if either NUW or NSW is true.
1869 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1870 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001871
1872 // If all of the other operands were loop invariant, we are done.
1873 if (Ops.size() == 1) return NewRec;
1874
1875 // Otherwise, multiply the folded AddRec by the non-liv parts.
1876 for (unsigned i = 0;; ++i)
1877 if (Ops[i] == AddRec) {
1878 Ops[i] = NewRec;
1879 break;
1880 }
Dan Gohman246b2562007-10-22 18:31:58 +00001881 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001882 }
1883
1884 // Okay, if there weren't any loop invariants to be folded, check to see if
1885 // there are multiple AddRec's with the same loop induction variable being
1886 // multiplied together. If so, we can fold them.
1887 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001888 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1889 ++OtherIdx)
1890 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1891 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1892 // {A*C,+,F*D + G*B + B*D}<L>
1893 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1894 ++OtherIdx)
1895 if (const SCEVAddRecExpr *OtherAddRec =
1896 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1897 if (OtherAddRec->getLoop() == AddRecLoop) {
1898 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1899 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1900 const SCEV *B = F->getStepRecurrence(*this);
1901 const SCEV *D = G->getStepRecurrence(*this);
1902 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1903 getMulExpr(G, B),
1904 getMulExpr(B, D));
1905 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Andrew Trick3228cc22011-03-14 16:50:06 +00001906 F->getLoop(),
1907 SCEV::FlagAnyWrap);
Dan Gohman6a0c1252010-08-31 22:52:12 +00001908 if (Ops.size() == 2) return NewAddRec;
1909 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1910 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1911 }
1912 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001913 }
1914
1915 // Otherwise couldn't fold anything into this recurrence. Move onto the
1916 // next one.
1917 }
1918
1919 // Okay, it looks like we really DO need an mul expr. Check to see if we
1920 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001921 FoldingSetNodeID ID;
1922 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001923 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1924 ID.AddPointer(Ops[i]);
1925 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001926 SCEVMulExpr *S =
1927 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1928 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001929 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1930 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001931 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1932 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001933 UniqueSCEVs.InsertNode(S, IP);
1934 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001935 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001936 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001937}
1938
Andreas Bolka8a11c982009-08-07 22:55:26 +00001939/// getUDivExpr - Get a canonical unsigned division expression, or something
1940/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001941const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1942 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001943 assert(getEffectiveSCEVType(LHS->getType()) ==
1944 getEffectiveSCEVType(RHS->getType()) &&
1945 "SCEVUDivExpr operand types don't match!");
1946
Dan Gohman622ed672009-05-04 22:02:23 +00001947 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001948 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001949 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001950 // If the denominator is zero, the result of the udiv is undefined. Don't
1951 // try to analyze it, because the resolution chosen here may differ from
1952 // the resolution chosen in other parts of the compiler.
1953 if (!RHSC->getValue()->isZero()) {
1954 // Determine if the division can be folded into the operands of
1955 // its operands.
1956 // TODO: Generalize this to non-constants by using known-bits information.
1957 const Type *Ty = LHS->getType();
1958 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001959 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001960 // For non-power-of-two values, effectively round the value up to the
1961 // nearest power of two.
1962 if (!RHSC->getValue()->getValue().isPowerOf2())
1963 ++MaxShiftAmt;
1964 const IntegerType *ExtTy =
1965 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1966 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1967 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1968 if (const SCEVConstant *Step =
1969 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1970 if (!Step->getValue()->getValue()
1971 .urem(RHSC->getValue()->getValue()) &&
1972 getZeroExtendExpr(AR, ExtTy) ==
1973 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1974 getZeroExtendExpr(Step, ExtTy),
Andrew Trick3228cc22011-03-14 16:50:06 +00001975 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001976 SmallVector<const SCEV *, 4> Operands;
1977 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1978 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick3228cc22011-03-14 16:50:06 +00001979 return getAddRecExpr(Operands, AR->getLoop(),
1980 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
1981 SCEV::FlagAnyWrap);
Dan Gohman185cf032009-05-08 20:18:49 +00001982 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001983 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1984 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1985 SmallVector<const SCEV *, 4> Operands;
1986 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1987 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1988 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1989 // Find an operand that's safely divisible.
1990 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1991 const SCEV *Op = M->getOperand(i);
1992 const SCEV *Div = getUDivExpr(Op, RHSC);
1993 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1994 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1995 M->op_end());
1996 Operands[i] = Div;
1997 return getMulExpr(Operands);
1998 }
1999 }
Dan Gohman185cf032009-05-08 20:18:49 +00002000 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002001 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2002 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
2003 SmallVector<const SCEV *, 4> Operands;
2004 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2005 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2006 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2007 Operands.clear();
2008 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2009 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2010 if (isa<SCEVUDivExpr>(Op) ||
2011 getMulExpr(Op, RHS) != A->getOperand(i))
2012 break;
2013 Operands.push_back(Op);
2014 }
2015 if (Operands.size() == A->getNumOperands())
2016 return getAddExpr(Operands);
2017 }
2018 }
Dan Gohman185cf032009-05-08 20:18:49 +00002019
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002020 // Fold if both operands are constant.
2021 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2022 Constant *LHSCV = LHSC->getValue();
2023 Constant *RHSCV = RHSC->getValue();
2024 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2025 RHSCV)));
2026 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002027 }
2028 }
2029
Dan Gohman1c343752009-06-27 21:21:31 +00002030 FoldingSetNodeID ID;
2031 ID.AddInteger(scUDivExpr);
2032 ID.AddPointer(LHS);
2033 ID.AddPointer(RHS);
2034 void *IP = 0;
2035 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00002036 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2037 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00002038 UniqueSCEVs.InsertNode(S, IP);
2039 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002040}
2041
2042
Dan Gohman6c0866c2009-05-24 23:45:28 +00002043/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2044/// Simplify the expression as much as possible.
Andrew Trick3228cc22011-03-14 16:50:06 +00002045const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2046 const Loop *L,
2047 SCEV::NoWrapFlags Flags) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002048 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002049 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002050 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002051 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002052 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trick3228cc22011-03-14 16:50:06 +00002053 // FIXME: can use maskFlags(Flags, SCEV::FlagNW)
2054 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00002055 }
2056
2057 Operands.push_back(Step);
Andrew Trick3228cc22011-03-14 16:50:06 +00002058 return getAddRecExpr(Operands, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002059}
2060
Dan Gohman6c0866c2009-05-24 23:45:28 +00002061/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2062/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002063const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002064ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick3228cc22011-03-14 16:50:06 +00002065 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002066 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002067#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002068 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002069 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002070 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002071 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00002072 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002073 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00002074 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00002075#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002076
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002077 if (Operands.back()->isZero()) {
2078 Operands.pop_back();
Andrew Trick3228cc22011-03-14 16:50:06 +00002079 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002080 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002081
Dan Gohmanbc028532010-02-19 18:49:22 +00002082 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2083 // use that information to infer NUW and NSW flags. However, computing a
2084 // BE count requires calling getAddRecExpr, so we may not yet have a
2085 // meaningful BE count at this point (and if we don't, we'd be stuck
2086 // with a SCEVCouldNotCompute as the cached BE count).
2087
Andrew Trick3228cc22011-03-14 16:50:06 +00002088 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2089 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002090 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00002091 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2092 E = Operands.end(); I != E; ++I)
2093 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002094 All = false;
2095 break;
2096 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002097 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002098 }
2099
Dan Gohmand9cc7492008-08-08 18:33:12 +00002100 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002101 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002102 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002103 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002104 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002105 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002106 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002107 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002108 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002109 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002110 // AddRecs require their operands be loop-invariant with respect to their
2111 // loops. Don't perform this transformation if it would break this
2112 // requirement.
2113 bool AllInvariant = true;
2114 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002115 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002116 AllInvariant = false;
2117 break;
2118 }
2119 if (AllInvariant) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002120 // Create a recurrence for the outer loop with the same step size.
2121 //
2122 // FIXME:
2123 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2124 // inner recurrence has the same property.
2125 // maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2126 SCEV::NoWrapFlags OuterFlags = SCEV::FlagAnyWrap;
2127
2128 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohman9a80b452009-06-26 22:36:20 +00002129 AllInvariant = true;
2130 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002131 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002132 AllInvariant = false;
2133 break;
2134 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002135 if (AllInvariant) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002136 // Ok, both add recurrences are valid after the transformation.
Andrew Trick3228cc22011-03-14 16:50:06 +00002137 //
2138 // FIXME:
2139 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2140 // the outer recurrence has the same property.
2141 // maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2142 SCEV::NoWrapFlags InnerFlags = SCEV::FlagAnyWrap;
2143 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2144 }
Dan Gohman9a80b452009-06-26 22:36:20 +00002145 }
2146 // Reset Operands to its original state.
2147 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002148 }
2149 }
2150
Dan Gohman67847532010-01-19 22:27:22 +00002151 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2152 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002153 FoldingSetNodeID ID;
2154 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002155 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2156 ID.AddPointer(Operands[i]);
2157 ID.AddPointer(L);
2158 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002159 SCEVAddRecExpr *S =
2160 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2161 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002162 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2163 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002164 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2165 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002166 UniqueSCEVs.InsertNode(S, IP);
2167 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002168 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002169 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002170}
2171
Dan Gohman9311ef62009-06-24 14:49:00 +00002172const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2173 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002174 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002175 Ops.push_back(LHS);
2176 Ops.push_back(RHS);
2177 return getSMaxExpr(Ops);
2178}
2179
Dan Gohman0bba49c2009-07-07 17:06:11 +00002180const SCEV *
2181ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002182 assert(!Ops.empty() && "Cannot get empty smax!");
2183 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002184#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002185 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002186 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002187 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002188 "SCEVSMaxExpr operand types don't match!");
2189#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002190
2191 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002192 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002193
2194 // If there are any constants, fold them together.
2195 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002196 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002197 ++Idx;
2198 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002199 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002200 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002201 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002202 APIntOps::smax(LHSC->getValue()->getValue(),
2203 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002204 Ops[0] = getConstant(Fold);
2205 Ops.erase(Ops.begin()+1); // Erase the folded element
2206 if (Ops.size() == 1) return Ops[0];
2207 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002208 }
2209
Dan Gohmane5aceed2009-06-24 14:46:22 +00002210 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002211 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2212 Ops.erase(Ops.begin());
2213 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002214 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2215 // If we have an smax with a constant maximum-int, it will always be
2216 // maximum-int.
2217 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002218 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002219
Dan Gohman3ab13122010-04-13 16:49:23 +00002220 if (Ops.size() == 1) return Ops[0];
2221 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002222
2223 // Find the first SMax
2224 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2225 ++Idx;
2226
2227 // Check to see if one of the operands is an SMax. If so, expand its operands
2228 // onto our operand list, and recurse to simplify.
2229 if (Idx < Ops.size()) {
2230 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002231 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002232 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002233 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002234 DeletedSMax = true;
2235 }
2236
2237 if (DeletedSMax)
2238 return getSMaxExpr(Ops);
2239 }
2240
2241 // Okay, check to see if the same value occurs in the operand list twice. If
2242 // so, delete one. Since we sorted the list, these values are required to
2243 // be adjacent.
2244 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002245 // X smax Y smax Y --> X smax Y
2246 // X smax Y --> X, if X is always greater than Y
2247 if (Ops[i] == Ops[i+1] ||
2248 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2249 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2250 --i; --e;
2251 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002252 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2253 --i; --e;
2254 }
2255
2256 if (Ops.size() == 1) return Ops[0];
2257
2258 assert(!Ops.empty() && "Reduced smax down to nothing!");
2259
Nick Lewycky3e630762008-02-20 06:48:22 +00002260 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002261 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002262 FoldingSetNodeID ID;
2263 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002264 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2265 ID.AddPointer(Ops[i]);
2266 void *IP = 0;
2267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002268 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2269 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002270 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2271 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002272 UniqueSCEVs.InsertNode(S, IP);
2273 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002274}
2275
Dan Gohman9311ef62009-06-24 14:49:00 +00002276const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2277 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002278 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002279 Ops.push_back(LHS);
2280 Ops.push_back(RHS);
2281 return getUMaxExpr(Ops);
2282}
2283
Dan Gohman0bba49c2009-07-07 17:06:11 +00002284const SCEV *
2285ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002286 assert(!Ops.empty() && "Cannot get empty umax!");
2287 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002288#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002289 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002290 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002291 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002292 "SCEVUMaxExpr operand types don't match!");
2293#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002294
2295 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002296 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002297
2298 // If there are any constants, fold them together.
2299 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002301 ++Idx;
2302 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002303 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002304 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002305 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002306 APIntOps::umax(LHSC->getValue()->getValue(),
2307 RHSC->getValue()->getValue()));
2308 Ops[0] = getConstant(Fold);
2309 Ops.erase(Ops.begin()+1); // Erase the folded element
2310 if (Ops.size() == 1) return Ops[0];
2311 LHSC = cast<SCEVConstant>(Ops[0]);
2312 }
2313
Dan Gohmane5aceed2009-06-24 14:46:22 +00002314 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002315 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2316 Ops.erase(Ops.begin());
2317 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002318 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2319 // If we have an umax with a constant maximum-int, it will always be
2320 // maximum-int.
2321 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002322 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002323
Dan Gohman3ab13122010-04-13 16:49:23 +00002324 if (Ops.size() == 1) return Ops[0];
2325 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002326
2327 // Find the first UMax
2328 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2329 ++Idx;
2330
2331 // Check to see if one of the operands is a UMax. If so, expand its operands
2332 // onto our operand list, and recurse to simplify.
2333 if (Idx < Ops.size()) {
2334 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002335 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002336 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002337 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002338 DeletedUMax = true;
2339 }
2340
2341 if (DeletedUMax)
2342 return getUMaxExpr(Ops);
2343 }
2344
2345 // Okay, check to see if the same value occurs in the operand list twice. If
2346 // so, delete one. Since we sorted the list, these values are required to
2347 // be adjacent.
2348 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002349 // X umax Y umax Y --> X umax Y
2350 // X umax Y --> X, if X is always greater than Y
2351 if (Ops[i] == Ops[i+1] ||
2352 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2353 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2354 --i; --e;
2355 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002356 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2357 --i; --e;
2358 }
2359
2360 if (Ops.size() == 1) return Ops[0];
2361
2362 assert(!Ops.empty() && "Reduced umax down to nothing!");
2363
2364 // Okay, it looks like we really DO need a umax expr. Check to see if we
2365 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002366 FoldingSetNodeID ID;
2367 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002368 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2369 ID.AddPointer(Ops[i]);
2370 void *IP = 0;
2371 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002372 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2373 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002374 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2375 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002376 UniqueSCEVs.InsertNode(S, IP);
2377 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002378}
2379
Dan Gohman9311ef62009-06-24 14:49:00 +00002380const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2381 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002382 // ~smax(~x, ~y) == smin(x, y).
2383 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2384}
2385
Dan Gohman9311ef62009-06-24 14:49:00 +00002386const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2387 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002388 // ~umax(~x, ~y) == umin(x, y)
2389 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2390}
2391
Dan Gohman4f8eea82010-02-01 18:27:38 +00002392const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002393 // If we have TargetData, we can bypass creating a target-independent
2394 // constant expression and then folding it back into a ConstantInt.
2395 // This is just a compile-time optimization.
2396 if (TD)
2397 return getConstant(TD->getIntPtrType(getContext()),
2398 TD->getTypeAllocSize(AllocTy));
2399
Dan Gohman4f8eea82010-02-01 18:27:38 +00002400 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002402 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2403 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002404 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2405 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2406}
2407
2408const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2409 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002411 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2412 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002413 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2414 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2415}
2416
2417const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2418 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002419 // If we have TargetData, we can bypass creating a target-independent
2420 // constant expression and then folding it back into a ConstantInt.
2421 // This is just a compile-time optimization.
2422 if (TD)
2423 return getConstant(TD->getIntPtrType(getContext()),
2424 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2425
Dan Gohman0f5efe52010-01-28 02:15:55 +00002426 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2427 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002428 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2429 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002430 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002431 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002432}
2433
Dan Gohman4f8eea82010-02-01 18:27:38 +00002434const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2435 Constant *FieldNo) {
2436 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002438 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2439 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002440 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002441 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002442}
2443
Dan Gohman0bba49c2009-07-07 17:06:11 +00002444const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002445 // Don't attempt to do anything other than create a SCEVUnknown object
2446 // here. createSCEV only calls getUnknown after checking for all other
2447 // interesting possibilities, and any other code that calls getUnknown
2448 // is doing so in order to hide a value from SCEV canonicalization.
2449
Dan Gohman1c343752009-06-27 21:21:31 +00002450 FoldingSetNodeID ID;
2451 ID.AddInteger(scUnknown);
2452 ID.AddPointer(V);
2453 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002454 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2455 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2456 "Stale SCEVUnknown in uniquing map!");
2457 return S;
2458 }
2459 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2460 FirstUnknown);
2461 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002462 UniqueSCEVs.InsertNode(S, IP);
2463 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002464}
2465
Chris Lattner53e677a2004-04-02 20:23:17 +00002466//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002467// Basic SCEV Analysis and PHI Idiom Recognition Code
2468//
2469
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002470/// isSCEVable - Test if values of the given type are analyzable within
2471/// the SCEV framework. This primarily includes integer types, and it
2472/// can optionally include pointer types if the ScalarEvolution class
2473/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002474bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002475 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002476 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002477}
2478
2479/// getTypeSizeInBits - Return the size in bits of the specified type,
2480/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002481uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002482 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2483
2484 // If we have a TargetData, use it!
2485 if (TD)
2486 return TD->getTypeSizeInBits(Ty);
2487
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002488 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002489 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002490 return Ty->getPrimitiveSizeInBits();
2491
2492 // The only other support type is pointer. Without TargetData, conservatively
2493 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002494 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002495 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002496}
2497
2498/// getEffectiveSCEVType - Return a type with the same bitwidth as
2499/// the given type and which represents how SCEV will treat the given
2500/// type, for which isSCEVable must return true. For pointer types,
2501/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002502const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002503 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2504
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002505 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002506 return Ty;
2507
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002508 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002509 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002510 if (TD) return TD->getIntPtrType(getContext());
2511
2512 // Without TargetData, conservatively assume pointers are 64-bit.
2513 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002514}
Chris Lattner53e677a2004-04-02 20:23:17 +00002515
Dan Gohman0bba49c2009-07-07 17:06:11 +00002516const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002517 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002518}
2519
Chris Lattner53e677a2004-04-02 20:23:17 +00002520/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2521/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002522const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002523 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002524
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002525 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2526 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002527 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002528
2529 // The process of creating a SCEV for V may have caused other SCEVs
2530 // to have been created, so it's necessary to insert the new entry
2531 // from scratch, rather than trying to remember the insert position
2532 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002533 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002534 return S;
2535}
2536
Dan Gohman2d1be872009-04-16 03:18:22 +00002537/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2538///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002539const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002540 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002541 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002542 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002543
2544 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002545 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002546 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002547 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002548}
2549
2550/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002551const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002552 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002553 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002554 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002555
2556 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002557 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002558 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002559 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002560 return getMinusSCEV(AllOnes, V);
2561}
2562
Andrew Trick3228cc22011-03-14 16:50:06 +00002563/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
2564///
2565/// FIXME: prohibit FlagNUW here, as soon as getMinusSCEVForExitTest goes.
Chris Lattner992efb02011-01-09 22:26:35 +00002566const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00002567 SCEV::NoWrapFlags Flags) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002568 // Fast path: X - X --> 0.
2569 if (LHS == RHS)
2570 return getConstant(LHS->getType(), 0);
2571
Dan Gohman2d1be872009-04-16 03:18:22 +00002572 // X - Y --> X + -Y
Andrew Trick3228cc22011-03-14 16:50:06 +00002573 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman2d1be872009-04-16 03:18:22 +00002574}
2575
2576/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2577/// input value to the specified type. If the type must be extended, it is zero
2578/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002579const SCEV *
Chris Lattner992efb02011-01-09 22:26:35 +00002580ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002581 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002582 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2583 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002584 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002585 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002586 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002587 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002588 return getTruncateExpr(V, Ty);
2589 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002590}
2591
2592/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2593/// input value to the specified type. If the type must be extended, it is sign
2594/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002595const SCEV *
2596ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002597 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002598 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002599 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2600 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002601 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002602 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002603 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002604 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002605 return getTruncateExpr(V, Ty);
2606 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002607}
2608
Dan Gohman467c4302009-05-13 03:46:30 +00002609/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2610/// input value to the specified type. If the type must be extended, it is zero
2611/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002612const SCEV *
2613ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002614 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002615 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2616 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002617 "Cannot noop or zero extend with non-integer arguments!");
2618 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2619 "getNoopOrZeroExtend cannot truncate!");
2620 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2621 return V; // No conversion
2622 return getZeroExtendExpr(V, Ty);
2623}
2624
2625/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2626/// input value to the specified type. If the type must be extended, it is sign
2627/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002628const SCEV *
2629ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002630 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002631 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2632 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002633 "Cannot noop or sign extend with non-integer arguments!");
2634 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2635 "getNoopOrSignExtend cannot truncate!");
2636 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2637 return V; // No conversion
2638 return getSignExtendExpr(V, Ty);
2639}
2640
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002641/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2642/// the input value to the specified type. If the type must be extended,
2643/// it is extended with unspecified bits. The conversion must not be
2644/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002645const SCEV *
2646ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002647 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002648 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2649 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002650 "Cannot noop or any extend with non-integer arguments!");
2651 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2652 "getNoopOrAnyExtend cannot truncate!");
2653 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2654 return V; // No conversion
2655 return getAnyExtendExpr(V, Ty);
2656}
2657
Dan Gohman467c4302009-05-13 03:46:30 +00002658/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2659/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002660const SCEV *
2661ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002662 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002663 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2664 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002665 "Cannot truncate or noop with non-integer arguments!");
2666 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2667 "getTruncateOrNoop cannot extend!");
2668 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2669 return V; // No conversion
2670 return getTruncateExpr(V, Ty);
2671}
2672
Dan Gohmana334aa72009-06-22 00:31:57 +00002673/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2674/// the types using zero-extension, and then perform a umax operation
2675/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002676const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2677 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002678 const SCEV *PromotedLHS = LHS;
2679 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002680
2681 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2682 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2683 else
2684 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2685
2686 return getUMaxExpr(PromotedLHS, PromotedRHS);
2687}
2688
Dan Gohmanc9759e82009-06-22 15:03:27 +00002689/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2690/// the types using zero-extension, and then perform a umin operation
2691/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002692const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2693 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002694 const SCEV *PromotedLHS = LHS;
2695 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002696
2697 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2698 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2699 else
2700 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2701
2702 return getUMinExpr(PromotedLHS, PromotedRHS);
2703}
2704
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002705/// PushDefUseChildren - Push users of the given Instruction
2706/// onto the given Worklist.
2707static void
2708PushDefUseChildren(Instruction *I,
2709 SmallVectorImpl<Instruction *> &Worklist) {
2710 // Push the def-use children onto the Worklist stack.
2711 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2712 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002713 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002714}
2715
2716/// ForgetSymbolicValue - This looks up computed SCEV values for all
2717/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002718/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002719/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002720void
Dan Gohman85669632010-02-25 06:57:05 +00002721ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002722 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002723 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002724
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002725 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002726 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002727 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002728 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002729 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002730
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002731 ValueExprMapType::iterator It =
2732 ValueExprMap.find(static_cast<Value *>(I));
2733 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002734 const SCEV *Old = It->second;
2735
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002736 // Short-circuit the def-use traversal if the symbolic name
2737 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002738 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002739 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002740
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002741 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002742 // structure, it's a PHI that's in the progress of being computed
2743 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2744 // additional loop trip count information isn't going to change anything.
2745 // In the second case, createNodeForPHI will perform the necessary
2746 // updates on its own when it gets to that point. In the third, we do
2747 // want to forget the SCEVUnknown.
2748 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002749 !isa<SCEVUnknown>(Old) ||
2750 (I != PN && Old == SymName)) {
Dan Gohman56a75682010-11-17 23:28:48 +00002751 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002752 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002753 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002754 }
2755
2756 PushDefUseChildren(I, Worklist);
2757 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002758}
Chris Lattner53e677a2004-04-02 20:23:17 +00002759
2760/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2761/// a loop header, making it a potential recurrence, or it doesn't.
2762///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002763const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002764 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2765 if (L->getHeader() == PN->getParent()) {
2766 // The loop may have multiple entrances or multiple exits; we can analyze
2767 // this phi as an addrec if it has a unique entry value and a unique
2768 // backedge value.
2769 Value *BEValueV = 0, *StartValueV = 0;
2770 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2771 Value *V = PN->getIncomingValue(i);
2772 if (L->contains(PN->getIncomingBlock(i))) {
2773 if (!BEValueV) {
2774 BEValueV = V;
2775 } else if (BEValueV != V) {
2776 BEValueV = 0;
2777 break;
2778 }
2779 } else if (!StartValueV) {
2780 StartValueV = V;
2781 } else if (StartValueV != V) {
2782 StartValueV = 0;
2783 break;
2784 }
2785 }
2786 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002787 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002788 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002789 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002790 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002791 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002792
2793 // Using this symbolic name for the PHI, analyze the value coming around
2794 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002795 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002796
2797 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2798 // has a special value for the first iteration of the loop.
2799
2800 // If the value coming around the backedge is an add with the symbolic
2801 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002802 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002803 // If there is a single occurrence of the symbolic value, replace it
2804 // with a recurrence.
2805 unsigned FoundIndex = Add->getNumOperands();
2806 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2807 if (Add->getOperand(i) == SymbolicName)
2808 if (FoundIndex == e) {
2809 FoundIndex = i;
2810 break;
2811 }
2812
2813 if (FoundIndex != Add->getNumOperands()) {
2814 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002815 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002816 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2817 if (i != FoundIndex)
2818 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002819 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002820
2821 // This is not a valid addrec if the step amount is varying each
2822 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002823 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002824 (isa<SCEVAddRecExpr>(Accum) &&
2825 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002826 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohmana10756e2010-01-21 02:09:26 +00002827
2828 // If the increment doesn't overflow, then neither the addrec nor
2829 // the post-increment will overflow.
2830 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2831 if (OBO->hasNoUnsignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002832 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002833 if (OBO->hasNoSignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002834 Flags = setFlags(Flags, SCEV::FlagNSW);
Andrew Trick635f7182011-03-09 17:23:39 +00002835 } else if (const GEPOperator *GEP =
Andrew Trick3228cc22011-03-14 16:50:06 +00002836 dyn_cast<GEPOperator>(BEValueV)) {
2837 // If the increment is an inbounds GEP, then we know the address
2838 // space cannot be wrapped around. We cannot make any guarantee
2839 // about signed or unsigned overflow because pointers are
2840 // unsigned but we may have a negative index from the base
2841 // pointer.
2842 if (GEP->isInBounds())
2843 // FIXME: should be SCEV::FlagNW
2844 Flags = setFlags(Flags, SCEV::FlagNSW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002845 }
2846
Dan Gohman27dead42010-04-12 07:49:36 +00002847 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick3228cc22011-03-14 16:50:06 +00002848 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002849
Dan Gohmana10756e2010-01-21 02:09:26 +00002850 // Since the no-wrap flags are on the increment, they apply to the
2851 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002852 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00002853 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick3228cc22011-03-14 16:50:06 +00002854 Accum, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002855
2856 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002857 // to be symbolic. We now need to go back and purge all of the
2858 // entries for the scalars that use the symbolic expression.
2859 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002860 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002861 return PHISCEV;
2862 }
2863 }
Dan Gohman622ed672009-05-04 22:02:23 +00002864 } else if (const SCEVAddRecExpr *AddRec =
2865 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002866 // Otherwise, this could be a loop like this:
2867 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2868 // In this case, j = {1,+,1} and BEValue is j.
2869 // Because the other in-value of i (0) fits the evolution of BEValue
2870 // i really is an addrec evolution.
2871 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002872 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002873
2874 // If StartVal = j.start - j.stride, we can use StartVal as the
2875 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002876 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002877 AddRec->getOperand(1))) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002878 // FIXME: For constant StartVal, we should be able to infer
2879 // no-wrap flags.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002880 const SCEV *PHISCEV =
Andrew Trick3228cc22011-03-14 16:50:06 +00002881 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
2882 SCEV::FlagAnyWrap);
Chris Lattner97156e72006-04-26 18:34:07 +00002883
2884 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002885 // to be symbolic. We now need to go back and purge all of the
2886 // entries for the scalars that use the symbolic expression.
2887 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002888 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002889 return PHISCEV;
2890 }
2891 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002892 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002893 }
Dan Gohman27dead42010-04-12 07:49:36 +00002894 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002895
Dan Gohman85669632010-02-25 06:57:05 +00002896 // If the PHI has a single incoming value, follow that value, unless the
2897 // PHI's incoming blocks are in a different loop, in which case doing so
2898 // risks breaking LCSSA form. Instcombine would normally zap these, but
2899 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00002900 if (Value *V = SimplifyInstruction(PN, TD, DT))
2901 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohman85669632010-02-25 06:57:05 +00002902 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002903
Chris Lattner53e677a2004-04-02 20:23:17 +00002904 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002905 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002906}
2907
Dan Gohman26466c02009-05-08 20:26:55 +00002908/// createNodeForGEP - Expand GEP instructions into add and multiply
2909/// operations. This allows them to be analyzed by regular SCEV code.
2910///
Dan Gohmand281ed22009-12-18 02:09:29 +00002911const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002912
Dan Gohmanb9f96512010-06-30 07:16:37 +00002913 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2914 // Add expression, because the Instruction may be guarded by control flow
2915 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002916 // context.
Chris Lattner8ebaf902011-02-13 03:14:49 +00002917 bool isInBounds = GEP->isInBounds();
Dan Gohman7a642572010-06-29 01:41:41 +00002918
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002919 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002920 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002921 // Don't attempt to analyze GEPs over unsized objects.
2922 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2923 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002924 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002925 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002926 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002927 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002928 I != E; ++I) {
2929 Value *Index = *I;
2930 // Compute the (potentially symbolic) offset in bytes for this index.
2931 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2932 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002933 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002934 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2935
Dan Gohmanb9f96512010-06-30 07:16:37 +00002936 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002937 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002938 } else {
2939 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002940 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2941 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002942 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002943 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2944
Dan Gohmanb9f96512010-06-30 07:16:37 +00002945 // Multiply the index by the element size to compute the element offset.
Andrew Trick3228cc22011-03-14 16:50:06 +00002946 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
2947 isInBounds ? SCEV::FlagNSW :
2948 SCEV::FlagAnyWrap);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002949
2950 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002951 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002952 }
2953 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002954
2955 // Get the SCEV for the GEP base.
2956 const SCEV *BaseS = getSCEV(Base);
2957
Dan Gohmanb9f96512010-06-30 07:16:37 +00002958 // Add the total offset from all the GEP indices to the base.
Andrew Trick3228cc22011-03-14 16:50:06 +00002959 return getAddExpr(BaseS, TotalOffset,
2960 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
Dan Gohman26466c02009-05-08 20:26:55 +00002961}
2962
Nick Lewycky83bb0052007-11-22 07:59:40 +00002963/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2964/// guaranteed to end in (at every loop iteration). It is, at the same time,
2965/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2966/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002967uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002968ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002969 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002970 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002971
Dan Gohman622ed672009-05-04 22:02:23 +00002972 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002973 return std::min(GetMinTrailingZeros(T->getOperand()),
2974 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002975
Dan Gohman622ed672009-05-04 22:02:23 +00002976 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002977 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2978 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2979 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002980 }
2981
Dan Gohman622ed672009-05-04 22:02:23 +00002982 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002983 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2984 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2985 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002986 }
2987
Dan Gohman622ed672009-05-04 22:02:23 +00002988 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002989 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002990 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002991 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002992 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002993 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002994 }
2995
Dan Gohman622ed672009-05-04 22:02:23 +00002996 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002997 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002998 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2999 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00003000 for (unsigned i = 1, e = M->getNumOperands();
3001 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003002 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00003003 BitWidth);
3004 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003005 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003006
Dan Gohman622ed672009-05-04 22:02:23 +00003007 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003008 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003009 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003010 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003011 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003012 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003013 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003014
Dan Gohman622ed672009-05-04 22:02:23 +00003015 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003016 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003017 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003018 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003019 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003020 return MinOpRes;
3021 }
3022
Dan Gohman622ed672009-05-04 22:02:23 +00003023 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00003024 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003025 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00003026 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003027 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00003028 return MinOpRes;
3029 }
3030
Dan Gohman2c364ad2009-06-19 23:29:04 +00003031 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3032 // For a SCEVUnknown, ask ValueTracking.
3033 unsigned BitWidth = getTypeSizeInBits(U->getType());
3034 APInt Mask = APInt::getAllOnesValue(BitWidth);
3035 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3036 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3037 return Zeros.countTrailingOnes();
3038 }
3039
3040 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00003041 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00003042}
Chris Lattner53e677a2004-04-02 20:23:17 +00003043
Dan Gohman85b05a22009-07-13 21:35:55 +00003044/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3045///
3046ConstantRange
3047ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003048 // See if we've computed this range already.
3049 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3050 if (I != UnsignedRanges.end())
3051 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003052
3053 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003054 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003055
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003056 unsigned BitWidth = getTypeSizeInBits(S->getType());
3057 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3058
3059 // If the value has known zeros, the maximum unsigned value will have those
3060 // known zeros as well.
3061 uint32_t TZ = GetMinTrailingZeros(S);
3062 if (TZ != 0)
3063 ConservativeResult =
3064 ConstantRange(APInt::getMinValue(BitWidth),
3065 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3066
Dan Gohman85b05a22009-07-13 21:35:55 +00003067 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3068 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3069 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3070 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003071 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003072 }
3073
3074 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3075 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3076 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3077 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003078 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003079 }
3080
3081 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3082 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3083 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3084 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003085 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003086 }
3087
3088 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3089 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3090 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3091 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003092 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003093 }
3094
3095 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3096 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3097 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003098 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003099 }
3100
3101 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3102 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003103 return setUnsignedRange(ZExt,
3104 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003105 }
3106
3107 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3108 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003109 return setUnsignedRange(SExt,
3110 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003111 }
3112
3113 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3114 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003115 return setUnsignedRange(Trunc,
3116 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003117 }
3118
Dan Gohman85b05a22009-07-13 21:35:55 +00003119 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003120 // If there's no unsigned wrap, the value will never be less than its
3121 // initial value.
Andrew Trick3228cc22011-03-14 16:50:06 +00003122 // FIXME: can broaden to FlagNW?
3123 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmana10756e2010-01-21 02:09:26 +00003124 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003125 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003126 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003127 ConservativeResult.intersectWith(
3128 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003129
3130 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003131 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003132 const Type *Ty = AddRec->getType();
3133 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003134 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3135 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003136 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3137
3138 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003139 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003140
3141 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003142 ConstantRange StepRange = getSignedRange(Step);
3143 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3144 ConstantRange EndRange =
3145 StartRange.add(MaxBECountRange.multiply(StepRange));
3146
3147 // Check for overflow. This must be done with ConstantRange arithmetic
3148 // because we could be called from within the ScalarEvolution overflow
3149 // checking code.
3150 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3151 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3152 ConstantRange ExtMaxBECountRange =
3153 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3154 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3155 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3156 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003157 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003158
Dan Gohman85b05a22009-07-13 21:35:55 +00003159 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3160 EndRange.getUnsignedMin());
3161 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3162 EndRange.getUnsignedMax());
3163 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003164 return setUnsignedRange(AddRec, ConservativeResult);
3165 return setUnsignedRange(AddRec,
3166 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003167 }
3168 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003169
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003170 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003171 }
3172
3173 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3174 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003175 APInt Mask = APInt::getAllOnesValue(BitWidth);
3176 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3177 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003178 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003179 return setUnsignedRange(U, ConservativeResult);
3180 return setUnsignedRange(U,
3181 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003182 }
3183
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003184 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003185}
3186
Dan Gohman85b05a22009-07-13 21:35:55 +00003187/// getSignedRange - Determine the signed range for a particular SCEV.
3188///
3189ConstantRange
3190ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohmana3bbf242011-01-24 17:54:18 +00003191 // See if we've computed this range already.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003192 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3193 if (I != SignedRanges.end())
3194 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003195
Dan Gohman85b05a22009-07-13 21:35:55 +00003196 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003197 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003198
Dan Gohman52fddd32010-01-26 04:40:18 +00003199 unsigned BitWidth = getTypeSizeInBits(S->getType());
3200 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3201
3202 // If the value has known zeros, the maximum signed value will have those
3203 // known zeros as well.
3204 uint32_t TZ = GetMinTrailingZeros(S);
3205 if (TZ != 0)
3206 ConservativeResult =
3207 ConstantRange(APInt::getSignedMinValue(BitWidth),
3208 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3209
Dan Gohman85b05a22009-07-13 21:35:55 +00003210 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3211 ConstantRange X = getSignedRange(Add->getOperand(0));
3212 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3213 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003214 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003215 }
3216
Dan Gohman85b05a22009-07-13 21:35:55 +00003217 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3218 ConstantRange X = getSignedRange(Mul->getOperand(0));
3219 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3220 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003221 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003222 }
3223
Dan Gohman85b05a22009-07-13 21:35:55 +00003224 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3225 ConstantRange X = getSignedRange(SMax->getOperand(0));
3226 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3227 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003228 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003229 }
Dan Gohman62849c02009-06-24 01:05:09 +00003230
Dan Gohman85b05a22009-07-13 21:35:55 +00003231 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3232 ConstantRange X = getSignedRange(UMax->getOperand(0));
3233 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3234 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003235 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003236 }
Dan Gohman62849c02009-06-24 01:05:09 +00003237
Dan Gohman85b05a22009-07-13 21:35:55 +00003238 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3239 ConstantRange X = getSignedRange(UDiv->getLHS());
3240 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003241 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003242 }
Dan Gohman62849c02009-06-24 01:05:09 +00003243
Dan Gohman85b05a22009-07-13 21:35:55 +00003244 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3245 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003246 return setSignedRange(ZExt,
3247 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003248 }
3249
3250 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3251 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003252 return setSignedRange(SExt,
3253 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003254 }
3255
3256 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3257 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003258 return setSignedRange(Trunc,
3259 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003260 }
3261
Dan Gohman85b05a22009-07-13 21:35:55 +00003262 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003263 // If there's no signed wrap, and all the operands have the same sign or
3264 // zero, the value won't ever change sign.
Andrew Trick3228cc22011-03-14 16:50:06 +00003265 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003266 bool AllNonNeg = true;
3267 bool AllNonPos = true;
3268 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3269 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3270 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3271 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003272 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003273 ConservativeResult = ConservativeResult.intersectWith(
3274 ConstantRange(APInt(BitWidth, 0),
3275 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003276 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003277 ConservativeResult = ConservativeResult.intersectWith(
3278 ConstantRange(APInt::getSignedMinValue(BitWidth),
3279 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003280 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003281
3282 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003283 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003284 const Type *Ty = AddRec->getType();
3285 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003286 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3287 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003288 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3289
3290 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003291 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003292
3293 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003294 ConstantRange StepRange = getSignedRange(Step);
3295 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3296 ConstantRange EndRange =
3297 StartRange.add(MaxBECountRange.multiply(StepRange));
3298
3299 // Check for overflow. This must be done with ConstantRange arithmetic
3300 // because we could be called from within the ScalarEvolution overflow
3301 // checking code.
3302 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3303 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3304 ConstantRange ExtMaxBECountRange =
3305 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3306 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3307 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3308 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003309 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003310
Dan Gohman85b05a22009-07-13 21:35:55 +00003311 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3312 EndRange.getSignedMin());
3313 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3314 EndRange.getSignedMax());
3315 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003316 return setSignedRange(AddRec, ConservativeResult);
3317 return setSignedRange(AddRec,
3318 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003319 }
Dan Gohman62849c02009-06-24 01:05:09 +00003320 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003321
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003322 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003323 }
3324
Dan Gohman2c364ad2009-06-19 23:29:04 +00003325 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3326 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003327 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003328 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003329 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3330 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003331 return setSignedRange(U, ConservativeResult);
3332 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003333 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003334 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003335 }
3336
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003337 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003338}
3339
Chris Lattner53e677a2004-04-02 20:23:17 +00003340/// createSCEV - We know that there is no SCEV for the specified value.
3341/// Analyze the expression.
3342///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003343const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003344 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003345 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003346
Dan Gohman6c459a22008-06-22 19:56:46 +00003347 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003348 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003349 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003350
3351 // Don't attempt to analyze instructions in blocks that aren't
3352 // reachable. Such instructions don't matter, and they aren't required
3353 // to obey basic rules for definitions dominating uses which this
3354 // analysis depends on.
3355 if (!DT->isReachableFromEntry(I->getParent()))
3356 return getUnknown(V);
3357 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003358 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003359 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3360 return getConstant(CI);
3361 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003362 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003363 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3364 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003365 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003366 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003367
Dan Gohmanca178902009-07-17 20:47:02 +00003368 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003369 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003370 case Instruction::Add: {
3371 // The simple thing to do would be to just call getSCEV on both operands
3372 // and call getAddExpr with the result. However if we're looking at a
3373 // bunch of things all added together, this can be quite inefficient,
3374 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3375 // Instead, gather up all the operands and make a single getAddExpr call.
3376 // LLVM IR canonical form means we need only traverse the left operands.
3377 SmallVector<const SCEV *, 4> AddOps;
3378 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003379 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3380 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3381 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3382 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003383 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003384 const SCEV *Op1 = getSCEV(U->getOperand(1));
3385 if (Opcode == Instruction::Sub)
3386 AddOps.push_back(getNegativeSCEV(Op1));
3387 else
3388 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003389 }
3390 AddOps.push_back(getSCEV(U->getOperand(0)));
3391 return getAddExpr(AddOps);
3392 }
3393 case Instruction::Mul: {
3394 // See the Add code above.
3395 SmallVector<const SCEV *, 4> MulOps;
3396 MulOps.push_back(getSCEV(U->getOperand(1)));
3397 for (Value *Op = U->getOperand(0);
Andrew Trick635f7182011-03-09 17:23:39 +00003398 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003399 Op = U->getOperand(0)) {
3400 U = cast<Operator>(Op);
3401 MulOps.push_back(getSCEV(U->getOperand(1)));
3402 }
3403 MulOps.push_back(getSCEV(U->getOperand(0)));
3404 return getMulExpr(MulOps);
3405 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003406 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003407 return getUDivExpr(getSCEV(U->getOperand(0)),
3408 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003409 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003410 return getMinusSCEV(getSCEV(U->getOperand(0)),
3411 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003412 case Instruction::And:
3413 // For an expression like x&255 that merely masks off the high bits,
3414 // use zext(trunc(x)) as the SCEV expression.
3415 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003416 if (CI->isNullValue())
3417 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003418 if (CI->isAllOnesValue())
3419 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003420 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003421
3422 // Instcombine's ShrinkDemandedConstant may strip bits out of
3423 // constants, obscuring what would otherwise be a low-bits mask.
3424 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3425 // knew about to reconstruct a low-bits mask value.
3426 unsigned LZ = A.countLeadingZeros();
3427 unsigned BitWidth = A.getBitWidth();
3428 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3429 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3430 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3431
3432 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3433
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003434 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003435 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003436 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003437 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003438 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003439 }
3440 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003441
Dan Gohman6c459a22008-06-22 19:56:46 +00003442 case Instruction::Or:
3443 // If the RHS of the Or is a constant, we may have something like:
3444 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3445 // optimizations will transparently handle this case.
3446 //
3447 // In order for this transformation to be safe, the LHS must be of the
3448 // form X*(2^n) and the Or constant must be less than 2^n.
3449 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003450 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003451 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003452 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003453 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3454 // Build a plain add SCEV.
3455 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3456 // If the LHS of the add was an addrec and it has no-wrap flags,
3457 // transfer the no-wrap flags, since an or won't introduce a wrap.
3458 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3459 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick3228cc22011-03-14 16:50:06 +00003460 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3461 OldAR->getNoWrapFlags());
Dan Gohman1f96e672009-09-17 18:05:20 +00003462 }
3463 return S;
3464 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003465 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003466 break;
3467 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003468 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003469 // If the RHS of the xor is a signbit, then this is just an add.
3470 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003471 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003472 return getAddExpr(getSCEV(U->getOperand(0)),
3473 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003474
3475 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003476 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003477 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003478
3479 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3480 // This is a variant of the check for xor with -1, and it handles
3481 // the case where instcombine has trimmed non-demanded bits out
3482 // of an xor with -1.
3483 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3484 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3485 if (BO->getOpcode() == Instruction::And &&
3486 LCI->getValue() == CI->getValue())
3487 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003488 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003489 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003490 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003491 const Type *Z0Ty = Z0->getType();
3492 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3493
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003494 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003495 // mask off the high bits. Complement the operand and
3496 // re-apply the zext.
3497 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3498 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3499
3500 // If C is a single bit, it may be in the sign-bit position
3501 // before the zero-extend. In this case, represent the xor
3502 // using an add, which is equivalent, and re-apply the zext.
Jay Foad40f8f622010-12-07 08:25:19 +00003503 APInt Trunc = CI->getValue().trunc(Z0TySize);
3504 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohman82052832009-06-18 00:00:20 +00003505 Trunc.isSignBit())
3506 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3507 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003508 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003509 }
3510 break;
3511
3512 case Instruction::Shl:
3513 // Turn shift left of a constant amount into a multiply.
3514 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003515 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003516
3517 // If the shift count is not less than the bitwidth, the result of
3518 // the shift is undefined. Don't try to analyze it, because the
3519 // resolution chosen here may differ from the resolution chosen in
3520 // other parts of the compiler.
3521 if (SA->getValue().uge(BitWidth))
3522 break;
3523
Owen Andersoneed707b2009-07-24 23:12:02 +00003524 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003525 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003526 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003527 }
3528 break;
3529
Nick Lewycky01eaf802008-07-07 06:15:49 +00003530 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003531 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003532 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003533 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003534
3535 // If the shift count is not less than the bitwidth, the result of
3536 // the shift is undefined. Don't try to analyze it, because the
3537 // resolution chosen here may differ from the resolution chosen in
3538 // other parts of the compiler.
3539 if (SA->getValue().uge(BitWidth))
3540 break;
3541
Owen Andersoneed707b2009-07-24 23:12:02 +00003542 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003543 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003544 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003545 }
3546 break;
3547
Dan Gohman4ee29af2009-04-21 02:26:00 +00003548 case Instruction::AShr:
3549 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3550 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003551 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003552 if (L->getOpcode() == Instruction::Shl &&
3553 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003554 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3555
3556 // If the shift count is not less than the bitwidth, the result of
3557 // the shift is undefined. Don't try to analyze it, because the
3558 // resolution chosen here may differ from the resolution chosen in
3559 // other parts of the compiler.
3560 if (CI->getValue().uge(BitWidth))
3561 break;
3562
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003563 uint64_t Amt = BitWidth - CI->getZExtValue();
3564 if (Amt == BitWidth)
3565 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003566 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003567 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003568 IntegerType::get(getContext(),
3569 Amt)),
3570 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003571 }
3572 break;
3573
Dan Gohman6c459a22008-06-22 19:56:46 +00003574 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003575 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003576
3577 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003578 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003579
3580 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003581 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003582
3583 case Instruction::BitCast:
3584 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003585 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003586 return getSCEV(U->getOperand(0));
3587 break;
3588
Dan Gohman4f8eea82010-02-01 18:27:38 +00003589 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3590 // lead to pointer expressions which cannot safely be expanded to GEPs,
3591 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3592 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003593
Dan Gohman26466c02009-05-08 20:26:55 +00003594 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003595 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003596
Dan Gohman6c459a22008-06-22 19:56:46 +00003597 case Instruction::PHI:
3598 return createNodeForPHI(cast<PHINode>(U));
3599
3600 case Instruction::Select:
3601 // This could be a smax or umax that was lowered earlier.
3602 // Try to recover it.
3603 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3604 Value *LHS = ICI->getOperand(0);
3605 Value *RHS = ICI->getOperand(1);
3606 switch (ICI->getPredicate()) {
3607 case ICmpInst::ICMP_SLT:
3608 case ICmpInst::ICMP_SLE:
3609 std::swap(LHS, RHS);
3610 // fall through
3611 case ICmpInst::ICMP_SGT:
3612 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003613 // a >s b ? a+x : b+x -> smax(a, b)+x
3614 // a >s b ? b+x : a+x -> smin(a, b)+x
3615 if (LHS->getType() == U->getType()) {
3616 const SCEV *LS = getSCEV(LHS);
3617 const SCEV *RS = getSCEV(RHS);
3618 const SCEV *LA = getSCEV(U->getOperand(1));
3619 const SCEV *RA = getSCEV(U->getOperand(2));
3620 const SCEV *LDiff = getMinusSCEV(LA, LS);
3621 const SCEV *RDiff = getMinusSCEV(RA, RS);
3622 if (LDiff == RDiff)
3623 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3624 LDiff = getMinusSCEV(LA, RS);
3625 RDiff = getMinusSCEV(RA, LS);
3626 if (LDiff == RDiff)
3627 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3628 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003629 break;
3630 case ICmpInst::ICMP_ULT:
3631 case ICmpInst::ICMP_ULE:
3632 std::swap(LHS, RHS);
3633 // fall through
3634 case ICmpInst::ICMP_UGT:
3635 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003636 // a >u b ? a+x : b+x -> umax(a, b)+x
3637 // a >u b ? b+x : a+x -> umin(a, b)+x
3638 if (LHS->getType() == U->getType()) {
3639 const SCEV *LS = getSCEV(LHS);
3640 const SCEV *RS = getSCEV(RHS);
3641 const SCEV *LA = getSCEV(U->getOperand(1));
3642 const SCEV *RA = getSCEV(U->getOperand(2));
3643 const SCEV *LDiff = getMinusSCEV(LA, LS);
3644 const SCEV *RDiff = getMinusSCEV(RA, RS);
3645 if (LDiff == RDiff)
3646 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3647 LDiff = getMinusSCEV(LA, RS);
3648 RDiff = getMinusSCEV(RA, LS);
3649 if (LDiff == RDiff)
3650 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3651 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003652 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003653 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003654 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3655 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003656 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003657 cast<ConstantInt>(RHS)->isZero()) {
3658 const SCEV *One = getConstant(LHS->getType(), 1);
3659 const SCEV *LS = getSCEV(LHS);
3660 const SCEV *LA = getSCEV(U->getOperand(1));
3661 const SCEV *RA = getSCEV(U->getOperand(2));
3662 const SCEV *LDiff = getMinusSCEV(LA, LS);
3663 const SCEV *RDiff = getMinusSCEV(RA, One);
3664 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003665 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003666 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003667 break;
3668 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003669 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3670 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003671 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003672 cast<ConstantInt>(RHS)->isZero()) {
3673 const SCEV *One = getConstant(LHS->getType(), 1);
3674 const SCEV *LS = getSCEV(LHS);
3675 const SCEV *LA = getSCEV(U->getOperand(1));
3676 const SCEV *RA = getSCEV(U->getOperand(2));
3677 const SCEV *LDiff = getMinusSCEV(LA, One);
3678 const SCEV *RDiff = getMinusSCEV(RA, LS);
3679 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003680 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003681 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003682 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003683 default:
3684 break;
3685 }
3686 }
3687
3688 default: // We cannot analyze this expression.
3689 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003690 }
3691
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003692 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003693}
3694
3695
3696
3697//===----------------------------------------------------------------------===//
3698// Iteration Count Computation Code
3699//
3700
Dan Gohman46bdfb02009-02-24 18:55:53 +00003701/// getBackedgeTakenCount - If the specified loop has a predictable
3702/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3703/// object. The backedge-taken count is the number of times the loop header
3704/// will be branched to from within the loop. This is one less than the
3705/// trip count of the loop, since it doesn't count the first iteration,
3706/// when the header is branched to from outside the loop.
3707///
3708/// Note that it is not valid to call this method on a loop without a
3709/// loop-invariant backedge-taken count (see
3710/// hasLoopInvariantBackedgeTakenCount).
3711///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003712const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003713 return getBackedgeTakenInfo(L).Exact;
3714}
3715
3716/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3717/// return the least SCEV value that is known never to be less than the
3718/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003719const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003720 return getBackedgeTakenInfo(L).Max;
3721}
3722
Dan Gohman59ae6b92009-07-08 19:23:34 +00003723/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3724/// onto the given Worklist.
3725static void
3726PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3727 BasicBlock *Header = L->getHeader();
3728
3729 // Push all Loop-header PHIs onto the Worklist stack.
3730 for (BasicBlock::iterator I = Header->begin();
3731 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3732 Worklist.push_back(PN);
3733}
3734
Dan Gohmana1af7572009-04-30 20:47:05 +00003735const ScalarEvolution::BackedgeTakenInfo &
3736ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003737 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003738 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003739 // update the value. The temporary CouldNotCompute value tells SCEV
3740 // code elsewhere that it shouldn't attempt to request a new
3741 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003742 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003743 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
Chris Lattnerf1859892011-01-09 02:16:18 +00003744 if (!Pair.second)
3745 return Pair.first->second;
Dan Gohman01ecca22009-04-27 20:16:15 +00003746
Chris Lattnerf1859892011-01-09 02:16:18 +00003747 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3748 if (BECount.Exact != getCouldNotCompute()) {
3749 assert(isLoopInvariant(BECount.Exact, L) &&
3750 isLoopInvariant(BECount.Max, L) &&
3751 "Computed backedge-taken count isn't loop invariant for loop!");
3752 ++NumTripCountsComputed;
3753
3754 // Update the value in the map.
3755 Pair.first->second = BECount;
3756 } else {
3757 if (BECount.Max != getCouldNotCompute())
Dan Gohman01ecca22009-04-27 20:16:15 +00003758 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003759 Pair.first->second = BECount;
Chris Lattnerf1859892011-01-09 02:16:18 +00003760 if (isa<PHINode>(L->getHeader()->begin()))
3761 // Only count loops that have phi nodes as not being computable.
3762 ++NumTripCountsNotComputed;
3763 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003764
Chris Lattnerf1859892011-01-09 02:16:18 +00003765 // Now that we know more about the trip count for this loop, forget any
3766 // existing SCEV values for PHI nodes in this loop since they are only
3767 // conservative estimates made without the benefit of trip count
3768 // information. This is similar to the code in forgetLoop, except that
3769 // it handles SCEVUnknown PHI nodes specially.
3770 if (BECount.hasAnyInfo()) {
3771 SmallVector<Instruction *, 16> Worklist;
3772 PushLoopPHIs(L, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003773
Chris Lattnerf1859892011-01-09 02:16:18 +00003774 SmallPtrSet<Instruction *, 8> Visited;
3775 while (!Worklist.empty()) {
3776 Instruction *I = Worklist.pop_back_val();
3777 if (!Visited.insert(I)) continue;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003778
Chris Lattnerf1859892011-01-09 02:16:18 +00003779 ValueExprMapType::iterator It =
3780 ValueExprMap.find(static_cast<Value *>(I));
3781 if (It != ValueExprMap.end()) {
3782 const SCEV *Old = It->second;
Dan Gohman6678e7b2010-11-17 02:44:44 +00003783
Chris Lattnerf1859892011-01-09 02:16:18 +00003784 // SCEVUnknown for a PHI either means that it has an unrecognized
3785 // structure, or it's a PHI that's in the progress of being computed
3786 // by createNodeForPHI. In the former case, additional loop trip
3787 // count information isn't going to change anything. In the later
3788 // case, createNodeForPHI will perform the necessary updates on its
3789 // own when it gets to that point.
3790 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3791 forgetMemoizedResults(Old);
3792 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003793 }
Chris Lattnerf1859892011-01-09 02:16:18 +00003794 if (PHINode *PN = dyn_cast<PHINode>(I))
3795 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003796 }
Chris Lattnerf1859892011-01-09 02:16:18 +00003797
3798 PushDefUseChildren(I, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003799 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003800 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003801 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003802}
3803
Dan Gohman4c7279a2009-10-31 15:04:55 +00003804/// forgetLoop - This method should be called by the client when it has
3805/// changed a loop in a way that may effect ScalarEvolution's ability to
3806/// compute a trip count, or if the loop is deleted.
3807void ScalarEvolution::forgetLoop(const Loop *L) {
3808 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003809 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003810
Dan Gohman4c7279a2009-10-31 15:04:55 +00003811 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003812 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003813 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003814
Dan Gohman59ae6b92009-07-08 19:23:34 +00003815 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003816 while (!Worklist.empty()) {
3817 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003818 if (!Visited.insert(I)) continue;
3819
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003820 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3821 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003822 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003823 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003824 if (PHINode *PN = dyn_cast<PHINode>(I))
3825 ConstantEvolutionLoopExitValue.erase(PN);
3826 }
3827
3828 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003829 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00003830
3831 // Forget all contained loops too, to avoid dangling entries in the
3832 // ValuesAtScopes map.
3833 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3834 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00003835}
3836
Eric Christophere6cbfa62010-07-29 01:25:38 +00003837/// forgetValue - This method should be called by the client when it has
3838/// changed a value in a way that may effect its value, or which may
3839/// disconnect it from a def-use chain linking it to a loop.
3840void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003841 Instruction *I = dyn_cast<Instruction>(V);
3842 if (!I) return;
3843
3844 // Drop information about expressions based on loop-header PHIs.
3845 SmallVector<Instruction *, 16> Worklist;
3846 Worklist.push_back(I);
3847
3848 SmallPtrSet<Instruction *, 8> Visited;
3849 while (!Worklist.empty()) {
3850 I = Worklist.pop_back_val();
3851 if (!Visited.insert(I)) continue;
3852
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003853 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3854 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003855 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003856 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003857 if (PHINode *PN = dyn_cast<PHINode>(I))
3858 ConstantEvolutionLoopExitValue.erase(PN);
3859 }
3860
3861 PushDefUseChildren(I, Worklist);
3862 }
3863}
3864
Dan Gohman46bdfb02009-02-24 18:55:53 +00003865/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3866/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003867ScalarEvolution::BackedgeTakenInfo
3868ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003869 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003870 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003871
Dan Gohmana334aa72009-06-22 00:31:57 +00003872 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003873 const SCEV *BECount = getCouldNotCompute();
3874 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003875 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003876 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3877 BackedgeTakenInfo NewBTI =
3878 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003879
Dan Gohman1c343752009-06-27 21:21:31 +00003880 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003881 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003882 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003883 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003884 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003885 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003886 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003887 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003888 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003889 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003890 }
Dan Gohman1c343752009-06-27 21:21:31 +00003891 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003892 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003893 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003894 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003895 }
3896
3897 return BackedgeTakenInfo(BECount, MaxBECount);
3898}
3899
3900/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3901/// of the specified loop will execute if it exits via the specified block.
3902ScalarEvolution::BackedgeTakenInfo
3903ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3904 BasicBlock *ExitingBlock) {
3905
3906 // Okay, we've chosen an exiting block. See what condition causes us to
3907 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003908 //
3909 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003910 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003911 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003912 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003913
Chris Lattner8b0e3602007-01-07 02:24:26 +00003914 // At this point, we know we have a conditional branch that determines whether
3915 // the loop is exited. However, we don't know if the branch is executed each
3916 // time through the loop. If not, then the execution count of the branch will
3917 // not be equal to the trip count of the loop.
3918 //
3919 // Currently we check for this by checking to see if the Exit branch goes to
3920 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003921 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003922 // loop header. This is common for un-rotated loops.
3923 //
3924 // If both of those tests fail, walk up the unique predecessor chain to the
3925 // header, stopping if there is an edge that doesn't exit the loop. If the
3926 // header is reached, the execution count of the branch will be equal to the
3927 // trip count of the loop.
3928 //
3929 // More extensive analysis could be done to handle more cases here.
3930 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003931 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003932 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003933 ExitBr->getParent() != L->getHeader()) {
3934 // The simple checks failed, try climbing the unique predecessor chain
3935 // up to the header.
3936 bool Ok = false;
3937 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3938 BasicBlock *Pred = BB->getUniquePredecessor();
3939 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003940 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003941 TerminatorInst *PredTerm = Pred->getTerminator();
3942 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3943 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3944 if (PredSucc == BB)
3945 continue;
3946 // If the predecessor has a successor that isn't BB and isn't
3947 // outside the loop, assume the worst.
3948 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003949 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003950 }
3951 if (Pred == L->getHeader()) {
3952 Ok = true;
3953 break;
3954 }
3955 BB = Pred;
3956 }
3957 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003958 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003959 }
3960
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003961 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003962 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3963 ExitBr->getSuccessor(0),
3964 ExitBr->getSuccessor(1));
3965}
3966
3967/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3968/// backedge of the specified loop will execute if its exit condition
3969/// were a conditional branch of ExitCond, TBB, and FBB.
3970ScalarEvolution::BackedgeTakenInfo
3971ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3972 Value *ExitCond,
3973 BasicBlock *TBB,
3974 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003975 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003976 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3977 if (BO->getOpcode() == Instruction::And) {
3978 // Recurse on the operands of the and.
3979 BackedgeTakenInfo BTI0 =
3980 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3981 BackedgeTakenInfo BTI1 =
3982 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003983 const SCEV *BECount = getCouldNotCompute();
3984 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003985 if (L->contains(TBB)) {
3986 // Both conditions must be true for the loop to continue executing.
3987 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003988 if (BTI0.Exact == getCouldNotCompute() ||
3989 BTI1.Exact == getCouldNotCompute())
3990 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003991 else
3992 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003993 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003994 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003995 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003996 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003997 else
3998 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003999 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004000 // Both conditions must be true at the same time for the loop to exit.
4001 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004002 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00004003 if (BTI0.Max == BTI1.Max)
4004 MaxBECount = BTI0.Max;
4005 if (BTI0.Exact == BTI1.Exact)
4006 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004007 }
4008
4009 return BackedgeTakenInfo(BECount, MaxBECount);
4010 }
4011 if (BO->getOpcode() == Instruction::Or) {
4012 // Recurse on the operands of the or.
4013 BackedgeTakenInfo BTI0 =
4014 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
4015 BackedgeTakenInfo BTI1 =
4016 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004017 const SCEV *BECount = getCouldNotCompute();
4018 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004019 if (L->contains(FBB)) {
4020 // Both conditions must be false for the loop to continue executing.
4021 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00004022 if (BTI0.Exact == getCouldNotCompute() ||
4023 BTI1.Exact == getCouldNotCompute())
4024 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004025 else
4026 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00004027 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004028 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00004029 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004030 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004031 else
4032 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004033 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004034 // Both conditions must be false at the same time for the loop to exit.
4035 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004036 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00004037 if (BTI0.Max == BTI1.Max)
4038 MaxBECount = BTI0.Max;
4039 if (BTI0.Exact == BTI1.Exact)
4040 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004041 }
4042
4043 return BackedgeTakenInfo(BECount, MaxBECount);
4044 }
4045 }
4046
4047 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004048 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00004049 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4050 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004051
Dan Gohman00cb5b72010-02-19 18:12:07 +00004052 // Check for a constant condition. These are normally stripped out by
4053 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4054 // preserve the CFG and is temporarily leaving constant conditions
4055 // in place.
4056 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4057 if (L->contains(FBB) == !CI->getZExtValue())
4058 // The backedge is always taken.
4059 return getCouldNotCompute();
4060 else
4061 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00004062 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00004063 }
4064
Eli Friedman361e54d2009-05-09 12:32:42 +00004065 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00004066 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4067}
4068
Chris Lattner992efb02011-01-09 22:26:35 +00004069static const SCEVAddRecExpr *
4070isSimpleUnwrappingAddRec(const SCEV *S, const Loop *L) {
4071 const SCEVAddRecExpr *SA = dyn_cast<SCEVAddRecExpr>(S);
Andrew Trick635f7182011-03-09 17:23:39 +00004072
Chris Lattner992efb02011-01-09 22:26:35 +00004073 // The SCEV must be an addrec of this loop.
4074 if (!SA || SA->getLoop() != L || !SA->isAffine())
4075 return 0;
Andrew Trick635f7182011-03-09 17:23:39 +00004076
Chris Lattner992efb02011-01-09 22:26:35 +00004077 // The SCEV must be known to not wrap in some way to be interesting.
Andrew Trick3228cc22011-03-14 16:50:06 +00004078 if (!SA->getNoWrapFlags(SCEV::FlagNW))
Chris Lattner992efb02011-01-09 22:26:35 +00004079 return 0;
4080
4081 // The stride must be a constant so that we know if it is striding up or down.
4082 if (!isa<SCEVConstant>(SA->getOperand(1)))
4083 return 0;
4084 return SA;
4085}
4086
4087/// getMinusSCEVForExitTest - When considering an exit test for a loop with a
4088/// "x != y" exit test, we turn this into a computation that evaluates x-y != 0,
4089/// and this function returns the expression to use for x-y. We know and take
4090/// advantage of the fact that this subtraction is only being used in a
4091/// comparison by zero context.
4092///
Andrew Trick3228cc22011-03-14 16:50:06 +00004093/// FIXME: this can be completely removed once AddRec FlagNWs are propagated.
Chris Lattner992efb02011-01-09 22:26:35 +00004094static const SCEV *getMinusSCEVForExitTest(const SCEV *LHS, const SCEV *RHS,
4095 const Loop *L, ScalarEvolution &SE) {
4096 // If either LHS or RHS is an AddRec SCEV (of this loop) that is known to not
Andrew Trick3228cc22011-03-14 16:50:06 +00004097 // self-wrap, then we know that the value will either become the other one
4098 // (and thus the loop terminates), that the loop will terminate through some
4099 // other exit condition first, or that the loop has undefined behavior. This
4100 // information is useful when the addrec has a stride that is != 1 or -1,
4101 // because it means we can't "miss" the exit value.
Chris Lattner992efb02011-01-09 22:26:35 +00004102 //
4103 // In any of these three cases, it is safe to turn the exit condition into a
4104 // "counting down" AddRec (to zero) by subtracting the two inputs as normal,
4105 // but since we know that the "end cannot be missed" we can force the
4106 // resulting AddRec to be a NUW addrec. Since it is counting down, this means
4107 // that the AddRec *cannot* pass zero.
4108
4109 // See if LHS and RHS are addrec's we can handle.
4110 const SCEVAddRecExpr *LHSA = isSimpleUnwrappingAddRec(LHS, L);
4111 const SCEVAddRecExpr *RHSA = isSimpleUnwrappingAddRec(RHS, L);
Andrew Trick635f7182011-03-09 17:23:39 +00004112
Chris Lattner992efb02011-01-09 22:26:35 +00004113 // If neither addrec is interesting, just return a minus.
4114 if (RHSA == 0 && LHSA == 0)
4115 return SE.getMinusSCEV(LHS, RHS);
Andrew Trick635f7182011-03-09 17:23:39 +00004116
Chris Lattner992efb02011-01-09 22:26:35 +00004117 // If only one of LHS and RHS are an AddRec of this loop, make sure it is LHS.
4118 if (RHSA && LHSA == 0) {
4119 // Safe because a-b === b-a for comparisons against zero.
4120 std::swap(LHS, RHS);
4121 std::swap(LHSA, RHSA);
4122 }
Andrew Trick635f7182011-03-09 17:23:39 +00004123
Chris Lattner992efb02011-01-09 22:26:35 +00004124 // Handle the case when only one is advancing in a non-overflowing way.
4125 if (RHSA == 0) {
4126 // If RHS is loop varying, then we can't predict when LHS will cross it.
4127 if (!SE.isLoopInvariant(RHS, L))
4128 return SE.getMinusSCEV(LHS, RHS);
Andrew Trick635f7182011-03-09 17:23:39 +00004129
Chris Lattner992efb02011-01-09 22:26:35 +00004130 // If LHS has a positive stride, then we compute RHS-LHS, because the loop
4131 // is counting up until it crosses RHS (which must be larger than LHS). If
4132 // it is negative, we compute LHS-RHS because we're counting down to RHS.
4133 const ConstantInt *Stride =
4134 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4135 if (Stride->getValue().isNegative())
4136 std::swap(LHS, RHS);
4137
Andrew Trick3228cc22011-03-14 16:50:06 +00004138 return SE.getMinusSCEV(RHS, LHS, SCEV::FlagNUW);
Chris Lattner992efb02011-01-09 22:26:35 +00004139 }
Andrew Trick635f7182011-03-09 17:23:39 +00004140
Chris Lattner992efb02011-01-09 22:26:35 +00004141 // If both LHS and RHS are interesting, we have something like:
4142 // a+i*4 != b+i*8.
4143 const ConstantInt *LHSStride =
4144 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4145 const ConstantInt *RHSStride =
4146 cast<SCEVConstant>(RHSA->getOperand(1))->getValue();
Andrew Trick635f7182011-03-09 17:23:39 +00004147
Chris Lattner992efb02011-01-09 22:26:35 +00004148 // If the strides are equal, then this is just a (complex) loop invariant
Chris Lattner6038a632011-01-11 17:11:59 +00004149 // comparison of a and b.
Chris Lattner992efb02011-01-09 22:26:35 +00004150 if (LHSStride == RHSStride)
4151 return SE.getMinusSCEV(LHSA->getStart(), RHSA->getStart());
Andrew Trick635f7182011-03-09 17:23:39 +00004152
Chris Lattner992efb02011-01-09 22:26:35 +00004153 // If the signs of the strides differ, then the negative stride is counting
4154 // down to the positive stride.
4155 if (LHSStride->getValue().isNegative() != RHSStride->getValue().isNegative()){
4156 if (RHSStride->getValue().isNegative())
4157 std::swap(LHS, RHS);
4158 } else {
4159 // If LHS's stride is smaller than RHS's stride, then "b" must be less than
4160 // "a" and "b" is RHS is counting up (catching up) to LHS. This is true
4161 // whether the strides are positive or negative.
4162 if (RHSStride->getValue().slt(LHSStride->getValue()))
4163 std::swap(LHS, RHS);
4164 }
Andrew Trick635f7182011-03-09 17:23:39 +00004165
Andrew Trick3228cc22011-03-14 16:50:06 +00004166 return SE.getMinusSCEV(LHS, RHS, SCEV::FlagNUW);
Chris Lattner992efb02011-01-09 22:26:35 +00004167}
4168
Dan Gohmana334aa72009-06-22 00:31:57 +00004169/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
4170/// backedge of the specified loop will execute if its exit condition
4171/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4172ScalarEvolution::BackedgeTakenInfo
4173ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
4174 ICmpInst *ExitCond,
4175 BasicBlock *TBB,
4176 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004177
Reid Spencere4d87aa2006-12-23 06:05:41 +00004178 // If the condition was exit on true, convert the condition to exit on false
4179 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00004180 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004181 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004182 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004184
4185 // Handle common loops like: for (X = "string"; *X; ++X)
4186 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4187 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004188 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004189 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004190 if (ItCnt.hasAnyInfo())
4191 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00004192 }
4193
Dan Gohman0bba49c2009-07-07 17:06:11 +00004194 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4195 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00004196
4197 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00004198 LHS = getSCEVAtScope(LHS, L);
4199 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004200
Dan Gohman64a845e2009-06-24 04:48:43 +00004201 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004202 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00004203 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004204 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004205 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004206 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004207 }
4208
Dan Gohman03557dc2010-05-03 16:35:17 +00004209 // Simplify the operands before analyzing them.
4210 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4211
Chris Lattner53e677a2004-04-02 20:23:17 +00004212 // If we have a comparison of a chrec against a constant, try to use value
4213 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004214 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4215 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004216 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004217 // Form the constant range.
4218 ConstantRange CompRange(
4219 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004220
Dan Gohman0bba49c2009-07-07 17:06:11 +00004221 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004222 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004223 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004224
Chris Lattner53e677a2004-04-02 20:23:17 +00004225 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004226 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004227 // Convert to: while (X-Y != 0)
Andrew Trick3228cc22011-03-14 16:50:06 +00004228 // FIXME: Once AddRec FlagNW are propagated, should be:
4229 // BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Chris Lattner992efb02011-01-09 22:26:35 +00004230 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEVForExitTest(LHS, RHS, L,
4231 *this), L);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004232 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004233 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004234 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004235 case ICmpInst::ICMP_EQ: { // while (X == Y)
4236 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004237 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4238 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004239 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004240 }
4241 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004242 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4243 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004244 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004245 }
4246 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004247 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4248 getNotSCEV(RHS), L, true);
4249 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004250 break;
4251 }
4252 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004253 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4254 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004255 break;
4256 }
4257 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004258 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4259 getNotSCEV(RHS), L, false);
4260 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004261 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004263 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004264#if 0
David Greene25e0e872009-12-23 22:18:14 +00004265 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004266 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004267 dbgs() << "[unsigned] ";
4268 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004269 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004270 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004271#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004272 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004273 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004274 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004275 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004276}
4277
Chris Lattner673e02b2004-10-12 01:49:27 +00004278static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004279EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4280 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004281 const SCEV *InVal = SE.getConstant(C);
4282 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004283 assert(isa<SCEVConstant>(Val) &&
4284 "Evaluation of SCEV at constant didn't fold correctly?");
4285 return cast<SCEVConstant>(Val)->getValue();
4286}
4287
4288/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4289/// and a GEP expression (missing the pointer index) indexing into it, return
4290/// the addressed element of the initializer or null if the index expression is
4291/// invalid.
4292static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004293GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004294 const std::vector<ConstantInt*> &Indices) {
4295 Constant *Init = GV->getInitializer();
4296 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004297 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004298 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4299 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4300 Init = cast<Constant>(CS->getOperand(Idx));
4301 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4302 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4303 Init = cast<Constant>(CA->getOperand(Idx));
4304 } else if (isa<ConstantAggregateZero>(Init)) {
4305 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4306 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004307 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004308 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4309 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004310 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004311 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004312 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004313 }
4314 return 0;
4315 } else {
4316 return 0; // Unknown initializer type
4317 }
4318 }
4319 return Init;
4320}
4321
Dan Gohman46bdfb02009-02-24 18:55:53 +00004322/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4323/// 'icmp op load X, cst', try to see if we can compute the backedge
4324/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004325ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004326ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4327 LoadInst *LI,
4328 Constant *RHS,
4329 const Loop *L,
4330 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004331 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004332
4333 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004334 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004335 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004336 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004337
4338 // Make sure that it is really a constant global we are gepping, with an
4339 // initializer, and make sure the first IDX is really 0.
4340 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004341 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004342 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4343 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004344 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004345
4346 // Okay, we allow one non-constant index into the GEP instruction.
4347 Value *VarIdx = 0;
4348 std::vector<ConstantInt*> Indexes;
4349 unsigned VarIdxNum = 0;
4350 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4351 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4352 Indexes.push_back(CI);
4353 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004354 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004355 VarIdx = GEP->getOperand(i);
4356 VarIdxNum = i-2;
4357 Indexes.push_back(0);
4358 }
4359
4360 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4361 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004362 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004363 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004364
4365 // We can only recognize very limited forms of loop index expressions, in
4366 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004367 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004368 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004369 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4370 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004371 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004372
4373 unsigned MaxSteps = MaxBruteForceIterations;
4374 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004375 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004376 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004377 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004378
4379 // Form the GEP offset.
4380 Indexes[VarIdxNum] = Val;
4381
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004382 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004383 if (Result == 0) break; // Cannot compute!
4384
4385 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004386 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004387 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004388 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004389#if 0
David Greene25e0e872009-12-23 22:18:14 +00004390 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004391 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4392 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004393#endif
4394 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004395 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004396 }
4397 }
Dan Gohman1c343752009-06-27 21:21:31 +00004398 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004399}
4400
4401
Chris Lattner3221ad02004-04-17 22:58:41 +00004402/// CanConstantFold - Return true if we can constant fold an instruction of the
4403/// specified type, assuming that all operands were constants.
4404static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004405 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004406 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4407 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004408
Chris Lattner3221ad02004-04-17 22:58:41 +00004409 if (const CallInst *CI = dyn_cast<CallInst>(I))
4410 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004411 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004412 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004413}
4414
Chris Lattner3221ad02004-04-17 22:58:41 +00004415/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4416/// in the loop that V is derived from. We allow arbitrary operations along the
4417/// way, but the operands of an operation must either be constants or a value
4418/// derived from a constant PHI. If this expression does not fit with these
4419/// constraints, return null.
4420static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4421 // If this is not an instruction, or if this is an instruction outside of the
4422 // loop, it can't be derived from a loop PHI.
4423 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004424 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004425
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004426 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004427 if (L->getHeader() == I->getParent())
4428 return PN;
4429 else
4430 // We don't currently keep track of the control flow needed to evaluate
4431 // PHIs, so we cannot handle PHIs inside of loops.
4432 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004433 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004434
4435 // If we won't be able to constant fold this expression even if the operands
4436 // are constants, return early.
4437 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004438
Chris Lattner3221ad02004-04-17 22:58:41 +00004439 // Otherwise, we can evaluate this instruction if all of its operands are
4440 // constant or derived from a PHI node themselves.
4441 PHINode *PHI = 0;
4442 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004443 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004444 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4445 if (P == 0) return 0; // Not evolving from PHI
4446 if (PHI == 0)
4447 PHI = P;
4448 else if (PHI != P)
4449 return 0; // Evolving from multiple different PHIs.
4450 }
4451
4452 // This is a expression evolving from a constant PHI!
4453 return PHI;
4454}
4455
4456/// EvaluateExpression - Given an expression that passes the
4457/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4458/// in the loop has the value PHIVal. If we can't fold this expression for some
4459/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004460static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4461 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004462 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004463 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004464 Instruction *I = cast<Instruction>(V);
4465
Dan Gohman9d4588f2010-06-22 13:15:46 +00004466 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004467
4468 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004469 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004470 if (Operands[i] == 0) return 0;
4471 }
4472
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004473 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004474 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004475 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004476 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004477 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004478}
4479
4480/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4481/// in the header of its containing loop, we know the loop executes a
4482/// constant number of times, and the PHI node is just a recurrence
4483/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004484Constant *
4485ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004486 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004487 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004488 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004489 ConstantEvolutionLoopExitValue.find(PN);
4490 if (I != ConstantEvolutionLoopExitValue.end())
4491 return I->second;
4492
Dan Gohmane0567812010-04-08 23:03:40 +00004493 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004494 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4495
4496 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4497
4498 // Since the loop is canonicalized, the PHI node must have two entries. One
4499 // entry must be a constant (coming in from outside of the loop), and the
4500 // second must be derived from the same PHI.
4501 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4502 Constant *StartCST =
4503 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4504 if (StartCST == 0)
4505 return RetVal = 0; // Must be a constant.
4506
4507 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004508 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4509 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004510 return RetVal = 0; // Not derived from same PHI.
4511
4512 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004513 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004514 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004515
Dan Gohman46bdfb02009-02-24 18:55:53 +00004516 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004517 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004518 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4519 if (IterationNum == NumIterations)
4520 return RetVal = PHIVal; // Got exit value!
4521
4522 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004523 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004524 if (NextPHI == PHIVal)
4525 return RetVal = NextPHI; // Stopped evolving!
4526 if (NextPHI == 0)
4527 return 0; // Couldn't evaluate!
4528 PHIVal = NextPHI;
4529 }
4530}
4531
Dan Gohman07ad19b2009-07-27 16:09:48 +00004532/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004533/// constant number of times (the condition evolves only from constants),
4534/// try to evaluate a few iterations of the loop until we get the exit
4535/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004536/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004537const SCEV *
4538ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4539 Value *Cond,
4540 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004541 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004542 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004543
Dan Gohmanb92654d2010-06-19 14:17:24 +00004544 // If the loop is canonicalized, the PHI will have exactly two entries.
4545 // That's the only form we support here.
4546 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4547
4548 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004549 // second must be derived from the same PHI.
4550 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4551 Constant *StartCST =
4552 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004553 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004554
4555 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004556 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4557 !isa<Constant>(BEValue))
4558 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004559
4560 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4561 // the loop symbolically to determine when the condition gets a value of
4562 // "ExitWhen".
4563 unsigned IterationNum = 0;
4564 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4565 for (Constant *PHIVal = StartCST;
4566 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004567 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004568 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004569
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004570 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004571 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004572
Reid Spencere8019bb2007-03-01 07:25:48 +00004573 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004574 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004575 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004576 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004577
Chris Lattner3221ad02004-04-17 22:58:41 +00004578 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004579 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004580 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004581 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004582 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004583 }
4584
4585 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004586 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004587}
4588
Dan Gohmane7125f42009-09-03 15:00:26 +00004589/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004590/// at the specified scope in the program. The L value specifies a loop
4591/// nest to evaluate the expression at, where null is the top-level or a
4592/// specified loop is immediately inside of the loop.
4593///
4594/// This method can be used to compute the exit value for a variable defined
4595/// in a loop by querying what the value will hold in the parent loop.
4596///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004597/// In the case that a relevant loop exit value cannot be computed, the
4598/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004599const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004600 // Check to see if we've folded this expression at this loop before.
4601 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4602 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4603 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4604 if (!Pair.second)
4605 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004606
Dan Gohman42214892009-08-31 21:15:23 +00004607 // Otherwise compute it.
4608 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004609 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004610 return C;
4611}
4612
4613const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004614 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004615
Nick Lewycky3e630762008-02-20 06:48:22 +00004616 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004617 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004618 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004619 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004620 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004621 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4622 if (PHINode *PN = dyn_cast<PHINode>(I))
4623 if (PN->getParent() == LI->getHeader()) {
4624 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004625 // to see if the loop that contains it has a known backedge-taken
4626 // count. If so, we may be able to force computation of the exit
4627 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004628 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004629 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004630 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004631 // Okay, we know how many times the containing loop executes. If
4632 // this is a constant evolving PHI node, get the final value at
4633 // the specified iteration number.
4634 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004635 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004636 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004637 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004638 }
4639 }
4640
Reid Spencer09906f32006-12-04 21:33:23 +00004641 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004642 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004643 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004644 // result. This is particularly useful for computing loop exit values.
4645 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004646 SmallVector<Constant *, 4> Operands;
4647 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004648 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4649 Value *Op = I->getOperand(i);
4650 if (Constant *C = dyn_cast<Constant>(Op)) {
4651 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004652 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004653 }
Dan Gohman11046452010-06-29 23:43:06 +00004654
4655 // If any of the operands is non-constant and if they are
4656 // non-integer and non-pointer, don't even try to analyze them
4657 // with scev techniques.
4658 if (!isSCEVable(Op->getType()))
4659 return V;
4660
4661 const SCEV *OrigV = getSCEV(Op);
4662 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4663 MadeImprovement |= OrigV != OpV;
4664
4665 Constant *C = 0;
4666 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4667 C = SC->getValue();
4668 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4669 C = dyn_cast<Constant>(SU->getValue());
4670 if (!C) return V;
4671 if (C->getType() != Op->getType())
4672 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4673 Op->getType(),
4674 false),
4675 C, Op->getType());
4676 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004677 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004678
Dan Gohman11046452010-06-29 23:43:06 +00004679 // Check to see if getSCEVAtScope actually made an improvement.
4680 if (MadeImprovement) {
4681 Constant *C = 0;
4682 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4683 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4684 Operands[0], Operands[1], TD);
4685 else
4686 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4687 &Operands[0], Operands.size(), TD);
4688 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004689 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004690 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004691 }
4692 }
4693
4694 // This is some other type of SCEVUnknown, just return it.
4695 return V;
4696 }
4697
Dan Gohman622ed672009-05-04 22:02:23 +00004698 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004699 // Avoid performing the look-up in the common case where the specified
4700 // expression has no loop-variant portions.
4701 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004702 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004703 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004704 // Okay, at least one of these operands is loop variant but might be
4705 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004706 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4707 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004708 NewOps.push_back(OpAtScope);
4709
4710 for (++i; i != e; ++i) {
4711 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004712 NewOps.push_back(OpAtScope);
4713 }
4714 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004715 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004716 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004717 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004718 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004719 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004720 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004721 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004722 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004723 }
4724 }
4725 // If we got here, all operands are loop invariant.
4726 return Comm;
4727 }
4728
Dan Gohman622ed672009-05-04 22:02:23 +00004729 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004730 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4731 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004732 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4733 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004734 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004735 }
4736
4737 // If this is a loop recurrence for a loop that does not contain L, then we
4738 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004739 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004740 // First, attempt to evaluate each operand.
4741 // Avoid performing the look-up in the common case where the specified
4742 // expression has no loop-variant portions.
4743 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4744 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4745 if (OpAtScope == AddRec->getOperand(i))
4746 continue;
4747
4748 // Okay, at least one of these operands is loop variant but might be
4749 // foldable. Build a new instance of the folded commutative expression.
4750 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4751 AddRec->op_begin()+i);
4752 NewOps.push_back(OpAtScope);
4753 for (++i; i != e; ++i)
4754 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4755
Andrew Trick3228cc22011-03-14 16:50:06 +00004756 AddRec = cast<SCEVAddRecExpr>(
4757 getAddRecExpr(NewOps, AddRec->getLoop(),
4758 // FIXME: AddRec->getNoWrapFlags(SCEV::FlagNW)
4759 SCEV::FlagAnyWrap));
Dan Gohman11046452010-06-29 23:43:06 +00004760 break;
4761 }
4762
4763 // If the scope is outside the addrec's loop, evaluate it by using the
4764 // loop exit value of the addrec.
4765 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004766 // To evaluate this recurrence, we need to know how many times the AddRec
4767 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004768 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004769 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004770
Eli Friedmanb42a6262008-08-04 23:49:06 +00004771 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004772 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004773 }
Dan Gohman11046452010-06-29 23:43:06 +00004774
Dan Gohmand594e6f2009-05-24 23:25:42 +00004775 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004776 }
4777
Dan Gohman622ed672009-05-04 22:02:23 +00004778 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004779 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004780 if (Op == Cast->getOperand())
4781 return Cast; // must be loop invariant
4782 return getZeroExtendExpr(Op, Cast->getType());
4783 }
4784
Dan Gohman622ed672009-05-04 22:02:23 +00004785 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004786 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004787 if (Op == Cast->getOperand())
4788 return Cast; // must be loop invariant
4789 return getSignExtendExpr(Op, Cast->getType());
4790 }
4791
Dan Gohman622ed672009-05-04 22:02:23 +00004792 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004793 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004794 if (Op == Cast->getOperand())
4795 return Cast; // must be loop invariant
4796 return getTruncateExpr(Op, Cast->getType());
4797 }
4798
Torok Edwinc23197a2009-07-14 16:55:14 +00004799 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004800 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004801}
4802
Dan Gohman66a7e852009-05-08 20:38:54 +00004803/// getSCEVAtScope - This is a convenience function which does
4804/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004805const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004806 return getSCEVAtScope(getSCEV(V), L);
4807}
4808
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004809/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4810/// following equation:
4811///
4812/// A * X = B (mod N)
4813///
4814/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4815/// A and B isn't important.
4816///
4817/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004818static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004819 ScalarEvolution &SE) {
4820 uint32_t BW = A.getBitWidth();
4821 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4822 assert(A != 0 && "A must be non-zero.");
4823
4824 // 1. D = gcd(A, N)
4825 //
4826 // The gcd of A and N may have only one prime factor: 2. The number of
4827 // trailing zeros in A is its multiplicity
4828 uint32_t Mult2 = A.countTrailingZeros();
4829 // D = 2^Mult2
4830
4831 // 2. Check if B is divisible by D.
4832 //
4833 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4834 // is not less than multiplicity of this prime factor for D.
4835 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004836 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004837
4838 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4839 // modulo (N / D).
4840 //
4841 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4842 // bit width during computations.
4843 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4844 APInt Mod(BW + 1, 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00004845 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004846 APInt I = AD.multiplicativeInverse(Mod);
4847
4848 // 4. Compute the minimum unsigned root of the equation:
4849 // I * (B / D) mod (N / D)
4850 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4851
4852 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4853 // bits.
4854 return SE.getConstant(Result.trunc(BW));
4855}
Chris Lattner53e677a2004-04-02 20:23:17 +00004856
4857/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4858/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4859/// might be the same) or two SCEVCouldNotCompute objects.
4860///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004861static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004862SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004863 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004864 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4865 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4866 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004867
Chris Lattner53e677a2004-04-02 20:23:17 +00004868 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004869 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004870 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004871 return std::make_pair(CNC, CNC);
4872 }
4873
Reid Spencere8019bb2007-03-01 07:25:48 +00004874 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004875 const APInt &L = LC->getValue()->getValue();
4876 const APInt &M = MC->getValue()->getValue();
4877 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004878 APInt Two(BitWidth, 2);
4879 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004880
Dan Gohman64a845e2009-06-24 04:48:43 +00004881 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004882 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004883 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004884 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4885 // The B coefficient is M-N/2
4886 APInt B(M);
4887 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004888
Reid Spencere8019bb2007-03-01 07:25:48 +00004889 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004890 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004891
Reid Spencere8019bb2007-03-01 07:25:48 +00004892 // Compute the B^2-4ac term.
4893 APInt SqrtTerm(B);
4894 SqrtTerm *= B;
4895 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004896
Reid Spencere8019bb2007-03-01 07:25:48 +00004897 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4898 // integer value or else APInt::sqrt() will assert.
4899 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004900
Dan Gohman64a845e2009-06-24 04:48:43 +00004901 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004902 // The divisions must be performed as signed divisions.
4903 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004904 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004905 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004906 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004907 return std::make_pair(CNC, CNC);
4908 }
4909
Owen Andersone922c022009-07-22 00:24:57 +00004910 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004911
4912 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004913 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004914 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004915 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004916
Dan Gohman64a845e2009-06-24 04:48:43 +00004917 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004918 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004919 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004920}
4921
4922/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004923/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick3228cc22011-03-14 16:50:06 +00004924///
4925/// This is only used for loops with a "x != y" exit test. The exit condition is
4926/// now expressed as a single expression, V = x-y. So the exit test is
4927/// effectively V != 0. We know and take advantage of the fact that this
4928/// expression only being used in a comparison by zero context.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004929ScalarEvolution::BackedgeTakenInfo
4930ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004931 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004932 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004933 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004934 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004935 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004936 }
4937
Dan Gohman35738ac2009-05-04 22:30:44 +00004938 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004939 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004940 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004941
Chris Lattner7975e3e2011-01-09 22:39:48 +00004942 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4943 // the quadratic equation to solve it.
4944 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4945 std::pair<const SCEV *,const SCEV *> Roots =
4946 SolveQuadraticEquation(AddRec, *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004947 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4948 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner7975e3e2011-01-09 22:39:48 +00004949 if (R1 && R2) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004950#if 0
David Greene25e0e872009-12-23 22:18:14 +00004951 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004952 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004953#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004954 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004955 if (ConstantInt *CB =
Chris Lattner53e1d452011-01-09 22:58:47 +00004956 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
4957 R1->getValue(),
4958 R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004959 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004960 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick635f7182011-03-09 17:23:39 +00004961
Chris Lattner53e677a2004-04-02 20:23:17 +00004962 // We can only use this value if the chrec ends up with an exact zero
4963 // value at this index. When solving for "X*X != 5", for example, we
4964 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004965 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004966 if (Val->isZero())
4967 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004968 }
4969 }
Chris Lattner7975e3e2011-01-09 22:39:48 +00004970 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004971 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004972
Chris Lattner7975e3e2011-01-09 22:39:48 +00004973 // Otherwise we can only handle this if it is affine.
4974 if (!AddRec->isAffine())
4975 return getCouldNotCompute();
4976
4977 // If this is an affine expression, the execution count of this branch is
4978 // the minimum unsigned root of the following equation:
4979 //
4980 // Start + Step*N = 0 (mod 2^BW)
4981 //
4982 // equivalent to:
4983 //
4984 // Step*N = -Start (mod 2^BW)
4985 //
4986 // where BW is the common bit width of Start and Step.
4987
4988 // Get the initial value for the loop.
4989 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
4990 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
4991
4992 // For now we handle only constant steps.
Andrew Trick3228cc22011-03-14 16:50:06 +00004993 //
4994 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
4995 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
4996 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
4997 // We have not yet seen any such cases.
Chris Lattner7975e3e2011-01-09 22:39:48 +00004998 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
4999 if (StepC == 0)
5000 return getCouldNotCompute();
5001
Andrew Trick3228cc22011-03-14 16:50:06 +00005002 // For positive steps (counting up until unsigned overflow):
5003 // N = -Start/Step (as unsigned)
5004 // For negative steps (counting down to zero):
5005 // N = Start/-Step
5006 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005007 bool CountDown = StepC->getValue()->getValue().isNegative();
5008 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick3228cc22011-03-14 16:50:06 +00005009
5010 // Handle unitary steps, which cannot wraparound.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005011 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5012 // N = Distance (as unsigned)
5013 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue())
5014 return Distance;
Andrew Trick635f7182011-03-09 17:23:39 +00005015
Andrew Trickdcfd4042011-03-14 17:28:02 +00005016 // If the recurrence is known not to wraparound, unsigned divide computes the
5017 // back edge count. We know that the value will either become zero (and thus
5018 // the loop terminates), that the loop will terminate through some other exit
5019 // condition first, or that the loop has undefined behavior. This means
5020 // we can't "miss" the exit value, even with nonunit stride.
5021 //
5022 // FIXME: Prove that loops always exhibits *acceptable* undefined
5023 // behavior. Loops must exhibit defined behavior until a wrapped value is
5024 // actually used. So the trip count computed by udiv could be smaller than the
5025 // number of well-defined iterations.
5026 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5027 // FIXME: We really want an "isexact" bit for udiv.
5028 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005029
5030 // Then, try to solve the above equation provided that Start is constant.
5031 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5032 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5033 -StartC->getValue()->getValue(),
5034 *this);
Dan Gohman1c343752009-06-27 21:21:31 +00005035 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005036}
5037
5038/// HowFarToNonZero - Return the number of times a backedge checking the
5039/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005040/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005041ScalarEvolution::BackedgeTakenInfo
5042ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005043 // Loops that look like: while (X == 0) are very strange indeed. We don't
5044 // handle them yet except for the trivial case. This could be expanded in the
5045 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005046
Chris Lattner53e677a2004-04-02 20:23:17 +00005047 // If the value is a constant, check to see if it is known to be non-zero
5048 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00005049 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00005050 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00005051 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00005052 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005053 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005054
Chris Lattner53e677a2004-04-02 20:23:17 +00005055 // We could implement others, but I really doubt anyone writes loops like
5056 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00005057 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005058}
5059
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005060/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5061/// (which may not be an immediate predecessor) which has exactly one
5062/// successor from which BB is reachable, or null if no such block is
5063/// found.
5064///
Dan Gohman005752b2010-04-15 16:19:08 +00005065std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005066ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00005067 // If the block has a unique predecessor, then there is no path from the
5068 // predecessor to the block that does not go through the direct edge
5069 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005070 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00005071 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005072
5073 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00005074 // If the header has a unique predecessor outside the loop, it must be
5075 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005076 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00005077 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005078
Dan Gohman005752b2010-04-15 16:19:08 +00005079 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005080}
5081
Dan Gohman763bad12009-06-20 00:35:32 +00005082/// HasSameValue - SCEV structural equivalence is usually sufficient for
5083/// testing whether two expressions are equal, however for the purposes of
5084/// looking for a condition guarding a loop, it can be useful to be a little
5085/// more general, since a front-end may have replicated the controlling
5086/// expression.
5087///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005088static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00005089 // Quick check to see if they are the same SCEV.
5090 if (A == B) return true;
5091
5092 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5093 // two different instructions with the same value. Check for this case.
5094 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5095 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5096 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5097 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00005098 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00005099 return true;
5100
5101 // Otherwise assume they may have a different value.
5102 return false;
5103}
5104
Dan Gohmane9796502010-04-24 01:28:42 +00005105/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5106/// predicate Pred. Return true iff any changes were made.
5107///
5108bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5109 const SCEV *&LHS, const SCEV *&RHS) {
5110 bool Changed = false;
5111
5112 // Canonicalize a constant to the right side.
5113 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5114 // Check for both operands constant.
5115 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5116 if (ConstantExpr::getICmp(Pred,
5117 LHSC->getValue(),
5118 RHSC->getValue())->isNullValue())
5119 goto trivially_false;
5120 else
5121 goto trivially_true;
5122 }
5123 // Otherwise swap the operands to put the constant on the right.
5124 std::swap(LHS, RHS);
5125 Pred = ICmpInst::getSwappedPredicate(Pred);
5126 Changed = true;
5127 }
5128
5129 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00005130 // addrec's loop, put the addrec on the left. Also make a dominance check,
5131 // as both operands could be addrecs loop-invariant in each other's loop.
5132 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5133 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00005134 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00005135 std::swap(LHS, RHS);
5136 Pred = ICmpInst::getSwappedPredicate(Pred);
5137 Changed = true;
5138 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00005139 }
Dan Gohmane9796502010-04-24 01:28:42 +00005140
5141 // If there's a constant operand, canonicalize comparisons with boundary
5142 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5143 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5144 const APInt &RA = RC->getValue()->getValue();
5145 switch (Pred) {
5146 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5147 case ICmpInst::ICMP_EQ:
5148 case ICmpInst::ICMP_NE:
5149 break;
5150 case ICmpInst::ICMP_UGE:
5151 if ((RA - 1).isMinValue()) {
5152 Pred = ICmpInst::ICMP_NE;
5153 RHS = getConstant(RA - 1);
5154 Changed = true;
5155 break;
5156 }
5157 if (RA.isMaxValue()) {
5158 Pred = ICmpInst::ICMP_EQ;
5159 Changed = true;
5160 break;
5161 }
5162 if (RA.isMinValue()) goto trivially_true;
5163
5164 Pred = ICmpInst::ICMP_UGT;
5165 RHS = getConstant(RA - 1);
5166 Changed = true;
5167 break;
5168 case ICmpInst::ICMP_ULE:
5169 if ((RA + 1).isMaxValue()) {
5170 Pred = ICmpInst::ICMP_NE;
5171 RHS = getConstant(RA + 1);
5172 Changed = true;
5173 break;
5174 }
5175 if (RA.isMinValue()) {
5176 Pred = ICmpInst::ICMP_EQ;
5177 Changed = true;
5178 break;
5179 }
5180 if (RA.isMaxValue()) goto trivially_true;
5181
5182 Pred = ICmpInst::ICMP_ULT;
5183 RHS = getConstant(RA + 1);
5184 Changed = true;
5185 break;
5186 case ICmpInst::ICMP_SGE:
5187 if ((RA - 1).isMinSignedValue()) {
5188 Pred = ICmpInst::ICMP_NE;
5189 RHS = getConstant(RA - 1);
5190 Changed = true;
5191 break;
5192 }
5193 if (RA.isMaxSignedValue()) {
5194 Pred = ICmpInst::ICMP_EQ;
5195 Changed = true;
5196 break;
5197 }
5198 if (RA.isMinSignedValue()) goto trivially_true;
5199
5200 Pred = ICmpInst::ICMP_SGT;
5201 RHS = getConstant(RA - 1);
5202 Changed = true;
5203 break;
5204 case ICmpInst::ICMP_SLE:
5205 if ((RA + 1).isMaxSignedValue()) {
5206 Pred = ICmpInst::ICMP_NE;
5207 RHS = getConstant(RA + 1);
5208 Changed = true;
5209 break;
5210 }
5211 if (RA.isMinSignedValue()) {
5212 Pred = ICmpInst::ICMP_EQ;
5213 Changed = true;
5214 break;
5215 }
5216 if (RA.isMaxSignedValue()) goto trivially_true;
5217
5218 Pred = ICmpInst::ICMP_SLT;
5219 RHS = getConstant(RA + 1);
5220 Changed = true;
5221 break;
5222 case ICmpInst::ICMP_UGT:
5223 if (RA.isMinValue()) {
5224 Pred = ICmpInst::ICMP_NE;
5225 Changed = true;
5226 break;
5227 }
5228 if ((RA + 1).isMaxValue()) {
5229 Pred = ICmpInst::ICMP_EQ;
5230 RHS = getConstant(RA + 1);
5231 Changed = true;
5232 break;
5233 }
5234 if (RA.isMaxValue()) goto trivially_false;
5235 break;
5236 case ICmpInst::ICMP_ULT:
5237 if (RA.isMaxValue()) {
5238 Pred = ICmpInst::ICMP_NE;
5239 Changed = true;
5240 break;
5241 }
5242 if ((RA - 1).isMinValue()) {
5243 Pred = ICmpInst::ICMP_EQ;
5244 RHS = getConstant(RA - 1);
5245 Changed = true;
5246 break;
5247 }
5248 if (RA.isMinValue()) goto trivially_false;
5249 break;
5250 case ICmpInst::ICMP_SGT:
5251 if (RA.isMinSignedValue()) {
5252 Pred = ICmpInst::ICMP_NE;
5253 Changed = true;
5254 break;
5255 }
5256 if ((RA + 1).isMaxSignedValue()) {
5257 Pred = ICmpInst::ICMP_EQ;
5258 RHS = getConstant(RA + 1);
5259 Changed = true;
5260 break;
5261 }
5262 if (RA.isMaxSignedValue()) goto trivially_false;
5263 break;
5264 case ICmpInst::ICMP_SLT:
5265 if (RA.isMaxSignedValue()) {
5266 Pred = ICmpInst::ICMP_NE;
5267 Changed = true;
5268 break;
5269 }
5270 if ((RA - 1).isMinSignedValue()) {
5271 Pred = ICmpInst::ICMP_EQ;
5272 RHS = getConstant(RA - 1);
5273 Changed = true;
5274 break;
5275 }
5276 if (RA.isMinSignedValue()) goto trivially_false;
5277 break;
5278 }
5279 }
5280
5281 // Check for obvious equality.
5282 if (HasSameValue(LHS, RHS)) {
5283 if (ICmpInst::isTrueWhenEqual(Pred))
5284 goto trivially_true;
5285 if (ICmpInst::isFalseWhenEqual(Pred))
5286 goto trivially_false;
5287 }
5288
Dan Gohman03557dc2010-05-03 16:35:17 +00005289 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5290 // adding or subtracting 1 from one of the operands.
5291 switch (Pred) {
5292 case ICmpInst::ICMP_SLE:
5293 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5294 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005295 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005296 Pred = ICmpInst::ICMP_SLT;
5297 Changed = true;
5298 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005299 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005300 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005301 Pred = ICmpInst::ICMP_SLT;
5302 Changed = true;
5303 }
5304 break;
5305 case ICmpInst::ICMP_SGE:
5306 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005307 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005308 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005309 Pred = ICmpInst::ICMP_SGT;
5310 Changed = true;
5311 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5312 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005313 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005314 Pred = ICmpInst::ICMP_SGT;
5315 Changed = true;
5316 }
5317 break;
5318 case ICmpInst::ICMP_ULE:
5319 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005320 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005321 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005322 Pred = ICmpInst::ICMP_ULT;
5323 Changed = true;
5324 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005325 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005326 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005327 Pred = ICmpInst::ICMP_ULT;
5328 Changed = true;
5329 }
5330 break;
5331 case ICmpInst::ICMP_UGE:
5332 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005333 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005334 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005335 Pred = ICmpInst::ICMP_UGT;
5336 Changed = true;
5337 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005338 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005339 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005340 Pred = ICmpInst::ICMP_UGT;
5341 Changed = true;
5342 }
5343 break;
5344 default:
5345 break;
5346 }
5347
Dan Gohmane9796502010-04-24 01:28:42 +00005348 // TODO: More simplifications are possible here.
5349
5350 return Changed;
5351
5352trivially_true:
5353 // Return 0 == 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005354 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005355 Pred = ICmpInst::ICMP_EQ;
5356 return true;
5357
5358trivially_false:
5359 // Return 0 != 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005360 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005361 Pred = ICmpInst::ICMP_NE;
5362 return true;
5363}
5364
Dan Gohman85b05a22009-07-13 21:35:55 +00005365bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5366 return getSignedRange(S).getSignedMax().isNegative();
5367}
5368
5369bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5370 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5371}
5372
5373bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5374 return !getSignedRange(S).getSignedMin().isNegative();
5375}
5376
5377bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5378 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5379}
5380
5381bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5382 return isKnownNegative(S) || isKnownPositive(S);
5383}
5384
5385bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5386 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005387 // Canonicalize the inputs first.
5388 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5389
Dan Gohman53c66ea2010-04-11 22:16:48 +00005390 // If LHS or RHS is an addrec, check to see if the condition is true in
5391 // every iteration of the loop.
5392 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5393 if (isLoopEntryGuardedByCond(
5394 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5395 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005396 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005397 return true;
5398 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5399 if (isLoopEntryGuardedByCond(
5400 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5401 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005402 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005403 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005404
Dan Gohman53c66ea2010-04-11 22:16:48 +00005405 // Otherwise see what can be done with known constant ranges.
5406 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5407}
5408
5409bool
5410ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5411 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005412 if (HasSameValue(LHS, RHS))
5413 return ICmpInst::isTrueWhenEqual(Pred);
5414
Dan Gohman53c66ea2010-04-11 22:16:48 +00005415 // This code is split out from isKnownPredicate because it is called from
5416 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005417 switch (Pred) {
5418 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005419 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005420 break;
5421 case ICmpInst::ICMP_SGT:
5422 Pred = ICmpInst::ICMP_SLT;
5423 std::swap(LHS, RHS);
5424 case ICmpInst::ICMP_SLT: {
5425 ConstantRange LHSRange = getSignedRange(LHS);
5426 ConstantRange RHSRange = getSignedRange(RHS);
5427 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5428 return true;
5429 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5430 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005431 break;
5432 }
5433 case ICmpInst::ICMP_SGE:
5434 Pred = ICmpInst::ICMP_SLE;
5435 std::swap(LHS, RHS);
5436 case ICmpInst::ICMP_SLE: {
5437 ConstantRange LHSRange = getSignedRange(LHS);
5438 ConstantRange RHSRange = getSignedRange(RHS);
5439 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5440 return true;
5441 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5442 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005443 break;
5444 }
5445 case ICmpInst::ICMP_UGT:
5446 Pred = ICmpInst::ICMP_ULT;
5447 std::swap(LHS, RHS);
5448 case ICmpInst::ICMP_ULT: {
5449 ConstantRange LHSRange = getUnsignedRange(LHS);
5450 ConstantRange RHSRange = getUnsignedRange(RHS);
5451 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5452 return true;
5453 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5454 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005455 break;
5456 }
5457 case ICmpInst::ICMP_UGE:
5458 Pred = ICmpInst::ICMP_ULE;
5459 std::swap(LHS, RHS);
5460 case ICmpInst::ICMP_ULE: {
5461 ConstantRange LHSRange = getUnsignedRange(LHS);
5462 ConstantRange RHSRange = getUnsignedRange(RHS);
5463 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5464 return true;
5465 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5466 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005467 break;
5468 }
5469 case ICmpInst::ICMP_NE: {
5470 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5471 return true;
5472 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5473 return true;
5474
5475 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5476 if (isKnownNonZero(Diff))
5477 return true;
5478 break;
5479 }
5480 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005481 // The check at the top of the function catches the case where
5482 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005483 break;
5484 }
5485 return false;
5486}
5487
5488/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5489/// protected by a conditional between LHS and RHS. This is used to
5490/// to eliminate casts.
5491bool
5492ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5493 ICmpInst::Predicate Pred,
5494 const SCEV *LHS, const SCEV *RHS) {
5495 // Interpret a null as meaning no loop, where there is obviously no guard
5496 // (interprocedural conditions notwithstanding).
5497 if (!L) return true;
5498
5499 BasicBlock *Latch = L->getLoopLatch();
5500 if (!Latch)
5501 return false;
5502
5503 BranchInst *LoopContinuePredicate =
5504 dyn_cast<BranchInst>(Latch->getTerminator());
5505 if (!LoopContinuePredicate ||
5506 LoopContinuePredicate->isUnconditional())
5507 return false;
5508
Dan Gohmanaf08a362010-08-10 23:46:30 +00005509 return isImpliedCond(Pred, LHS, RHS,
5510 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005511 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005512}
5513
Dan Gohman3948d0b2010-04-11 19:27:13 +00005514/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005515/// by a conditional between LHS and RHS. This is used to help avoid max
5516/// expressions in loop trip counts, and to eliminate casts.
5517bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005518ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5519 ICmpInst::Predicate Pred,
5520 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005521 // Interpret a null as meaning no loop, where there is obviously no guard
5522 // (interprocedural conditions notwithstanding).
5523 if (!L) return false;
5524
Dan Gohman859b4822009-05-18 15:36:09 +00005525 // Starting at the loop predecessor, climb up the predecessor chain, as long
5526 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005527 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005528 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005529 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005530 Pair.first;
5531 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005532
5533 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005534 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005535 if (!LoopEntryPredicate ||
5536 LoopEntryPredicate->isUnconditional())
5537 continue;
5538
Dan Gohmanaf08a362010-08-10 23:46:30 +00005539 if (isImpliedCond(Pred, LHS, RHS,
5540 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005541 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005542 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005543 }
5544
Dan Gohman38372182008-08-12 20:17:31 +00005545 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005546}
5547
Dan Gohman0f4b2852009-07-21 23:03:19 +00005548/// isImpliedCond - Test whether the condition described by Pred, LHS,
5549/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005550bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005551 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005552 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005553 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005554 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005556 if (BO->getOpcode() == Instruction::And) {
5557 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005558 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5559 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005560 } else if (BO->getOpcode() == Instruction::Or) {
5561 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005562 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5563 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005564 }
5565 }
5566
Dan Gohmanaf08a362010-08-10 23:46:30 +00005567 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005568 if (!ICI) return false;
5569
Dan Gohman85b05a22009-07-13 21:35:55 +00005570 // Bail if the ICmp's operands' types are wider than the needed type
5571 // before attempting to call getSCEV on them. This avoids infinite
5572 // recursion, since the analysis of widening casts can require loop
5573 // exit condition information for overflow checking, which would
5574 // lead back here.
5575 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005576 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005577 return false;
5578
Dan Gohman0f4b2852009-07-21 23:03:19 +00005579 // Now that we found a conditional branch that dominates the loop, check to
5580 // see if it is the comparison we are looking for.
5581 ICmpInst::Predicate FoundPred;
5582 if (Inverse)
5583 FoundPred = ICI->getInversePredicate();
5584 else
5585 FoundPred = ICI->getPredicate();
5586
5587 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5588 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005589
5590 // Balance the types. The case where FoundLHS' type is wider than
5591 // LHS' type is checked for above.
5592 if (getTypeSizeInBits(LHS->getType()) >
5593 getTypeSizeInBits(FoundLHS->getType())) {
5594 if (CmpInst::isSigned(Pred)) {
5595 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5596 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5597 } else {
5598 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5599 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5600 }
5601 }
5602
Dan Gohman0f4b2852009-07-21 23:03:19 +00005603 // Canonicalize the query to match the way instcombine will have
5604 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005605 if (SimplifyICmpOperands(Pred, LHS, RHS))
5606 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005607 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005608 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5609 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005610 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005611
5612 // Check to see if we can make the LHS or RHS match.
5613 if (LHS == FoundRHS || RHS == FoundLHS) {
5614 if (isa<SCEVConstant>(RHS)) {
5615 std::swap(FoundLHS, FoundRHS);
5616 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5617 } else {
5618 std::swap(LHS, RHS);
5619 Pred = ICmpInst::getSwappedPredicate(Pred);
5620 }
5621 }
5622
5623 // Check whether the found predicate is the same as the desired predicate.
5624 if (FoundPred == Pred)
5625 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5626
5627 // Check whether swapping the found predicate makes it the same as the
5628 // desired predicate.
5629 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5630 if (isa<SCEVConstant>(RHS))
5631 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5632 else
5633 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5634 RHS, LHS, FoundLHS, FoundRHS);
5635 }
5636
5637 // Check whether the actual condition is beyond sufficient.
5638 if (FoundPred == ICmpInst::ICMP_EQ)
5639 if (ICmpInst::isTrueWhenEqual(Pred))
5640 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5641 return true;
5642 if (Pred == ICmpInst::ICMP_NE)
5643 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5644 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5645 return true;
5646
5647 // Otherwise assume the worst.
5648 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005649}
5650
Dan Gohman0f4b2852009-07-21 23:03:19 +00005651/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005652/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005653/// and FoundRHS is true.
5654bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5655 const SCEV *LHS, const SCEV *RHS,
5656 const SCEV *FoundLHS,
5657 const SCEV *FoundRHS) {
5658 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5659 FoundLHS, FoundRHS) ||
5660 // ~x < ~y --> x > y
5661 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5662 getNotSCEV(FoundRHS),
5663 getNotSCEV(FoundLHS));
5664}
5665
5666/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005667/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005668/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005669bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005670ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5671 const SCEV *LHS, const SCEV *RHS,
5672 const SCEV *FoundLHS,
5673 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005674 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005675 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5676 case ICmpInst::ICMP_EQ:
5677 case ICmpInst::ICMP_NE:
5678 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5679 return true;
5680 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005681 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005682 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005683 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5684 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005685 return true;
5686 break;
5687 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005688 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005689 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5690 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005691 return true;
5692 break;
5693 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005694 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005695 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5696 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005697 return true;
5698 break;
5699 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005700 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005701 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5702 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005703 return true;
5704 break;
5705 }
5706
5707 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005708}
5709
Dan Gohman51f53b72009-06-21 23:46:38 +00005710/// getBECount - Subtract the end and start values and divide by the step,
5711/// rounding up, to get the number of times the backedge is executed. Return
5712/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005713const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005714 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005715 const SCEV *Step,
5716 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005717 assert(!isKnownNegative(Step) &&
5718 "This code doesn't handle negative strides yet!");
5719
Dan Gohman51f53b72009-06-21 23:46:38 +00005720 const Type *Ty = Start->getType();
Andrew Tricke62289b2011-03-09 17:29:58 +00005721
5722 // When Start == End, we have an exact BECount == 0. Short-circuit this case
5723 // here because SCEV may not be able to determine that the unsigned division
5724 // after rounding is zero.
5725 if (Start == End)
5726 return getConstant(Ty, 0);
5727
Dan Gohmandeff6212010-05-03 22:09:21 +00005728 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005729 const SCEV *Diff = getMinusSCEV(End, Start);
5730 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005731
5732 // Add an adjustment to the difference between End and Start so that
5733 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005734 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005735
Dan Gohman1f96e672009-09-17 18:05:20 +00005736 if (!NoWrap) {
5737 // Check Add for unsigned overflow.
5738 // TODO: More sophisticated things could be done here.
5739 const Type *WideTy = IntegerType::get(getContext(),
5740 getTypeSizeInBits(Ty) + 1);
5741 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5742 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5743 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5744 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5745 return getCouldNotCompute();
5746 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005747
5748 return getUDivExpr(Add, Step);
5749}
5750
Chris Lattnerdb25de42005-08-15 23:33:51 +00005751/// HowManyLessThans - Return the number of times a backedge containing the
5752/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005753/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005754ScalarEvolution::BackedgeTakenInfo
5755ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5756 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005757 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005758 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005759
Dan Gohman35738ac2009-05-04 22:30:44 +00005760 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005761 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005762 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005763
Dan Gohman1f96e672009-09-17 18:05:20 +00005764 // Check to see if we have a flag which makes analysis easy.
Andrew Trick3228cc22011-03-14 16:50:06 +00005765 bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5766 AddRec->getNoWrapFlags(SCEV::FlagNUW);
Dan Gohman1f96e672009-09-17 18:05:20 +00005767
Chris Lattnerdb25de42005-08-15 23:33:51 +00005768 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005769 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005770 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005771
Dan Gohman52fddd32010-01-26 04:40:18 +00005772 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005773 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005774 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005775 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005776 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005777 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005778 // value and past the maximum value for its type in a single step.
5779 // Note that it's not sufficient to check NoWrap here, because even
5780 // though the value after a wrap is undefined, it's not undefined
5781 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005782 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005783 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005784 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005785 if (isSigned) {
5786 APInt Max = APInt::getSignedMaxValue(BitWidth);
5787 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5788 .slt(getSignedRange(RHS).getSignedMax()))
5789 return getCouldNotCompute();
5790 } else {
5791 APInt Max = APInt::getMaxValue(BitWidth);
5792 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5793 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5794 return getCouldNotCompute();
5795 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005796 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005797 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005798 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005799
Dan Gohmana1af7572009-04-30 20:47:05 +00005800 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5801 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5802 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005803 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005804
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005805 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005806 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005807
Dan Gohmana1af7572009-04-30 20:47:05 +00005808 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005809 const SCEV *MinStart = getConstant(isSigned ?
5810 getSignedRange(Start).getSignedMin() :
5811 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005812
Dan Gohmana1af7572009-04-30 20:47:05 +00005813 // If we know that the condition is true in order to enter the loop,
5814 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005815 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5816 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005817 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005818 if (!isLoopEntryGuardedByCond(L,
5819 isSigned ? ICmpInst::ICMP_SLT :
5820 ICmpInst::ICMP_ULT,
5821 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005822 End = isSigned ? getSMaxExpr(RHS, Start)
5823 : getUMaxExpr(RHS, Start);
5824
5825 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005826 const SCEV *MaxEnd = getConstant(isSigned ?
5827 getSignedRange(End).getSignedMax() :
5828 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005829
Dan Gohman52fddd32010-01-26 04:40:18 +00005830 // If MaxEnd is within a step of the maximum integer value in its type,
5831 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005832 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005833 // compute the correct value.
5834 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005835 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005836 MaxEnd = isSigned ?
5837 getSMinExpr(MaxEnd,
5838 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5839 StepMinusOne)) :
5840 getUMinExpr(MaxEnd,
5841 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5842 StepMinusOne));
5843
Dan Gohmana1af7572009-04-30 20:47:05 +00005844 // Finally, we subtract these two values and divide, rounding up, to get
5845 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005846 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005847
5848 // The maximum backedge count is similar, except using the minimum start
5849 // value and the maximum end value.
Andrew Tricke62289b2011-03-09 17:29:58 +00005850 // If we already have an exact constant BECount, use it instead.
5851 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
5852 : getBECount(MinStart, MaxEnd, Step, NoWrap);
5853
5854 // If the stride is nonconstant, and NoWrap == true, then
5855 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
5856 // exact BECount and invalid MaxBECount, which should be avoided to catch
5857 // more optimization opportunities.
5858 if (isa<SCEVCouldNotCompute>(MaxBECount))
5859 MaxBECount = BECount;
Dan Gohmana1af7572009-04-30 20:47:05 +00005860
5861 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005862 }
5863
Dan Gohman1c343752009-06-27 21:21:31 +00005864 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005865}
5866
Chris Lattner53e677a2004-04-02 20:23:17 +00005867/// getNumIterationsInRange - Return the number of iterations of this loop that
5868/// produce values in the specified constant range. Another way of looking at
5869/// this is that it returns the first iteration number where the value is not in
5870/// the condition, thus computing the exit count. If the iteration count can't
5871/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005872const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005873 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005874 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005875 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005876
5877 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005878 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005879 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005880 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005881 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00005882 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
5883 // FIXME: getNoWrapFlags(FlagNW)
5884 FlagAnyWrap);
Dan Gohman622ed672009-05-04 22:02:23 +00005885 if (const SCEVAddRecExpr *ShiftedAddRec =
5886 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005887 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005888 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005889 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005890 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005891 }
5892
5893 // The only time we can solve this is when we have all constant indices.
5894 // Otherwise, we cannot determine the overflow conditions.
5895 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5896 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005897 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005898
5899
5900 // Okay at this point we know that all elements of the chrec are constants and
5901 // that the start element is zero.
5902
5903 // First check to see if the range contains zero. If not, the first
5904 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005905 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005906 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005907 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005908
Chris Lattner53e677a2004-04-02 20:23:17 +00005909 if (isAffine()) {
5910 // If this is an affine expression then we have this situation:
5911 // Solve {0,+,A} in Range === Ax in Range
5912
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005913 // We know that zero is in the range. If A is positive then we know that
5914 // the upper value of the range must be the first possible exit value.
5915 // If A is negative then the lower of the range is the last possible loop
5916 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005917 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005918 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5919 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005920
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005921 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005922 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005923 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005924
5925 // Evaluate at the exit value. If we really did fall out of the valid
5926 // range, then we computed our trip count, otherwise wrap around or other
5927 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005928 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005929 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005930 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005931
5932 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005933 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005934 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005935 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005936 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005937 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005938 } else if (isQuadratic()) {
5939 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5940 // quadratic equation to solve it. To do this, we must frame our problem in
5941 // terms of figuring out when zero is crossed, instead of when
5942 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005943 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005944 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick3228cc22011-03-14 16:50:06 +00005945 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
5946 // getNoWrapFlags(FlagNW)
5947 FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00005948
5949 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005950 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005951 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005952 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5953 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005954 if (R1) {
5955 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005956 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005957 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005958 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005959 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005960 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005961
Chris Lattner53e677a2004-04-02 20:23:17 +00005962 // Make sure the root is not off by one. The returned iteration should
5963 // not be in the range, but the previous one should be. When solving
5964 // for "X*X < 5", for example, we should not return a root of 2.
5965 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005966 R1->getValue(),
5967 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005968 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005969 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005970 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005971 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005972
Dan Gohman246b2562007-10-22 18:31:58 +00005973 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005974 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005975 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005976 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005977 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005978
Chris Lattner53e677a2004-04-02 20:23:17 +00005979 // If R1 was not in the range, then it is a good return value. Make
5980 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005981 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005982 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005983 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005984 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005985 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005986 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005987 }
5988 }
5989 }
5990
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005991 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005992}
5993
5994
5995
5996//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005997// SCEVCallbackVH Class Implementation
5998//===----------------------------------------------------------------------===//
5999
Dan Gohman1959b752009-05-19 19:22:47 +00006000void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006001 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00006002 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6003 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006004 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00006005 // this now dangles!
6006}
6007
Dan Gohman81f91212010-07-28 01:09:07 +00006008void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006009 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00006010
Dan Gohman35738ac2009-05-04 22:30:44 +00006011 // Forget all the expressions associated with users of the old value,
6012 // so that future queries will recompute the expressions using the new
6013 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00006014 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00006015 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00006016 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00006017 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6018 UI != UE; ++UI)
6019 Worklist.push_back(*UI);
6020 while (!Worklist.empty()) {
6021 User *U = Worklist.pop_back_val();
6022 // Deleting the Old value will cause this to dangle. Postpone
6023 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00006024 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00006025 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00006026 if (!Visited.insert(U))
6027 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00006028 if (PHINode *PN = dyn_cast<PHINode>(U))
6029 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006030 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00006031 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6032 UI != UE; ++UI)
6033 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00006034 }
Dan Gohman59846ac2010-07-28 00:28:25 +00006035 // Delete the Old value.
6036 if (PHINode *PN = dyn_cast<PHINode>(Old))
6037 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006038 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00006039 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00006040}
6041
Dan Gohman1959b752009-05-19 19:22:47 +00006042ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00006043 : CallbackVH(V), SE(se) {}
6044
6045//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00006046// ScalarEvolution Class Implementation
6047//===----------------------------------------------------------------------===//
6048
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006049ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00006050 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00006051 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006052}
6053
Chris Lattner53e677a2004-04-02 20:23:17 +00006054bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006055 this->F = &F;
6056 LI = &getAnalysis<LoopInfo>();
6057 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00006058 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00006059 return false;
6060}
6061
6062void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00006063 // Iterate through all the SCEVUnknown instances and call their
6064 // destructors, so that they release their references to their values.
6065 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6066 U->~SCEVUnknown();
6067 FirstUnknown = 0;
6068
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006069 ValueExprMap.clear();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006070 BackedgeTakenCounts.clear();
6071 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00006072 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00006073 LoopDispositions.clear();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006074 BlockDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00006075 UnsignedRanges.clear();
6076 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00006077 UniqueSCEVs.clear();
6078 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00006079}
6080
6081void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6082 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00006083 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00006084 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00006085}
6086
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006087bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006088 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00006089}
6090
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006091static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00006092 const Loop *L) {
6093 // Print all inner loops first
6094 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6095 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006096
Dan Gohman30733292010-01-09 18:17:45 +00006097 OS << "Loop ";
6098 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6099 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006100
Dan Gohman5d984912009-12-18 01:14:11 +00006101 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006102 L->getExitBlocks(ExitBlocks);
6103 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00006104 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006105
Dan Gohman46bdfb02009-02-24 18:55:53 +00006106 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6107 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00006108 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006109 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006110 }
6111
Dan Gohman30733292010-01-09 18:17:45 +00006112 OS << "\n"
6113 "Loop ";
6114 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6115 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00006116
6117 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6118 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6119 } else {
6120 OS << "Unpredictable max backedge-taken count. ";
6121 }
6122
6123 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006124}
6125
Dan Gohman5d984912009-12-18 01:14:11 +00006126void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006127 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006128 // out SCEV values of all instructions that are interesting. Doing
6129 // this potentially causes it to create new SCEV objects though,
6130 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00006131 // observable from outside the class though, so casting away the
6132 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00006133 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00006134
Dan Gohman30733292010-01-09 18:17:45 +00006135 OS << "Classifying expressions for: ";
6136 WriteAsOperand(OS, F, /*PrintType=*/false);
6137 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006138 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00006139 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00006140 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00006141 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006142 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006143 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006144
Dan Gohman0c689c52009-06-19 17:49:54 +00006145 const Loop *L = LI->getLoopFor((*I).getParent());
6146
Dan Gohman0bba49c2009-07-07 17:06:11 +00006147 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00006148 if (AtUse != SV) {
6149 OS << " --> ";
6150 AtUse->print(OS);
6151 }
6152
6153 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00006154 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006155 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00006156 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006157 OS << "<<Unknown>>";
6158 } else {
6159 OS << *ExitValue;
6160 }
6161 }
6162
Chris Lattner53e677a2004-04-02 20:23:17 +00006163 OS << "\n";
6164 }
6165
Dan Gohman30733292010-01-09 18:17:45 +00006166 OS << "Determining loop execution counts for: ";
6167 WriteAsOperand(OS, F, /*PrintType=*/false);
6168 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006169 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6170 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006171}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00006172
Dan Gohman714b5292010-11-17 23:21:44 +00006173ScalarEvolution::LoopDisposition
6174ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6175 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6176 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6177 Values.insert(std::make_pair(L, LoopVariant));
6178 if (!Pair.second)
6179 return Pair.first->second;
6180
6181 LoopDisposition D = computeLoopDisposition(S, L);
6182 return LoopDispositions[S][L] = D;
6183}
6184
6185ScalarEvolution::LoopDisposition
6186ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00006187 switch (S->getSCEVType()) {
6188 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00006189 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006190 case scTruncate:
6191 case scZeroExtend:
6192 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00006193 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006194 case scAddRecExpr: {
6195 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6196
Dan Gohman714b5292010-11-17 23:21:44 +00006197 // If L is the addrec's loop, it's computable.
6198 if (AR->getLoop() == L)
6199 return LoopComputable;
6200
Dan Gohman17ead4f2010-11-17 21:23:15 +00006201 // Add recurrences are never invariant in the function-body (null loop).
6202 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00006203 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006204
6205 // This recurrence is variant w.r.t. L if L contains AR's loop.
6206 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00006207 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006208
6209 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6210 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00006211 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006212
6213 // This recurrence is variant w.r.t. L if any of its operands
6214 // are variant.
6215 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6216 I != E; ++I)
6217 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00006218 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006219
6220 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00006221 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006222 }
6223 case scAddExpr:
6224 case scMulExpr:
6225 case scUMaxExpr:
6226 case scSMaxExpr: {
6227 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006228 bool HasVarying = false;
6229 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6230 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00006231 LoopDisposition D = getLoopDisposition(*I, L);
6232 if (D == LoopVariant)
6233 return LoopVariant;
6234 if (D == LoopComputable)
6235 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006236 }
Dan Gohman714b5292010-11-17 23:21:44 +00006237 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006238 }
6239 case scUDivExpr: {
6240 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00006241 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6242 if (LD == LoopVariant)
6243 return LoopVariant;
6244 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6245 if (RD == LoopVariant)
6246 return LoopVariant;
6247 return (LD == LoopInvariant && RD == LoopInvariant) ?
6248 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006249 }
6250 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00006251 // All non-instruction values are loop invariant. All instructions are loop
6252 // invariant if they are not contained in the specified loop.
6253 // Instructions are never considered invariant in the function body
6254 // (null loop) because they are defined within the "loop".
6255 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6256 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6257 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006258 case scCouldNotCompute:
6259 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00006260 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006261 default: break;
6262 }
6263 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00006264 return LoopVariant;
6265}
6266
6267bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6268 return getLoopDisposition(S, L) == LoopInvariant;
6269}
6270
6271bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6272 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006273}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006274
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006275ScalarEvolution::BlockDisposition
6276ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6277 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6278 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6279 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6280 if (!Pair.second)
6281 return Pair.first->second;
6282
6283 BlockDisposition D = computeBlockDisposition(S, BB);
6284 return BlockDispositions[S][BB] = D;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006285}
6286
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006287ScalarEvolution::BlockDisposition
6288ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006289 switch (S->getSCEVType()) {
6290 case scConstant:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006291 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006292 case scTruncate:
6293 case scZeroExtend:
6294 case scSignExtend:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006295 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006296 case scAddRecExpr: {
6297 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006298 // to test for proper dominance too, because the instruction which
6299 // produces the addrec's value is a PHI, and a PHI effectively properly
6300 // dominates its entire containing block.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006301 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6302 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006303 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006304 }
6305 // FALL THROUGH into SCEVNAryExpr handling.
6306 case scAddExpr:
6307 case scMulExpr:
6308 case scUMaxExpr:
6309 case scSMaxExpr: {
6310 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006311 bool Proper = true;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006312 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006313 I != E; ++I) {
6314 BlockDisposition D = getBlockDisposition(*I, BB);
6315 if (D == DoesNotDominateBlock)
6316 return DoesNotDominateBlock;
6317 if (D == DominatesBlock)
6318 Proper = false;
6319 }
6320 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006321 }
6322 case scUDivExpr: {
6323 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006324 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6325 BlockDisposition LD = getBlockDisposition(LHS, BB);
6326 if (LD == DoesNotDominateBlock)
6327 return DoesNotDominateBlock;
6328 BlockDisposition RD = getBlockDisposition(RHS, BB);
6329 if (RD == DoesNotDominateBlock)
6330 return DoesNotDominateBlock;
6331 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6332 ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006333 }
6334 case scUnknown:
6335 if (Instruction *I =
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006336 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6337 if (I->getParent() == BB)
6338 return DominatesBlock;
6339 if (DT->properlyDominates(I->getParent(), BB))
6340 return ProperlyDominatesBlock;
6341 return DoesNotDominateBlock;
6342 }
6343 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006344 case scCouldNotCompute:
6345 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006346 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006347 default: break;
6348 }
6349 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006350 return DoesNotDominateBlock;
6351}
6352
6353bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6354 return getBlockDisposition(S, BB) >= DominatesBlock;
6355}
6356
6357bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6358 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006359}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006360
6361bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6362 switch (S->getSCEVType()) {
6363 case scConstant:
6364 return false;
6365 case scTruncate:
6366 case scZeroExtend:
6367 case scSignExtend: {
6368 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6369 const SCEV *CastOp = Cast->getOperand();
6370 return Op == CastOp || hasOperand(CastOp, Op);
6371 }
6372 case scAddRecExpr:
6373 case scAddExpr:
6374 case scMulExpr:
6375 case scUMaxExpr:
6376 case scSMaxExpr: {
6377 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6378 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6379 I != E; ++I) {
6380 const SCEV *NAryOp = *I;
6381 if (NAryOp == Op || hasOperand(NAryOp, Op))
6382 return true;
6383 }
6384 return false;
6385 }
6386 case scUDivExpr: {
6387 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6388 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6389 return LHS == Op || hasOperand(LHS, Op) ||
6390 RHS == Op || hasOperand(RHS, Op);
6391 }
6392 case scUnknown:
6393 return false;
6394 case scCouldNotCompute:
6395 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6396 return false;
6397 default: break;
6398 }
6399 llvm_unreachable("Unknown SCEV kind!");
6400 return false;
6401}
Dan Gohman56a75682010-11-17 23:28:48 +00006402
6403void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6404 ValuesAtScopes.erase(S);
6405 LoopDispositions.erase(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006406 BlockDispositions.erase(S);
Dan Gohman56a75682010-11-17 23:28:48 +00006407 UnsignedRanges.erase(S);
6408 SignedRanges.erase(S);
6409}