blob: a64a7c183305100c6f7c0522630587dc87db0e77 [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 Trick3228cc22011-03-14 16:50:06 +00001795 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001796 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001797
1798 if (Ops.size() == 1)
1799 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001800 }
1801
1802 // Skip over the add expression until we get to a multiply.
1803 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1804 ++Idx;
1805
Chris Lattner53e677a2004-04-02 20:23:17 +00001806 // If there are mul operands inline them all into this expression.
1807 if (Idx < Ops.size()) {
1808 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001809 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001810 // If we have an mul, expand the mul operands onto the end of the operands
1811 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001812 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001813 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001814 DeletedMul = true;
1815 }
1816
1817 // If we deleted at least one mul, we added operands to the end of the list,
1818 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001819 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001820 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001821 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001822 }
1823
1824 // If there are any add recurrences in the operands list, see if any other
1825 // added values are loop invariant. If so, we can fold them into the
1826 // recurrence.
1827 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1828 ++Idx;
1829
1830 // Scan over all recurrences, trying to fold loop invariants into them.
1831 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1832 // Scan all of the other operands to this mul and add them to the vector if
1833 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001834 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001835 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001836 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001837 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001838 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001839 LIOps.push_back(Ops[i]);
1840 Ops.erase(Ops.begin()+i);
1841 --i; --e;
1842 }
1843
1844 // If we found some loop invariants, fold them into the recurrence.
1845 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001846 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001847 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001848 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001849 const SCEV *Scale = getMulExpr(LIOps);
1850 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1851 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001852
Dan Gohmanb9f96512010-06-30 07:16:37 +00001853 // Build the new addrec. Propagate the NUW and NSW flags if both the
1854 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick3228cc22011-03-14 16:50:06 +00001855 //
1856 // No self-wrap cannot be guaranteed after changing the step size, but
1857 // will be infered if either NUW or NSW is true.
1858 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1859 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001860
1861 // If all of the other operands were loop invariant, we are done.
1862 if (Ops.size() == 1) return NewRec;
1863
1864 // Otherwise, multiply the folded AddRec by the non-liv parts.
1865 for (unsigned i = 0;; ++i)
1866 if (Ops[i] == AddRec) {
1867 Ops[i] = NewRec;
1868 break;
1869 }
Dan Gohman246b2562007-10-22 18:31:58 +00001870 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001871 }
1872
1873 // Okay, if there weren't any loop invariants to be folded, check to see if
1874 // there are multiple AddRec's with the same loop induction variable being
1875 // multiplied together. If so, we can fold them.
1876 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001877 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1878 ++OtherIdx)
1879 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1880 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1881 // {A*C,+,F*D + G*B + B*D}<L>
1882 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1883 ++OtherIdx)
1884 if (const SCEVAddRecExpr *OtherAddRec =
1885 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1886 if (OtherAddRec->getLoop() == AddRecLoop) {
1887 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1888 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1889 const SCEV *B = F->getStepRecurrence(*this);
1890 const SCEV *D = G->getStepRecurrence(*this);
1891 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1892 getMulExpr(G, B),
1893 getMulExpr(B, D));
1894 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Andrew Trick3228cc22011-03-14 16:50:06 +00001895 F->getLoop(),
1896 SCEV::FlagAnyWrap);
Dan Gohman6a0c1252010-08-31 22:52:12 +00001897 if (Ops.size() == 2) return NewAddRec;
1898 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1899 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1900 }
1901 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001902 }
1903
1904 // Otherwise couldn't fold anything into this recurrence. Move onto the
1905 // next one.
1906 }
1907
1908 // Okay, it looks like we really DO need an mul expr. Check to see if we
1909 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001910 FoldingSetNodeID ID;
1911 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001912 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1913 ID.AddPointer(Ops[i]);
1914 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001915 SCEVMulExpr *S =
1916 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1917 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001918 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1919 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001920 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1921 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001922 UniqueSCEVs.InsertNode(S, IP);
1923 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001924 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001925 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001926}
1927
Andreas Bolka8a11c982009-08-07 22:55:26 +00001928/// getUDivExpr - Get a canonical unsigned division expression, or something
1929/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001930const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1931 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001932 assert(getEffectiveSCEVType(LHS->getType()) ==
1933 getEffectiveSCEVType(RHS->getType()) &&
1934 "SCEVUDivExpr operand types don't match!");
1935
Dan Gohman622ed672009-05-04 22:02:23 +00001936 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001937 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001938 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001939 // If the denominator is zero, the result of the udiv is undefined. Don't
1940 // try to analyze it, because the resolution chosen here may differ from
1941 // the resolution chosen in other parts of the compiler.
1942 if (!RHSC->getValue()->isZero()) {
1943 // Determine if the division can be folded into the operands of
1944 // its operands.
1945 // TODO: Generalize this to non-constants by using known-bits information.
1946 const Type *Ty = LHS->getType();
1947 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001948 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001949 // For non-power-of-two values, effectively round the value up to the
1950 // nearest power of two.
1951 if (!RHSC->getValue()->getValue().isPowerOf2())
1952 ++MaxShiftAmt;
1953 const IntegerType *ExtTy =
1954 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1955 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1956 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1957 if (const SCEVConstant *Step =
1958 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1959 if (!Step->getValue()->getValue()
1960 .urem(RHSC->getValue()->getValue()) &&
1961 getZeroExtendExpr(AR, ExtTy) ==
1962 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1963 getZeroExtendExpr(Step, ExtTy),
Andrew Trick3228cc22011-03-14 16:50:06 +00001964 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001965 SmallVector<const SCEV *, 4> Operands;
1966 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1967 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick3228cc22011-03-14 16:50:06 +00001968 return getAddRecExpr(Operands, AR->getLoop(),
1969 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
1970 SCEV::FlagAnyWrap);
Dan Gohman185cf032009-05-08 20:18:49 +00001971 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001972 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1973 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1974 SmallVector<const SCEV *, 4> Operands;
1975 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1976 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1977 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1978 // Find an operand that's safely divisible.
1979 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1980 const SCEV *Op = M->getOperand(i);
1981 const SCEV *Div = getUDivExpr(Op, RHSC);
1982 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1983 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1984 M->op_end());
1985 Operands[i] = Div;
1986 return getMulExpr(Operands);
1987 }
1988 }
Dan Gohman185cf032009-05-08 20:18:49 +00001989 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001990 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1991 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1992 SmallVector<const SCEV *, 4> Operands;
1993 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1994 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1995 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1996 Operands.clear();
1997 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1998 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1999 if (isa<SCEVUDivExpr>(Op) ||
2000 getMulExpr(Op, RHS) != A->getOperand(i))
2001 break;
2002 Operands.push_back(Op);
2003 }
2004 if (Operands.size() == A->getNumOperands())
2005 return getAddExpr(Operands);
2006 }
2007 }
Dan Gohman185cf032009-05-08 20:18:49 +00002008
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002009 // Fold if both operands are constant.
2010 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2011 Constant *LHSCV = LHSC->getValue();
2012 Constant *RHSCV = RHSC->getValue();
2013 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2014 RHSCV)));
2015 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002016 }
2017 }
2018
Dan Gohman1c343752009-06-27 21:21:31 +00002019 FoldingSetNodeID ID;
2020 ID.AddInteger(scUDivExpr);
2021 ID.AddPointer(LHS);
2022 ID.AddPointer(RHS);
2023 void *IP = 0;
2024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00002025 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2026 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00002027 UniqueSCEVs.InsertNode(S, IP);
2028 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002029}
2030
2031
Dan Gohman6c0866c2009-05-24 23:45:28 +00002032/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2033/// Simplify the expression as much as possible.
Andrew Trick3228cc22011-03-14 16:50:06 +00002034const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2035 const Loop *L,
2036 SCEV::NoWrapFlags Flags) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002037 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002038 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002039 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002040 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002041 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trick3228cc22011-03-14 16:50:06 +00002042 // FIXME: can use maskFlags(Flags, SCEV::FlagNW)
2043 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00002044 }
2045
2046 Operands.push_back(Step);
Andrew Trick3228cc22011-03-14 16:50:06 +00002047 return getAddRecExpr(Operands, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002048}
2049
Dan Gohman6c0866c2009-05-24 23:45:28 +00002050/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2051/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002052const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002053ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick3228cc22011-03-14 16:50:06 +00002054 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002055 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002056#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002057 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002058 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002059 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002060 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00002061 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002062 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00002063 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00002064#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002065
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002066 if (Operands.back()->isZero()) {
2067 Operands.pop_back();
Andrew Trick3228cc22011-03-14 16:50:06 +00002068 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002069 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002070
Dan Gohmanbc028532010-02-19 18:49:22 +00002071 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2072 // use that information to infer NUW and NSW flags. However, computing a
2073 // BE count requires calling getAddRecExpr, so we may not yet have a
2074 // meaningful BE count at this point (and if we don't, we'd be stuck
2075 // with a SCEVCouldNotCompute as the cached BE count).
2076
Andrew Trick3228cc22011-03-14 16:50:06 +00002077 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2078 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002079 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00002080 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2081 E = Operands.end(); I != E; ++I)
2082 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002083 All = false;
2084 break;
2085 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002086 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002087 }
2088
Dan Gohmand9cc7492008-08-08 18:33:12 +00002089 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002090 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002091 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002092 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002093 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002094 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002095 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002096 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002097 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002098 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002099 // AddRecs require their operands be loop-invariant with respect to their
2100 // loops. Don't perform this transformation if it would break this
2101 // requirement.
2102 bool AllInvariant = true;
2103 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002104 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002105 AllInvariant = false;
2106 break;
2107 }
2108 if (AllInvariant) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002109 // Create a recurrence for the outer loop with the same step size.
2110 //
2111 // FIXME:
2112 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2113 // inner recurrence has the same property.
2114 // maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2115 SCEV::NoWrapFlags OuterFlags = SCEV::FlagAnyWrap;
2116
2117 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohman9a80b452009-06-26 22:36:20 +00002118 AllInvariant = true;
2119 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002120 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002121 AllInvariant = false;
2122 break;
2123 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002124 if (AllInvariant) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002125 // Ok, both add recurrences are valid after the transformation.
Andrew Trick3228cc22011-03-14 16:50:06 +00002126 //
2127 // FIXME:
2128 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2129 // the outer recurrence has the same property.
2130 // maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2131 SCEV::NoWrapFlags InnerFlags = SCEV::FlagAnyWrap;
2132 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2133 }
Dan Gohman9a80b452009-06-26 22:36:20 +00002134 }
2135 // Reset Operands to its original state.
2136 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002137 }
2138 }
2139
Dan Gohman67847532010-01-19 22:27:22 +00002140 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2141 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002142 FoldingSetNodeID ID;
2143 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002144 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2145 ID.AddPointer(Operands[i]);
2146 ID.AddPointer(L);
2147 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002148 SCEVAddRecExpr *S =
2149 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2150 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002151 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2152 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002153 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2154 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002155 UniqueSCEVs.InsertNode(S, IP);
2156 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002157 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002158 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002159}
2160
Dan Gohman9311ef62009-06-24 14:49:00 +00002161const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2162 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002163 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002164 Ops.push_back(LHS);
2165 Ops.push_back(RHS);
2166 return getSMaxExpr(Ops);
2167}
2168
Dan Gohman0bba49c2009-07-07 17:06:11 +00002169const SCEV *
2170ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002171 assert(!Ops.empty() && "Cannot get empty smax!");
2172 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002173#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002174 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002175 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002176 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002177 "SCEVSMaxExpr operand types don't match!");
2178#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002179
2180 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002181 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002182
2183 // If there are any constants, fold them together.
2184 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002185 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002186 ++Idx;
2187 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002188 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002189 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002190 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002191 APIntOps::smax(LHSC->getValue()->getValue(),
2192 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002193 Ops[0] = getConstant(Fold);
2194 Ops.erase(Ops.begin()+1); // Erase the folded element
2195 if (Ops.size() == 1) return Ops[0];
2196 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002197 }
2198
Dan Gohmane5aceed2009-06-24 14:46:22 +00002199 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002200 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2201 Ops.erase(Ops.begin());
2202 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002203 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2204 // If we have an smax with a constant maximum-int, it will always be
2205 // maximum-int.
2206 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002207 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002208
Dan Gohman3ab13122010-04-13 16:49:23 +00002209 if (Ops.size() == 1) return Ops[0];
2210 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002211
2212 // Find the first SMax
2213 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2214 ++Idx;
2215
2216 // Check to see if one of the operands is an SMax. If so, expand its operands
2217 // onto our operand list, and recurse to simplify.
2218 if (Idx < Ops.size()) {
2219 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002220 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002221 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002222 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002223 DeletedSMax = true;
2224 }
2225
2226 if (DeletedSMax)
2227 return getSMaxExpr(Ops);
2228 }
2229
2230 // Okay, check to see if the same value occurs in the operand list twice. If
2231 // so, delete one. Since we sorted the list, these values are required to
2232 // be adjacent.
2233 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002234 // X smax Y smax Y --> X smax Y
2235 // X smax Y --> X, if X is always greater than Y
2236 if (Ops[i] == Ops[i+1] ||
2237 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2238 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2239 --i; --e;
2240 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002241 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2242 --i; --e;
2243 }
2244
2245 if (Ops.size() == 1) return Ops[0];
2246
2247 assert(!Ops.empty() && "Reduced smax down to nothing!");
2248
Nick Lewycky3e630762008-02-20 06:48:22 +00002249 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002250 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002251 FoldingSetNodeID ID;
2252 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002253 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2254 ID.AddPointer(Ops[i]);
2255 void *IP = 0;
2256 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002257 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2258 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002259 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2260 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002261 UniqueSCEVs.InsertNode(S, IP);
2262 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002263}
2264
Dan Gohman9311ef62009-06-24 14:49:00 +00002265const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2266 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002267 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002268 Ops.push_back(LHS);
2269 Ops.push_back(RHS);
2270 return getUMaxExpr(Ops);
2271}
2272
Dan Gohman0bba49c2009-07-07 17:06:11 +00002273const SCEV *
2274ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002275 assert(!Ops.empty() && "Cannot get empty umax!");
2276 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002277#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002278 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002279 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002280 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002281 "SCEVUMaxExpr operand types don't match!");
2282#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002283
2284 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002285 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002286
2287 // If there are any constants, fold them together.
2288 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002289 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002290 ++Idx;
2291 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002292 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002293 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002294 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002295 APIntOps::umax(LHSC->getValue()->getValue(),
2296 RHSC->getValue()->getValue()));
2297 Ops[0] = getConstant(Fold);
2298 Ops.erase(Ops.begin()+1); // Erase the folded element
2299 if (Ops.size() == 1) return Ops[0];
2300 LHSC = cast<SCEVConstant>(Ops[0]);
2301 }
2302
Dan Gohmane5aceed2009-06-24 14:46:22 +00002303 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002304 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2305 Ops.erase(Ops.begin());
2306 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002307 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2308 // If we have an umax with a constant maximum-int, it will always be
2309 // maximum-int.
2310 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002311 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002312
Dan Gohman3ab13122010-04-13 16:49:23 +00002313 if (Ops.size() == 1) return Ops[0];
2314 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002315
2316 // Find the first UMax
2317 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2318 ++Idx;
2319
2320 // Check to see if one of the operands is a UMax. If so, expand its operands
2321 // onto our operand list, and recurse to simplify.
2322 if (Idx < Ops.size()) {
2323 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002324 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002325 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002326 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002327 DeletedUMax = true;
2328 }
2329
2330 if (DeletedUMax)
2331 return getUMaxExpr(Ops);
2332 }
2333
2334 // Okay, check to see if the same value occurs in the operand list twice. If
2335 // so, delete one. Since we sorted the list, these values are required to
2336 // be adjacent.
2337 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002338 // X umax Y umax Y --> X umax Y
2339 // X umax Y --> X, if X is always greater than Y
2340 if (Ops[i] == Ops[i+1] ||
2341 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2342 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2343 --i; --e;
2344 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002345 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2346 --i; --e;
2347 }
2348
2349 if (Ops.size() == 1) return Ops[0];
2350
2351 assert(!Ops.empty() && "Reduced umax down to nothing!");
2352
2353 // Okay, it looks like we really DO need a umax expr. Check to see if we
2354 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002355 FoldingSetNodeID ID;
2356 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002357 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2358 ID.AddPointer(Ops[i]);
2359 void *IP = 0;
2360 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002361 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2362 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002363 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2364 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002365 UniqueSCEVs.InsertNode(S, IP);
2366 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002367}
2368
Dan Gohman9311ef62009-06-24 14:49:00 +00002369const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2370 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002371 // ~smax(~x, ~y) == smin(x, y).
2372 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2373}
2374
Dan Gohman9311ef62009-06-24 14:49:00 +00002375const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2376 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002377 // ~umax(~x, ~y) == umin(x, y)
2378 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2379}
2380
Dan Gohman4f8eea82010-02-01 18:27:38 +00002381const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002382 // If we have TargetData, we can bypass creating a target-independent
2383 // constant expression and then folding it back into a ConstantInt.
2384 // This is just a compile-time optimization.
2385 if (TD)
2386 return getConstant(TD->getIntPtrType(getContext()),
2387 TD->getTypeAllocSize(AllocTy));
2388
Dan Gohman4f8eea82010-02-01 18:27:38 +00002389 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002391 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2392 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002393 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2394 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2395}
2396
2397const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2398 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2399 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002400 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2401 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002402 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2403 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2404}
2405
2406const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2407 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002408 // If we have TargetData, we can bypass creating a target-independent
2409 // constant expression and then folding it back into a ConstantInt.
2410 // This is just a compile-time optimization.
2411 if (TD)
2412 return getConstant(TD->getIntPtrType(getContext()),
2413 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2414
Dan Gohman0f5efe52010-01-28 02:15:55 +00002415 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2416 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002417 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2418 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002419 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002420 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002421}
2422
Dan Gohman4f8eea82010-02-01 18:27:38 +00002423const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2424 Constant *FieldNo) {
2425 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002426 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002427 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2428 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002429 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002430 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002431}
2432
Dan Gohman0bba49c2009-07-07 17:06:11 +00002433const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002434 // Don't attempt to do anything other than create a SCEVUnknown object
2435 // here. createSCEV only calls getUnknown after checking for all other
2436 // interesting possibilities, and any other code that calls getUnknown
2437 // is doing so in order to hide a value from SCEV canonicalization.
2438
Dan Gohman1c343752009-06-27 21:21:31 +00002439 FoldingSetNodeID ID;
2440 ID.AddInteger(scUnknown);
2441 ID.AddPointer(V);
2442 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002443 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2444 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2445 "Stale SCEVUnknown in uniquing map!");
2446 return S;
2447 }
2448 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2449 FirstUnknown);
2450 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002451 UniqueSCEVs.InsertNode(S, IP);
2452 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002453}
2454
Chris Lattner53e677a2004-04-02 20:23:17 +00002455//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002456// Basic SCEV Analysis and PHI Idiom Recognition Code
2457//
2458
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002459/// isSCEVable - Test if values of the given type are analyzable within
2460/// the SCEV framework. This primarily includes integer types, and it
2461/// can optionally include pointer types if the ScalarEvolution class
2462/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002463bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002464 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002465 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002466}
2467
2468/// getTypeSizeInBits - Return the size in bits of the specified type,
2469/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002470uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002471 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2472
2473 // If we have a TargetData, use it!
2474 if (TD)
2475 return TD->getTypeSizeInBits(Ty);
2476
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002477 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002478 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002479 return Ty->getPrimitiveSizeInBits();
2480
2481 // The only other support type is pointer. Without TargetData, conservatively
2482 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002483 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002484 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002485}
2486
2487/// getEffectiveSCEVType - Return a type with the same bitwidth as
2488/// the given type and which represents how SCEV will treat the given
2489/// type, for which isSCEVable must return true. For pointer types,
2490/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002491const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002492 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2493
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002494 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002495 return Ty;
2496
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002497 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002498 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002499 if (TD) return TD->getIntPtrType(getContext());
2500
2501 // Without TargetData, conservatively assume pointers are 64-bit.
2502 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002503}
Chris Lattner53e677a2004-04-02 20:23:17 +00002504
Dan Gohman0bba49c2009-07-07 17:06:11 +00002505const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002506 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002507}
2508
Chris Lattner53e677a2004-04-02 20:23:17 +00002509/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2510/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002511const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002512 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002513
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002514 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2515 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002516 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002517
2518 // The process of creating a SCEV for V may have caused other SCEVs
2519 // to have been created, so it's necessary to insert the new entry
2520 // from scratch, rather than trying to remember the insert position
2521 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002522 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002523 return S;
2524}
2525
Dan Gohman2d1be872009-04-16 03:18:22 +00002526/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2527///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002528const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002529 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002530 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002531 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002532
2533 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002534 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002535 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002536 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002537}
2538
2539/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002540const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002541 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002542 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002543 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002544
2545 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002546 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002547 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002548 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002549 return getMinusSCEV(AllOnes, V);
2550}
2551
Andrew Trick3228cc22011-03-14 16:50:06 +00002552/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
2553///
2554/// FIXME: prohibit FlagNUW here, as soon as getMinusSCEVForExitTest goes.
Chris Lattner992efb02011-01-09 22:26:35 +00002555const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00002556 SCEV::NoWrapFlags Flags) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002557 // Fast path: X - X --> 0.
2558 if (LHS == RHS)
2559 return getConstant(LHS->getType(), 0);
2560
Dan Gohman2d1be872009-04-16 03:18:22 +00002561 // X - Y --> X + -Y
Andrew Trick3228cc22011-03-14 16:50:06 +00002562 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman2d1be872009-04-16 03:18:22 +00002563}
2564
2565/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2566/// input value to the specified type. If the type must be extended, it is zero
2567/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002568const SCEV *
Chris Lattner992efb02011-01-09 22:26:35 +00002569ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002570 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002571 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2572 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002573 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002574 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002575 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002576 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002577 return getTruncateExpr(V, Ty);
2578 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002579}
2580
2581/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2582/// input value to the specified type. If the type must be extended, it is sign
2583/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002584const SCEV *
2585ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002586 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002587 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002588 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2589 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002590 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002591 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002592 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002593 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002594 return getTruncateExpr(V, Ty);
2595 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002596}
2597
Dan Gohman467c4302009-05-13 03:46:30 +00002598/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2599/// input value to the specified type. If the type must be extended, it is zero
2600/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002601const SCEV *
2602ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002603 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002604 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2605 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002606 "Cannot noop or zero extend with non-integer arguments!");
2607 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2608 "getNoopOrZeroExtend cannot truncate!");
2609 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2610 return V; // No conversion
2611 return getZeroExtendExpr(V, Ty);
2612}
2613
2614/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2615/// input value to the specified type. If the type must be extended, it is sign
2616/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002617const SCEV *
2618ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002619 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002620 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2621 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002622 "Cannot noop or sign extend with non-integer arguments!");
2623 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2624 "getNoopOrSignExtend cannot truncate!");
2625 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2626 return V; // No conversion
2627 return getSignExtendExpr(V, Ty);
2628}
2629
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002630/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2631/// the input value to the specified type. If the type must be extended,
2632/// it is extended with unspecified bits. The conversion must not be
2633/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002634const SCEV *
2635ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002636 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002637 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2638 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002639 "Cannot noop or any extend with non-integer arguments!");
2640 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2641 "getNoopOrAnyExtend cannot truncate!");
2642 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2643 return V; // No conversion
2644 return getAnyExtendExpr(V, Ty);
2645}
2646
Dan Gohman467c4302009-05-13 03:46:30 +00002647/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2648/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002649const SCEV *
2650ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002651 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002652 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2653 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002654 "Cannot truncate or noop with non-integer arguments!");
2655 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2656 "getTruncateOrNoop cannot extend!");
2657 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2658 return V; // No conversion
2659 return getTruncateExpr(V, Ty);
2660}
2661
Dan Gohmana334aa72009-06-22 00:31:57 +00002662/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2663/// the types using zero-extension, and then perform a umax operation
2664/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002665const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2666 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002667 const SCEV *PromotedLHS = LHS;
2668 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002669
2670 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2671 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2672 else
2673 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2674
2675 return getUMaxExpr(PromotedLHS, PromotedRHS);
2676}
2677
Dan Gohmanc9759e82009-06-22 15:03:27 +00002678/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2679/// the types using zero-extension, and then perform a umin operation
2680/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002681const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2682 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002683 const SCEV *PromotedLHS = LHS;
2684 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002685
2686 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2687 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2688 else
2689 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2690
2691 return getUMinExpr(PromotedLHS, PromotedRHS);
2692}
2693
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002694/// PushDefUseChildren - Push users of the given Instruction
2695/// onto the given Worklist.
2696static void
2697PushDefUseChildren(Instruction *I,
2698 SmallVectorImpl<Instruction *> &Worklist) {
2699 // Push the def-use children onto the Worklist stack.
2700 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2701 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002702 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002703}
2704
2705/// ForgetSymbolicValue - This looks up computed SCEV values for all
2706/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002707/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002708/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002709void
Dan Gohman85669632010-02-25 06:57:05 +00002710ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002711 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002712 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002713
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002714 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002715 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002716 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002717 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002718 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002719
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002720 ValueExprMapType::iterator It =
2721 ValueExprMap.find(static_cast<Value *>(I));
2722 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002723 const SCEV *Old = It->second;
2724
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002725 // Short-circuit the def-use traversal if the symbolic name
2726 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002727 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002728 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002729
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002730 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002731 // structure, it's a PHI that's in the progress of being computed
2732 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2733 // additional loop trip count information isn't going to change anything.
2734 // In the second case, createNodeForPHI will perform the necessary
2735 // updates on its own when it gets to that point. In the third, we do
2736 // want to forget the SCEVUnknown.
2737 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002738 !isa<SCEVUnknown>(Old) ||
2739 (I != PN && Old == SymName)) {
Dan Gohman56a75682010-11-17 23:28:48 +00002740 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002741 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002742 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002743 }
2744
2745 PushDefUseChildren(I, Worklist);
2746 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002747}
Chris Lattner53e677a2004-04-02 20:23:17 +00002748
2749/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2750/// a loop header, making it a potential recurrence, or it doesn't.
2751///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002752const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002753 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2754 if (L->getHeader() == PN->getParent()) {
2755 // The loop may have multiple entrances or multiple exits; we can analyze
2756 // this phi as an addrec if it has a unique entry value and a unique
2757 // backedge value.
2758 Value *BEValueV = 0, *StartValueV = 0;
2759 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2760 Value *V = PN->getIncomingValue(i);
2761 if (L->contains(PN->getIncomingBlock(i))) {
2762 if (!BEValueV) {
2763 BEValueV = V;
2764 } else if (BEValueV != V) {
2765 BEValueV = 0;
2766 break;
2767 }
2768 } else if (!StartValueV) {
2769 StartValueV = V;
2770 } else if (StartValueV != V) {
2771 StartValueV = 0;
2772 break;
2773 }
2774 }
2775 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002776 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002777 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002778 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002779 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002780 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002781
2782 // Using this symbolic name for the PHI, analyze the value coming around
2783 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002784 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002785
2786 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2787 // has a special value for the first iteration of the loop.
2788
2789 // If the value coming around the backedge is an add with the symbolic
2790 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002791 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002792 // If there is a single occurrence of the symbolic value, replace it
2793 // with a recurrence.
2794 unsigned FoundIndex = Add->getNumOperands();
2795 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2796 if (Add->getOperand(i) == SymbolicName)
2797 if (FoundIndex == e) {
2798 FoundIndex = i;
2799 break;
2800 }
2801
2802 if (FoundIndex != Add->getNumOperands()) {
2803 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002804 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002805 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2806 if (i != FoundIndex)
2807 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002808 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002809
2810 // This is not a valid addrec if the step amount is varying each
2811 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002812 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002813 (isa<SCEVAddRecExpr>(Accum) &&
2814 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002815 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohmana10756e2010-01-21 02:09:26 +00002816
2817 // If the increment doesn't overflow, then neither the addrec nor
2818 // the post-increment will overflow.
2819 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2820 if (OBO->hasNoUnsignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002821 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002822 if (OBO->hasNoSignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002823 Flags = setFlags(Flags, SCEV::FlagNSW);
Andrew Trick635f7182011-03-09 17:23:39 +00002824 } else if (const GEPOperator *GEP =
Andrew Trick3228cc22011-03-14 16:50:06 +00002825 dyn_cast<GEPOperator>(BEValueV)) {
2826 // If the increment is an inbounds GEP, then we know the address
2827 // space cannot be wrapped around. We cannot make any guarantee
2828 // about signed or unsigned overflow because pointers are
2829 // unsigned but we may have a negative index from the base
2830 // pointer.
2831 if (GEP->isInBounds())
2832 // FIXME: should be SCEV::FlagNW
2833 Flags = setFlags(Flags, SCEV::FlagNSW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002834 }
2835
Dan Gohman27dead42010-04-12 07:49:36 +00002836 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick3228cc22011-03-14 16:50:06 +00002837 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002838
Dan Gohmana10756e2010-01-21 02:09:26 +00002839 // Since the no-wrap flags are on the increment, they apply to the
2840 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002841 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00002842 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick3228cc22011-03-14 16:50:06 +00002843 Accum, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002844
2845 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002846 // to be symbolic. We now need to go back and purge all of the
2847 // entries for the scalars that use the symbolic expression.
2848 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002849 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002850 return PHISCEV;
2851 }
2852 }
Dan Gohman622ed672009-05-04 22:02:23 +00002853 } else if (const SCEVAddRecExpr *AddRec =
2854 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002855 // Otherwise, this could be a loop like this:
2856 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2857 // In this case, j = {1,+,1} and BEValue is j.
2858 // Because the other in-value of i (0) fits the evolution of BEValue
2859 // i really is an addrec evolution.
2860 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002861 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002862
2863 // If StartVal = j.start - j.stride, we can use StartVal as the
2864 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002865 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002866 AddRec->getOperand(1))) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002867 // FIXME: For constant StartVal, we should be able to infer
2868 // no-wrap flags.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002869 const SCEV *PHISCEV =
Andrew Trick3228cc22011-03-14 16:50:06 +00002870 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
2871 SCEV::FlagAnyWrap);
Chris Lattner97156e72006-04-26 18:34:07 +00002872
2873 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002874 // to be symbolic. We now need to go back and purge all of the
2875 // entries for the scalars that use the symbolic expression.
2876 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002877 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002878 return PHISCEV;
2879 }
2880 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002881 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002882 }
Dan Gohman27dead42010-04-12 07:49:36 +00002883 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002884
Dan Gohman85669632010-02-25 06:57:05 +00002885 // If the PHI has a single incoming value, follow that value, unless the
2886 // PHI's incoming blocks are in a different loop, in which case doing so
2887 // risks breaking LCSSA form. Instcombine would normally zap these, but
2888 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00002889 if (Value *V = SimplifyInstruction(PN, TD, DT))
2890 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohman85669632010-02-25 06:57:05 +00002891 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002892
Chris Lattner53e677a2004-04-02 20:23:17 +00002893 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002894 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002895}
2896
Dan Gohman26466c02009-05-08 20:26:55 +00002897/// createNodeForGEP - Expand GEP instructions into add and multiply
2898/// operations. This allows them to be analyzed by regular SCEV code.
2899///
Dan Gohmand281ed22009-12-18 02:09:29 +00002900const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002901
Dan Gohmanb9f96512010-06-30 07:16:37 +00002902 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2903 // Add expression, because the Instruction may be guarded by control flow
2904 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002905 // context.
Chris Lattner8ebaf902011-02-13 03:14:49 +00002906 bool isInBounds = GEP->isInBounds();
Dan Gohman7a642572010-06-29 01:41:41 +00002907
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002908 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002909 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002910 // Don't attempt to analyze GEPs over unsized objects.
2911 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2912 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002913 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002914 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002915 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002916 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002917 I != E; ++I) {
2918 Value *Index = *I;
2919 // Compute the (potentially symbolic) offset in bytes for this index.
2920 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2921 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002922 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002923 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2924
Dan Gohmanb9f96512010-06-30 07:16:37 +00002925 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002926 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002927 } else {
2928 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002929 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2930 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002931 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002932 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2933
Dan Gohmanb9f96512010-06-30 07:16:37 +00002934 // Multiply the index by the element size to compute the element offset.
Andrew Trick3228cc22011-03-14 16:50:06 +00002935 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
2936 isInBounds ? SCEV::FlagNSW :
2937 SCEV::FlagAnyWrap);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002938
2939 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002940 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002941 }
2942 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002943
2944 // Get the SCEV for the GEP base.
2945 const SCEV *BaseS = getSCEV(Base);
2946
Dan Gohmanb9f96512010-06-30 07:16:37 +00002947 // Add the total offset from all the GEP indices to the base.
Andrew Trick3228cc22011-03-14 16:50:06 +00002948 return getAddExpr(BaseS, TotalOffset,
2949 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
Dan Gohman26466c02009-05-08 20:26:55 +00002950}
2951
Nick Lewycky83bb0052007-11-22 07:59:40 +00002952/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2953/// guaranteed to end in (at every loop iteration). It is, at the same time,
2954/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2955/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002956uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002957ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002958 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002959 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002960
Dan Gohman622ed672009-05-04 22:02:23 +00002961 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002962 return std::min(GetMinTrailingZeros(T->getOperand()),
2963 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002964
Dan Gohman622ed672009-05-04 22:02:23 +00002965 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002966 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2967 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2968 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002969 }
2970
Dan Gohman622ed672009-05-04 22:02:23 +00002971 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002972 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2973 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2974 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002975 }
2976
Dan Gohman622ed672009-05-04 22:02:23 +00002977 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002978 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002979 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002980 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002981 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002982 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002983 }
2984
Dan Gohman622ed672009-05-04 22:02:23 +00002985 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002986 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002987 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2988 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002989 for (unsigned i = 1, e = M->getNumOperands();
2990 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002991 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002992 BitWidth);
2993 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002994 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002995
Dan Gohman622ed672009-05-04 22:02:23 +00002996 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002997 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002998 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002999 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003000 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003001 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003002 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003003
Dan Gohman622ed672009-05-04 22:02:23 +00003004 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003005 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003006 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003007 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003008 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003009 return MinOpRes;
3010 }
3011
Dan Gohman622ed672009-05-04 22:02:23 +00003012 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00003013 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003014 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00003015 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003016 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00003017 return MinOpRes;
3018 }
3019
Dan Gohman2c364ad2009-06-19 23:29:04 +00003020 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3021 // For a SCEVUnknown, ask ValueTracking.
3022 unsigned BitWidth = getTypeSizeInBits(U->getType());
3023 APInt Mask = APInt::getAllOnesValue(BitWidth);
3024 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3025 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3026 return Zeros.countTrailingOnes();
3027 }
3028
3029 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00003030 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00003031}
Chris Lattner53e677a2004-04-02 20:23:17 +00003032
Dan Gohman85b05a22009-07-13 21:35:55 +00003033/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3034///
3035ConstantRange
3036ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003037 // See if we've computed this range already.
3038 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3039 if (I != UnsignedRanges.end())
3040 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003041
3042 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003043 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003044
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003045 unsigned BitWidth = getTypeSizeInBits(S->getType());
3046 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3047
3048 // If the value has known zeros, the maximum unsigned value will have those
3049 // known zeros as well.
3050 uint32_t TZ = GetMinTrailingZeros(S);
3051 if (TZ != 0)
3052 ConservativeResult =
3053 ConstantRange(APInt::getMinValue(BitWidth),
3054 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3055
Dan Gohman85b05a22009-07-13 21:35:55 +00003056 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3057 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3058 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3059 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003060 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003061 }
3062
3063 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3064 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3065 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3066 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003067 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003068 }
3069
3070 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3071 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3072 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3073 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003074 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003075 }
3076
3077 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3078 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3079 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3080 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003081 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003082 }
3083
3084 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3085 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3086 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003087 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003088 }
3089
3090 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3091 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003092 return setUnsignedRange(ZExt,
3093 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003094 }
3095
3096 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3097 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003098 return setUnsignedRange(SExt,
3099 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003100 }
3101
3102 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3103 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003104 return setUnsignedRange(Trunc,
3105 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003106 }
3107
Dan Gohman85b05a22009-07-13 21:35:55 +00003108 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003109 // If there's no unsigned wrap, the value will never be less than its
3110 // initial value.
Andrew Trick3228cc22011-03-14 16:50:06 +00003111 // FIXME: can broaden to FlagNW?
3112 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmana10756e2010-01-21 02:09:26 +00003113 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003114 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003115 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003116 ConservativeResult.intersectWith(
3117 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003118
3119 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003120 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003121 const Type *Ty = AddRec->getType();
3122 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003123 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3124 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003125 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3126
3127 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003128 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003129
3130 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003131 ConstantRange StepRange = getSignedRange(Step);
3132 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3133 ConstantRange EndRange =
3134 StartRange.add(MaxBECountRange.multiply(StepRange));
3135
3136 // Check for overflow. This must be done with ConstantRange arithmetic
3137 // because we could be called from within the ScalarEvolution overflow
3138 // checking code.
3139 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3140 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3141 ConstantRange ExtMaxBECountRange =
3142 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3143 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3144 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3145 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003146 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003147
Dan Gohman85b05a22009-07-13 21:35:55 +00003148 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3149 EndRange.getUnsignedMin());
3150 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3151 EndRange.getUnsignedMax());
3152 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003153 return setUnsignedRange(AddRec, ConservativeResult);
3154 return setUnsignedRange(AddRec,
3155 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003156 }
3157 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003158
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003159 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003160 }
3161
3162 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3163 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003164 APInt Mask = APInt::getAllOnesValue(BitWidth);
3165 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3166 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003167 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003168 return setUnsignedRange(U, ConservativeResult);
3169 return setUnsignedRange(U,
3170 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003171 }
3172
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003173 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003174}
3175
Dan Gohman85b05a22009-07-13 21:35:55 +00003176/// getSignedRange - Determine the signed range for a particular SCEV.
3177///
3178ConstantRange
3179ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohmana3bbf242011-01-24 17:54:18 +00003180 // See if we've computed this range already.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003181 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3182 if (I != SignedRanges.end())
3183 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003184
Dan Gohman85b05a22009-07-13 21:35:55 +00003185 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003186 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003187
Dan Gohman52fddd32010-01-26 04:40:18 +00003188 unsigned BitWidth = getTypeSizeInBits(S->getType());
3189 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3190
3191 // If the value has known zeros, the maximum signed value will have those
3192 // known zeros as well.
3193 uint32_t TZ = GetMinTrailingZeros(S);
3194 if (TZ != 0)
3195 ConservativeResult =
3196 ConstantRange(APInt::getSignedMinValue(BitWidth),
3197 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3198
Dan Gohman85b05a22009-07-13 21:35:55 +00003199 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3200 ConstantRange X = getSignedRange(Add->getOperand(0));
3201 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3202 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003203 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003204 }
3205
Dan Gohman85b05a22009-07-13 21:35:55 +00003206 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3207 ConstantRange X = getSignedRange(Mul->getOperand(0));
3208 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3209 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003210 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003211 }
3212
Dan Gohman85b05a22009-07-13 21:35:55 +00003213 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3214 ConstantRange X = getSignedRange(SMax->getOperand(0));
3215 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3216 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003217 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003218 }
Dan Gohman62849c02009-06-24 01:05:09 +00003219
Dan Gohman85b05a22009-07-13 21:35:55 +00003220 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3221 ConstantRange X = getSignedRange(UMax->getOperand(0));
3222 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3223 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003224 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003225 }
Dan Gohman62849c02009-06-24 01:05:09 +00003226
Dan Gohman85b05a22009-07-13 21:35:55 +00003227 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3228 ConstantRange X = getSignedRange(UDiv->getLHS());
3229 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003230 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003231 }
Dan Gohman62849c02009-06-24 01:05:09 +00003232
Dan Gohman85b05a22009-07-13 21:35:55 +00003233 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3234 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003235 return setSignedRange(ZExt,
3236 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003237 }
3238
3239 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3240 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003241 return setSignedRange(SExt,
3242 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003243 }
3244
3245 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3246 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003247 return setSignedRange(Trunc,
3248 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003249 }
3250
Dan Gohman85b05a22009-07-13 21:35:55 +00003251 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003252 // If there's no signed wrap, and all the operands have the same sign or
3253 // zero, the value won't ever change sign.
Andrew Trick3228cc22011-03-14 16:50:06 +00003254 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003255 bool AllNonNeg = true;
3256 bool AllNonPos = true;
3257 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3258 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3259 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3260 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003261 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003262 ConservativeResult = ConservativeResult.intersectWith(
3263 ConstantRange(APInt(BitWidth, 0),
3264 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003265 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003266 ConservativeResult = ConservativeResult.intersectWith(
3267 ConstantRange(APInt::getSignedMinValue(BitWidth),
3268 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003269 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003270
3271 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003272 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003273 const Type *Ty = AddRec->getType();
3274 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003275 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3276 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003277 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3278
3279 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003280 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003281
3282 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003283 ConstantRange StepRange = getSignedRange(Step);
3284 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3285 ConstantRange EndRange =
3286 StartRange.add(MaxBECountRange.multiply(StepRange));
3287
3288 // Check for overflow. This must be done with ConstantRange arithmetic
3289 // because we could be called from within the ScalarEvolution overflow
3290 // checking code.
3291 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3292 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3293 ConstantRange ExtMaxBECountRange =
3294 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3295 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3296 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3297 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003298 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003299
Dan Gohman85b05a22009-07-13 21:35:55 +00003300 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3301 EndRange.getSignedMin());
3302 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3303 EndRange.getSignedMax());
3304 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003305 return setSignedRange(AddRec, ConservativeResult);
3306 return setSignedRange(AddRec,
3307 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003308 }
Dan Gohman62849c02009-06-24 01:05:09 +00003309 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003310
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003311 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003312 }
3313
Dan Gohman2c364ad2009-06-19 23:29:04 +00003314 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3315 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003316 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003317 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003318 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3319 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003320 return setSignedRange(U, ConservativeResult);
3321 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003322 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003323 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003324 }
3325
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003326 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003327}
3328
Chris Lattner53e677a2004-04-02 20:23:17 +00003329/// createSCEV - We know that there is no SCEV for the specified value.
3330/// Analyze the expression.
3331///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003332const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003333 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003334 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003335
Dan Gohman6c459a22008-06-22 19:56:46 +00003336 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003337 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003338 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003339
3340 // Don't attempt to analyze instructions in blocks that aren't
3341 // reachable. Such instructions don't matter, and they aren't required
3342 // to obey basic rules for definitions dominating uses which this
3343 // analysis depends on.
3344 if (!DT->isReachableFromEntry(I->getParent()))
3345 return getUnknown(V);
3346 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003347 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003348 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3349 return getConstant(CI);
3350 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003351 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003352 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3353 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003354 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003355 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003356
Dan Gohmanca178902009-07-17 20:47:02 +00003357 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003358 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003359 case Instruction::Add: {
3360 // The simple thing to do would be to just call getSCEV on both operands
3361 // and call getAddExpr with the result. However if we're looking at a
3362 // bunch of things all added together, this can be quite inefficient,
3363 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3364 // Instead, gather up all the operands and make a single getAddExpr call.
3365 // LLVM IR canonical form means we need only traverse the left operands.
3366 SmallVector<const SCEV *, 4> AddOps;
3367 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003368 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3369 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3370 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3371 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003372 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003373 const SCEV *Op1 = getSCEV(U->getOperand(1));
3374 if (Opcode == Instruction::Sub)
3375 AddOps.push_back(getNegativeSCEV(Op1));
3376 else
3377 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003378 }
3379 AddOps.push_back(getSCEV(U->getOperand(0)));
3380 return getAddExpr(AddOps);
3381 }
3382 case Instruction::Mul: {
3383 // See the Add code above.
3384 SmallVector<const SCEV *, 4> MulOps;
3385 MulOps.push_back(getSCEV(U->getOperand(1)));
3386 for (Value *Op = U->getOperand(0);
Andrew Trick635f7182011-03-09 17:23:39 +00003387 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003388 Op = U->getOperand(0)) {
3389 U = cast<Operator>(Op);
3390 MulOps.push_back(getSCEV(U->getOperand(1)));
3391 }
3392 MulOps.push_back(getSCEV(U->getOperand(0)));
3393 return getMulExpr(MulOps);
3394 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003395 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003396 return getUDivExpr(getSCEV(U->getOperand(0)),
3397 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003398 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003399 return getMinusSCEV(getSCEV(U->getOperand(0)),
3400 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003401 case Instruction::And:
3402 // For an expression like x&255 that merely masks off the high bits,
3403 // use zext(trunc(x)) as the SCEV expression.
3404 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003405 if (CI->isNullValue())
3406 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003407 if (CI->isAllOnesValue())
3408 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003409 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003410
3411 // Instcombine's ShrinkDemandedConstant may strip bits out of
3412 // constants, obscuring what would otherwise be a low-bits mask.
3413 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3414 // knew about to reconstruct a low-bits mask value.
3415 unsigned LZ = A.countLeadingZeros();
3416 unsigned BitWidth = A.getBitWidth();
3417 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3418 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3419 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3420
3421 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3422
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003423 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003424 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003425 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003426 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003427 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003428 }
3429 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003430
Dan Gohman6c459a22008-06-22 19:56:46 +00003431 case Instruction::Or:
3432 // If the RHS of the Or is a constant, we may have something like:
3433 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3434 // optimizations will transparently handle this case.
3435 //
3436 // In order for this transformation to be safe, the LHS must be of the
3437 // form X*(2^n) and the Or constant must be less than 2^n.
3438 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003439 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003440 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003441 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003442 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3443 // Build a plain add SCEV.
3444 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3445 // If the LHS of the add was an addrec and it has no-wrap flags,
3446 // transfer the no-wrap flags, since an or won't introduce a wrap.
3447 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3448 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick3228cc22011-03-14 16:50:06 +00003449 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3450 OldAR->getNoWrapFlags());
Dan Gohman1f96e672009-09-17 18:05:20 +00003451 }
3452 return S;
3453 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003454 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003455 break;
3456 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003457 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003458 // If the RHS of the xor is a signbit, then this is just an add.
3459 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003460 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003461 return getAddExpr(getSCEV(U->getOperand(0)),
3462 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003463
3464 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003465 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003466 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003467
3468 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3469 // This is a variant of the check for xor with -1, and it handles
3470 // the case where instcombine has trimmed non-demanded bits out
3471 // of an xor with -1.
3472 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3473 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3474 if (BO->getOpcode() == Instruction::And &&
3475 LCI->getValue() == CI->getValue())
3476 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003477 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003478 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003479 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003480 const Type *Z0Ty = Z0->getType();
3481 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3482
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003483 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003484 // mask off the high bits. Complement the operand and
3485 // re-apply the zext.
3486 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3487 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3488
3489 // If C is a single bit, it may be in the sign-bit position
3490 // before the zero-extend. In this case, represent the xor
3491 // using an add, which is equivalent, and re-apply the zext.
Jay Foad40f8f622010-12-07 08:25:19 +00003492 APInt Trunc = CI->getValue().trunc(Z0TySize);
3493 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohman82052832009-06-18 00:00:20 +00003494 Trunc.isSignBit())
3495 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3496 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003497 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003498 }
3499 break;
3500
3501 case Instruction::Shl:
3502 // Turn shift left of a constant amount into a multiply.
3503 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003504 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003505
3506 // If the shift count is not less than the bitwidth, the result of
3507 // the shift is undefined. Don't try to analyze it, because the
3508 // resolution chosen here may differ from the resolution chosen in
3509 // other parts of the compiler.
3510 if (SA->getValue().uge(BitWidth))
3511 break;
3512
Owen Andersoneed707b2009-07-24 23:12:02 +00003513 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003514 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003515 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003516 }
3517 break;
3518
Nick Lewycky01eaf802008-07-07 06:15:49 +00003519 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003520 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003521 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003522 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003523
3524 // If the shift count is not less than the bitwidth, the result of
3525 // the shift is undefined. Don't try to analyze it, because the
3526 // resolution chosen here may differ from the resolution chosen in
3527 // other parts of the compiler.
3528 if (SA->getValue().uge(BitWidth))
3529 break;
3530
Owen Andersoneed707b2009-07-24 23:12:02 +00003531 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003532 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003533 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003534 }
3535 break;
3536
Dan Gohman4ee29af2009-04-21 02:26:00 +00003537 case Instruction::AShr:
3538 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3539 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003540 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003541 if (L->getOpcode() == Instruction::Shl &&
3542 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003543 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3544
3545 // If the shift count is not less than the bitwidth, the result of
3546 // the shift is undefined. Don't try to analyze it, because the
3547 // resolution chosen here may differ from the resolution chosen in
3548 // other parts of the compiler.
3549 if (CI->getValue().uge(BitWidth))
3550 break;
3551
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003552 uint64_t Amt = BitWidth - CI->getZExtValue();
3553 if (Amt == BitWidth)
3554 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003555 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003556 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003557 IntegerType::get(getContext(),
3558 Amt)),
3559 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003560 }
3561 break;
3562
Dan Gohman6c459a22008-06-22 19:56:46 +00003563 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003564 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003565
3566 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003567 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003568
3569 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003570 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003571
3572 case Instruction::BitCast:
3573 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003574 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003575 return getSCEV(U->getOperand(0));
3576 break;
3577
Dan Gohman4f8eea82010-02-01 18:27:38 +00003578 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3579 // lead to pointer expressions which cannot safely be expanded to GEPs,
3580 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3581 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003582
Dan Gohman26466c02009-05-08 20:26:55 +00003583 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003584 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003585
Dan Gohman6c459a22008-06-22 19:56:46 +00003586 case Instruction::PHI:
3587 return createNodeForPHI(cast<PHINode>(U));
3588
3589 case Instruction::Select:
3590 // This could be a smax or umax that was lowered earlier.
3591 // Try to recover it.
3592 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3593 Value *LHS = ICI->getOperand(0);
3594 Value *RHS = ICI->getOperand(1);
3595 switch (ICI->getPredicate()) {
3596 case ICmpInst::ICMP_SLT:
3597 case ICmpInst::ICMP_SLE:
3598 std::swap(LHS, RHS);
3599 // fall through
3600 case ICmpInst::ICMP_SGT:
3601 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003602 // a >s b ? a+x : b+x -> smax(a, b)+x
3603 // a >s b ? b+x : a+x -> smin(a, b)+x
3604 if (LHS->getType() == U->getType()) {
3605 const SCEV *LS = getSCEV(LHS);
3606 const SCEV *RS = getSCEV(RHS);
3607 const SCEV *LA = getSCEV(U->getOperand(1));
3608 const SCEV *RA = getSCEV(U->getOperand(2));
3609 const SCEV *LDiff = getMinusSCEV(LA, LS);
3610 const SCEV *RDiff = getMinusSCEV(RA, RS);
3611 if (LDiff == RDiff)
3612 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3613 LDiff = getMinusSCEV(LA, RS);
3614 RDiff = getMinusSCEV(RA, LS);
3615 if (LDiff == RDiff)
3616 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3617 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003618 break;
3619 case ICmpInst::ICMP_ULT:
3620 case ICmpInst::ICMP_ULE:
3621 std::swap(LHS, RHS);
3622 // fall through
3623 case ICmpInst::ICMP_UGT:
3624 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003625 // a >u b ? a+x : b+x -> umax(a, b)+x
3626 // a >u b ? b+x : a+x -> umin(a, b)+x
3627 if (LHS->getType() == U->getType()) {
3628 const SCEV *LS = getSCEV(LHS);
3629 const SCEV *RS = getSCEV(RHS);
3630 const SCEV *LA = getSCEV(U->getOperand(1));
3631 const SCEV *RA = getSCEV(U->getOperand(2));
3632 const SCEV *LDiff = getMinusSCEV(LA, LS);
3633 const SCEV *RDiff = getMinusSCEV(RA, RS);
3634 if (LDiff == RDiff)
3635 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3636 LDiff = getMinusSCEV(LA, RS);
3637 RDiff = getMinusSCEV(RA, LS);
3638 if (LDiff == RDiff)
3639 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3640 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003641 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003642 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003643 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3644 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003645 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003646 cast<ConstantInt>(RHS)->isZero()) {
3647 const SCEV *One = getConstant(LHS->getType(), 1);
3648 const SCEV *LS = getSCEV(LHS);
3649 const SCEV *LA = getSCEV(U->getOperand(1));
3650 const SCEV *RA = getSCEV(U->getOperand(2));
3651 const SCEV *LDiff = getMinusSCEV(LA, LS);
3652 const SCEV *RDiff = getMinusSCEV(RA, One);
3653 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003654 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003655 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003656 break;
3657 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003658 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3659 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003660 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003661 cast<ConstantInt>(RHS)->isZero()) {
3662 const SCEV *One = getConstant(LHS->getType(), 1);
3663 const SCEV *LS = getSCEV(LHS);
3664 const SCEV *LA = getSCEV(U->getOperand(1));
3665 const SCEV *RA = getSCEV(U->getOperand(2));
3666 const SCEV *LDiff = getMinusSCEV(LA, One);
3667 const SCEV *RDiff = getMinusSCEV(RA, LS);
3668 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003669 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003670 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003671 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003672 default:
3673 break;
3674 }
3675 }
3676
3677 default: // We cannot analyze this expression.
3678 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003679 }
3680
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003681 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003682}
3683
3684
3685
3686//===----------------------------------------------------------------------===//
3687// Iteration Count Computation Code
3688//
3689
Dan Gohman46bdfb02009-02-24 18:55:53 +00003690/// getBackedgeTakenCount - If the specified loop has a predictable
3691/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3692/// object. The backedge-taken count is the number of times the loop header
3693/// will be branched to from within the loop. This is one less than the
3694/// trip count of the loop, since it doesn't count the first iteration,
3695/// when the header is branched to from outside the loop.
3696///
3697/// Note that it is not valid to call this method on a loop without a
3698/// loop-invariant backedge-taken count (see
3699/// hasLoopInvariantBackedgeTakenCount).
3700///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003701const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003702 return getBackedgeTakenInfo(L).Exact;
3703}
3704
3705/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3706/// return the least SCEV value that is known never to be less than the
3707/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003708const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003709 return getBackedgeTakenInfo(L).Max;
3710}
3711
Dan Gohman59ae6b92009-07-08 19:23:34 +00003712/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3713/// onto the given Worklist.
3714static void
3715PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3716 BasicBlock *Header = L->getHeader();
3717
3718 // Push all Loop-header PHIs onto the Worklist stack.
3719 for (BasicBlock::iterator I = Header->begin();
3720 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3721 Worklist.push_back(PN);
3722}
3723
Dan Gohmana1af7572009-04-30 20:47:05 +00003724const ScalarEvolution::BackedgeTakenInfo &
3725ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003726 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003727 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003728 // update the value. The temporary CouldNotCompute value tells SCEV
3729 // code elsewhere that it shouldn't attempt to request a new
3730 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003731 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003732 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
Chris Lattnerf1859892011-01-09 02:16:18 +00003733 if (!Pair.second)
3734 return Pair.first->second;
Dan Gohman01ecca22009-04-27 20:16:15 +00003735
Chris Lattnerf1859892011-01-09 02:16:18 +00003736 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3737 if (BECount.Exact != getCouldNotCompute()) {
3738 assert(isLoopInvariant(BECount.Exact, L) &&
3739 isLoopInvariant(BECount.Max, L) &&
3740 "Computed backedge-taken count isn't loop invariant for loop!");
3741 ++NumTripCountsComputed;
3742
3743 // Update the value in the map.
3744 Pair.first->second = BECount;
3745 } else {
3746 if (BECount.Max != getCouldNotCompute())
Dan Gohman01ecca22009-04-27 20:16:15 +00003747 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003748 Pair.first->second = BECount;
Chris Lattnerf1859892011-01-09 02:16:18 +00003749 if (isa<PHINode>(L->getHeader()->begin()))
3750 // Only count loops that have phi nodes as not being computable.
3751 ++NumTripCountsNotComputed;
3752 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003753
Chris Lattnerf1859892011-01-09 02:16:18 +00003754 // Now that we know more about the trip count for this loop, forget any
3755 // existing SCEV values for PHI nodes in this loop since they are only
3756 // conservative estimates made without the benefit of trip count
3757 // information. This is similar to the code in forgetLoop, except that
3758 // it handles SCEVUnknown PHI nodes specially.
3759 if (BECount.hasAnyInfo()) {
3760 SmallVector<Instruction *, 16> Worklist;
3761 PushLoopPHIs(L, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003762
Chris Lattnerf1859892011-01-09 02:16:18 +00003763 SmallPtrSet<Instruction *, 8> Visited;
3764 while (!Worklist.empty()) {
3765 Instruction *I = Worklist.pop_back_val();
3766 if (!Visited.insert(I)) continue;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003767
Chris Lattnerf1859892011-01-09 02:16:18 +00003768 ValueExprMapType::iterator It =
3769 ValueExprMap.find(static_cast<Value *>(I));
3770 if (It != ValueExprMap.end()) {
3771 const SCEV *Old = It->second;
Dan Gohman6678e7b2010-11-17 02:44:44 +00003772
Chris Lattnerf1859892011-01-09 02:16:18 +00003773 // SCEVUnknown for a PHI either means that it has an unrecognized
3774 // structure, or it's a PHI that's in the progress of being computed
3775 // by createNodeForPHI. In the former case, additional loop trip
3776 // count information isn't going to change anything. In the later
3777 // case, createNodeForPHI will perform the necessary updates on its
3778 // own when it gets to that point.
3779 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3780 forgetMemoizedResults(Old);
3781 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003782 }
Chris Lattnerf1859892011-01-09 02:16:18 +00003783 if (PHINode *PN = dyn_cast<PHINode>(I))
3784 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003785 }
Chris Lattnerf1859892011-01-09 02:16:18 +00003786
3787 PushDefUseChildren(I, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003788 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003789 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003790 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003791}
3792
Dan Gohman4c7279a2009-10-31 15:04:55 +00003793/// forgetLoop - This method should be called by the client when it has
3794/// changed a loop in a way that may effect ScalarEvolution's ability to
3795/// compute a trip count, or if the loop is deleted.
3796void ScalarEvolution::forgetLoop(const Loop *L) {
3797 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003798 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003799
Dan Gohman4c7279a2009-10-31 15:04:55 +00003800 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003801 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003802 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003803
Dan Gohman59ae6b92009-07-08 19:23:34 +00003804 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003805 while (!Worklist.empty()) {
3806 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003807 if (!Visited.insert(I)) continue;
3808
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003809 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3810 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003811 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003812 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003813 if (PHINode *PN = dyn_cast<PHINode>(I))
3814 ConstantEvolutionLoopExitValue.erase(PN);
3815 }
3816
3817 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003818 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00003819
3820 // Forget all contained loops too, to avoid dangling entries in the
3821 // ValuesAtScopes map.
3822 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3823 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00003824}
3825
Eric Christophere6cbfa62010-07-29 01:25:38 +00003826/// forgetValue - This method should be called by the client when it has
3827/// changed a value in a way that may effect its value, or which may
3828/// disconnect it from a def-use chain linking it to a loop.
3829void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003830 Instruction *I = dyn_cast<Instruction>(V);
3831 if (!I) return;
3832
3833 // Drop information about expressions based on loop-header PHIs.
3834 SmallVector<Instruction *, 16> Worklist;
3835 Worklist.push_back(I);
3836
3837 SmallPtrSet<Instruction *, 8> Visited;
3838 while (!Worklist.empty()) {
3839 I = Worklist.pop_back_val();
3840 if (!Visited.insert(I)) continue;
3841
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003842 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3843 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003844 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003845 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003846 if (PHINode *PN = dyn_cast<PHINode>(I))
3847 ConstantEvolutionLoopExitValue.erase(PN);
3848 }
3849
3850 PushDefUseChildren(I, Worklist);
3851 }
3852}
3853
Dan Gohman46bdfb02009-02-24 18:55:53 +00003854/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3855/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003856ScalarEvolution::BackedgeTakenInfo
3857ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003858 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003859 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003860
Dan Gohmana334aa72009-06-22 00:31:57 +00003861 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003862 const SCEV *BECount = getCouldNotCompute();
3863 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003864 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003865 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3866 BackedgeTakenInfo NewBTI =
3867 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003868
Dan Gohman1c343752009-06-27 21:21:31 +00003869 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003870 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003871 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003872 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003873 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003874 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003875 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003876 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003877 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003878 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003879 }
Dan Gohman1c343752009-06-27 21:21:31 +00003880 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003881 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003882 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003883 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003884 }
3885
3886 return BackedgeTakenInfo(BECount, MaxBECount);
3887}
3888
3889/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3890/// of the specified loop will execute if it exits via the specified block.
3891ScalarEvolution::BackedgeTakenInfo
3892ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3893 BasicBlock *ExitingBlock) {
3894
3895 // Okay, we've chosen an exiting block. See what condition causes us to
3896 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003897 //
3898 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003899 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003900 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003901 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003902
Chris Lattner8b0e3602007-01-07 02:24:26 +00003903 // At this point, we know we have a conditional branch that determines whether
3904 // the loop is exited. However, we don't know if the branch is executed each
3905 // time through the loop. If not, then the execution count of the branch will
3906 // not be equal to the trip count of the loop.
3907 //
3908 // Currently we check for this by checking to see if the Exit branch goes to
3909 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003910 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003911 // loop header. This is common for un-rotated loops.
3912 //
3913 // If both of those tests fail, walk up the unique predecessor chain to the
3914 // header, stopping if there is an edge that doesn't exit the loop. If the
3915 // header is reached, the execution count of the branch will be equal to the
3916 // trip count of the loop.
3917 //
3918 // More extensive analysis could be done to handle more cases here.
3919 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003920 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003921 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003922 ExitBr->getParent() != L->getHeader()) {
3923 // The simple checks failed, try climbing the unique predecessor chain
3924 // up to the header.
3925 bool Ok = false;
3926 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3927 BasicBlock *Pred = BB->getUniquePredecessor();
3928 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003929 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003930 TerminatorInst *PredTerm = Pred->getTerminator();
3931 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3932 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3933 if (PredSucc == BB)
3934 continue;
3935 // If the predecessor has a successor that isn't BB and isn't
3936 // outside the loop, assume the worst.
3937 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003938 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003939 }
3940 if (Pred == L->getHeader()) {
3941 Ok = true;
3942 break;
3943 }
3944 BB = Pred;
3945 }
3946 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003947 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003948 }
3949
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003950 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003951 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3952 ExitBr->getSuccessor(0),
3953 ExitBr->getSuccessor(1));
3954}
3955
3956/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3957/// backedge of the specified loop will execute if its exit condition
3958/// were a conditional branch of ExitCond, TBB, and FBB.
3959ScalarEvolution::BackedgeTakenInfo
3960ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3961 Value *ExitCond,
3962 BasicBlock *TBB,
3963 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003964 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003965 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3966 if (BO->getOpcode() == Instruction::And) {
3967 // Recurse on the operands of the and.
3968 BackedgeTakenInfo BTI0 =
3969 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3970 BackedgeTakenInfo BTI1 =
3971 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003972 const SCEV *BECount = getCouldNotCompute();
3973 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003974 if (L->contains(TBB)) {
3975 // Both conditions must be true for the loop to continue executing.
3976 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003977 if (BTI0.Exact == getCouldNotCompute() ||
3978 BTI1.Exact == getCouldNotCompute())
3979 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003980 else
3981 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003982 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003983 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003984 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003985 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003986 else
3987 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003988 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003989 // Both conditions must be true at the same time for the loop to exit.
3990 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003991 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003992 if (BTI0.Max == BTI1.Max)
3993 MaxBECount = BTI0.Max;
3994 if (BTI0.Exact == BTI1.Exact)
3995 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003996 }
3997
3998 return BackedgeTakenInfo(BECount, MaxBECount);
3999 }
4000 if (BO->getOpcode() == Instruction::Or) {
4001 // Recurse on the operands of the or.
4002 BackedgeTakenInfo BTI0 =
4003 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
4004 BackedgeTakenInfo BTI1 =
4005 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004006 const SCEV *BECount = getCouldNotCompute();
4007 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004008 if (L->contains(FBB)) {
4009 // Both conditions must be false for the loop to continue executing.
4010 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00004011 if (BTI0.Exact == getCouldNotCompute() ||
4012 BTI1.Exact == getCouldNotCompute())
4013 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004014 else
4015 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00004016 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004017 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00004018 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004019 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004020 else
4021 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004022 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004023 // Both conditions must be false at the same time for the loop to exit.
4024 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004025 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00004026 if (BTI0.Max == BTI1.Max)
4027 MaxBECount = BTI0.Max;
4028 if (BTI0.Exact == BTI1.Exact)
4029 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004030 }
4031
4032 return BackedgeTakenInfo(BECount, MaxBECount);
4033 }
4034 }
4035
4036 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004037 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00004038 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4039 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004040
Dan Gohman00cb5b72010-02-19 18:12:07 +00004041 // Check for a constant condition. These are normally stripped out by
4042 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4043 // preserve the CFG and is temporarily leaving constant conditions
4044 // in place.
4045 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4046 if (L->contains(FBB) == !CI->getZExtValue())
4047 // The backedge is always taken.
4048 return getCouldNotCompute();
4049 else
4050 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00004051 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00004052 }
4053
Eli Friedman361e54d2009-05-09 12:32:42 +00004054 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00004055 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4056}
4057
Chris Lattner992efb02011-01-09 22:26:35 +00004058static const SCEVAddRecExpr *
4059isSimpleUnwrappingAddRec(const SCEV *S, const Loop *L) {
4060 const SCEVAddRecExpr *SA = dyn_cast<SCEVAddRecExpr>(S);
Andrew Trick635f7182011-03-09 17:23:39 +00004061
Chris Lattner992efb02011-01-09 22:26:35 +00004062 // The SCEV must be an addrec of this loop.
4063 if (!SA || SA->getLoop() != L || !SA->isAffine())
4064 return 0;
Andrew Trick635f7182011-03-09 17:23:39 +00004065
Chris Lattner992efb02011-01-09 22:26:35 +00004066 // The SCEV must be known to not wrap in some way to be interesting.
Andrew Trick3228cc22011-03-14 16:50:06 +00004067 if (!SA->getNoWrapFlags(SCEV::FlagNW))
Chris Lattner992efb02011-01-09 22:26:35 +00004068 return 0;
4069
4070 // The stride must be a constant so that we know if it is striding up or down.
4071 if (!isa<SCEVConstant>(SA->getOperand(1)))
4072 return 0;
4073 return SA;
4074}
4075
4076/// getMinusSCEVForExitTest - When considering an exit test for a loop with a
4077/// "x != y" exit test, we turn this into a computation that evaluates x-y != 0,
4078/// and this function returns the expression to use for x-y. We know and take
4079/// advantage of the fact that this subtraction is only being used in a
4080/// comparison by zero context.
4081///
Andrew Trick3228cc22011-03-14 16:50:06 +00004082/// FIXME: this can be completely removed once AddRec FlagNWs are propagated.
Chris Lattner992efb02011-01-09 22:26:35 +00004083static const SCEV *getMinusSCEVForExitTest(const SCEV *LHS, const SCEV *RHS,
4084 const Loop *L, ScalarEvolution &SE) {
4085 // If either LHS or RHS is an AddRec SCEV (of this loop) that is known to not
Andrew Trick3228cc22011-03-14 16:50:06 +00004086 // self-wrap, then we know that the value will either become the other one
4087 // (and thus the loop terminates), that the loop will terminate through some
4088 // other exit condition first, or that the loop has undefined behavior. This
4089 // information is useful when the addrec has a stride that is != 1 or -1,
4090 // because it means we can't "miss" the exit value.
Chris Lattner992efb02011-01-09 22:26:35 +00004091 //
4092 // In any of these three cases, it is safe to turn the exit condition into a
4093 // "counting down" AddRec (to zero) by subtracting the two inputs as normal,
4094 // but since we know that the "end cannot be missed" we can force the
4095 // resulting AddRec to be a NUW addrec. Since it is counting down, this means
4096 // that the AddRec *cannot* pass zero.
4097
4098 // See if LHS and RHS are addrec's we can handle.
4099 const SCEVAddRecExpr *LHSA = isSimpleUnwrappingAddRec(LHS, L);
4100 const SCEVAddRecExpr *RHSA = isSimpleUnwrappingAddRec(RHS, L);
Andrew Trick635f7182011-03-09 17:23:39 +00004101
Chris Lattner992efb02011-01-09 22:26:35 +00004102 // If neither addrec is interesting, just return a minus.
4103 if (RHSA == 0 && LHSA == 0)
4104 return SE.getMinusSCEV(LHS, RHS);
Andrew Trick635f7182011-03-09 17:23:39 +00004105
Chris Lattner992efb02011-01-09 22:26:35 +00004106 // If only one of LHS and RHS are an AddRec of this loop, make sure it is LHS.
4107 if (RHSA && LHSA == 0) {
4108 // Safe because a-b === b-a for comparisons against zero.
4109 std::swap(LHS, RHS);
4110 std::swap(LHSA, RHSA);
4111 }
Andrew Trick635f7182011-03-09 17:23:39 +00004112
Chris Lattner992efb02011-01-09 22:26:35 +00004113 // Handle the case when only one is advancing in a non-overflowing way.
4114 if (RHSA == 0) {
4115 // If RHS is loop varying, then we can't predict when LHS will cross it.
4116 if (!SE.isLoopInvariant(RHS, L))
4117 return SE.getMinusSCEV(LHS, RHS);
Andrew Trick635f7182011-03-09 17:23:39 +00004118
Chris Lattner992efb02011-01-09 22:26:35 +00004119 // If LHS has a positive stride, then we compute RHS-LHS, because the loop
4120 // is counting up until it crosses RHS (which must be larger than LHS). If
4121 // it is negative, we compute LHS-RHS because we're counting down to RHS.
4122 const ConstantInt *Stride =
4123 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4124 if (Stride->getValue().isNegative())
4125 std::swap(LHS, RHS);
4126
Andrew Trick3228cc22011-03-14 16:50:06 +00004127 return SE.getMinusSCEV(RHS, LHS, SCEV::FlagNUW);
Chris Lattner992efb02011-01-09 22:26:35 +00004128 }
Andrew Trick635f7182011-03-09 17:23:39 +00004129
Chris Lattner992efb02011-01-09 22:26:35 +00004130 // If both LHS and RHS are interesting, we have something like:
4131 // a+i*4 != b+i*8.
4132 const ConstantInt *LHSStride =
4133 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4134 const ConstantInt *RHSStride =
4135 cast<SCEVConstant>(RHSA->getOperand(1))->getValue();
Andrew Trick635f7182011-03-09 17:23:39 +00004136
Chris Lattner992efb02011-01-09 22:26:35 +00004137 // If the strides are equal, then this is just a (complex) loop invariant
Chris Lattner6038a632011-01-11 17:11:59 +00004138 // comparison of a and b.
Chris Lattner992efb02011-01-09 22:26:35 +00004139 if (LHSStride == RHSStride)
4140 return SE.getMinusSCEV(LHSA->getStart(), RHSA->getStart());
Andrew Trick635f7182011-03-09 17:23:39 +00004141
Chris Lattner992efb02011-01-09 22:26:35 +00004142 // If the signs of the strides differ, then the negative stride is counting
4143 // down to the positive stride.
4144 if (LHSStride->getValue().isNegative() != RHSStride->getValue().isNegative()){
4145 if (RHSStride->getValue().isNegative())
4146 std::swap(LHS, RHS);
4147 } else {
4148 // If LHS's stride is smaller than RHS's stride, then "b" must be less than
4149 // "a" and "b" is RHS is counting up (catching up) to LHS. This is true
4150 // whether the strides are positive or negative.
4151 if (RHSStride->getValue().slt(LHSStride->getValue()))
4152 std::swap(LHS, RHS);
4153 }
Andrew Trick635f7182011-03-09 17:23:39 +00004154
Andrew Trick3228cc22011-03-14 16:50:06 +00004155 return SE.getMinusSCEV(LHS, RHS, SCEV::FlagNUW);
Chris Lattner992efb02011-01-09 22:26:35 +00004156}
4157
Dan Gohmana334aa72009-06-22 00:31:57 +00004158/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
4159/// backedge of the specified loop will execute if its exit condition
4160/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4161ScalarEvolution::BackedgeTakenInfo
4162ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
4163 ICmpInst *ExitCond,
4164 BasicBlock *TBB,
4165 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004166
Reid Spencere4d87aa2006-12-23 06:05:41 +00004167 // If the condition was exit on true, convert the condition to exit on false
4168 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00004169 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004170 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004171 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004172 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004173
4174 // Handle common loops like: for (X = "string"; *X; ++X)
4175 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4176 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004177 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004178 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004179 if (ItCnt.hasAnyInfo())
4180 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00004181 }
4182
Dan Gohman0bba49c2009-07-07 17:06:11 +00004183 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4184 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00004185
4186 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00004187 LHS = getSCEVAtScope(LHS, L);
4188 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004189
Dan Gohman64a845e2009-06-24 04:48:43 +00004190 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004191 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00004192 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004193 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004194 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004196 }
4197
Dan Gohman03557dc2010-05-03 16:35:17 +00004198 // Simplify the operands before analyzing them.
4199 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4200
Chris Lattner53e677a2004-04-02 20:23:17 +00004201 // If we have a comparison of a chrec against a constant, try to use value
4202 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004203 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4204 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004205 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004206 // Form the constant range.
4207 ConstantRange CompRange(
4208 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004209
Dan Gohman0bba49c2009-07-07 17:06:11 +00004210 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004211 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004212 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004213
Chris Lattner53e677a2004-04-02 20:23:17 +00004214 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004215 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004216 // Convert to: while (X-Y != 0)
Andrew Trick3228cc22011-03-14 16:50:06 +00004217 // FIXME: Once AddRec FlagNW are propagated, should be:
4218 // BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Chris Lattner992efb02011-01-09 22:26:35 +00004219 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEVForExitTest(LHS, RHS, L,
4220 *this), L);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004221 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004222 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004223 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004224 case ICmpInst::ICMP_EQ: { // while (X == Y)
4225 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004226 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4227 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004228 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004229 }
4230 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004231 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4232 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004233 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004234 }
4235 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004236 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4237 getNotSCEV(RHS), L, true);
4238 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004239 break;
4240 }
4241 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004242 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4243 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004244 break;
4245 }
4246 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004247 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4248 getNotSCEV(RHS), L, false);
4249 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004250 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004251 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004252 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004253#if 0
David Greene25e0e872009-12-23 22:18:14 +00004254 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004255 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004256 dbgs() << "[unsigned] ";
4257 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004258 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004260#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004261 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004262 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004263 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004264 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004265}
4266
Chris Lattner673e02b2004-10-12 01:49:27 +00004267static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004268EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4269 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004270 const SCEV *InVal = SE.getConstant(C);
4271 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004272 assert(isa<SCEVConstant>(Val) &&
4273 "Evaluation of SCEV at constant didn't fold correctly?");
4274 return cast<SCEVConstant>(Val)->getValue();
4275}
4276
4277/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4278/// and a GEP expression (missing the pointer index) indexing into it, return
4279/// the addressed element of the initializer or null if the index expression is
4280/// invalid.
4281static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004282GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004283 const std::vector<ConstantInt*> &Indices) {
4284 Constant *Init = GV->getInitializer();
4285 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004286 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004287 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4288 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4289 Init = cast<Constant>(CS->getOperand(Idx));
4290 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4291 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4292 Init = cast<Constant>(CA->getOperand(Idx));
4293 } else if (isa<ConstantAggregateZero>(Init)) {
4294 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4295 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004296 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004297 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4298 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004299 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004300 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004301 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004302 }
4303 return 0;
4304 } else {
4305 return 0; // Unknown initializer type
4306 }
4307 }
4308 return Init;
4309}
4310
Dan Gohman46bdfb02009-02-24 18:55:53 +00004311/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4312/// 'icmp op load X, cst', try to see if we can compute the backedge
4313/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004314ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004315ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4316 LoadInst *LI,
4317 Constant *RHS,
4318 const Loop *L,
4319 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004320 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004321
4322 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004323 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004324 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004325 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004326
4327 // Make sure that it is really a constant global we are gepping, with an
4328 // initializer, and make sure the first IDX is really 0.
4329 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004330 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004331 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4332 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004333 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004334
4335 // Okay, we allow one non-constant index into the GEP instruction.
4336 Value *VarIdx = 0;
4337 std::vector<ConstantInt*> Indexes;
4338 unsigned VarIdxNum = 0;
4339 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4340 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4341 Indexes.push_back(CI);
4342 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004343 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004344 VarIdx = GEP->getOperand(i);
4345 VarIdxNum = i-2;
4346 Indexes.push_back(0);
4347 }
4348
4349 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4350 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004351 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004352 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004353
4354 // We can only recognize very limited forms of loop index expressions, in
4355 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004356 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004357 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004358 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4359 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004360 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004361
4362 unsigned MaxSteps = MaxBruteForceIterations;
4363 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004364 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004365 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004366 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004367
4368 // Form the GEP offset.
4369 Indexes[VarIdxNum] = Val;
4370
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004371 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004372 if (Result == 0) break; // Cannot compute!
4373
4374 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004375 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004376 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004377 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004378#if 0
David Greene25e0e872009-12-23 22:18:14 +00004379 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004380 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4381 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004382#endif
4383 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004384 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004385 }
4386 }
Dan Gohman1c343752009-06-27 21:21:31 +00004387 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004388}
4389
4390
Chris Lattner3221ad02004-04-17 22:58:41 +00004391/// CanConstantFold - Return true if we can constant fold an instruction of the
4392/// specified type, assuming that all operands were constants.
4393static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004394 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004395 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4396 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004397
Chris Lattner3221ad02004-04-17 22:58:41 +00004398 if (const CallInst *CI = dyn_cast<CallInst>(I))
4399 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004400 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004401 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004402}
4403
Chris Lattner3221ad02004-04-17 22:58:41 +00004404/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4405/// in the loop that V is derived from. We allow arbitrary operations along the
4406/// way, but the operands of an operation must either be constants or a value
4407/// derived from a constant PHI. If this expression does not fit with these
4408/// constraints, return null.
4409static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4410 // If this is not an instruction, or if this is an instruction outside of the
4411 // loop, it can't be derived from a loop PHI.
4412 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004413 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004414
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004415 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004416 if (L->getHeader() == I->getParent())
4417 return PN;
4418 else
4419 // We don't currently keep track of the control flow needed to evaluate
4420 // PHIs, so we cannot handle PHIs inside of loops.
4421 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004422 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004423
4424 // If we won't be able to constant fold this expression even if the operands
4425 // are constants, return early.
4426 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004427
Chris Lattner3221ad02004-04-17 22:58:41 +00004428 // Otherwise, we can evaluate this instruction if all of its operands are
4429 // constant or derived from a PHI node themselves.
4430 PHINode *PHI = 0;
4431 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004432 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004433 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4434 if (P == 0) return 0; // Not evolving from PHI
4435 if (PHI == 0)
4436 PHI = P;
4437 else if (PHI != P)
4438 return 0; // Evolving from multiple different PHIs.
4439 }
4440
4441 // This is a expression evolving from a constant PHI!
4442 return PHI;
4443}
4444
4445/// EvaluateExpression - Given an expression that passes the
4446/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4447/// in the loop has the value PHIVal. If we can't fold this expression for some
4448/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004449static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4450 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004451 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004452 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004453 Instruction *I = cast<Instruction>(V);
4454
Dan Gohman9d4588f2010-06-22 13:15:46 +00004455 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004456
4457 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004458 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004459 if (Operands[i] == 0) return 0;
4460 }
4461
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004462 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004463 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004464 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004465 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004466 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004467}
4468
4469/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4470/// in the header of its containing loop, we know the loop executes a
4471/// constant number of times, and the PHI node is just a recurrence
4472/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004473Constant *
4474ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004475 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004476 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004477 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004478 ConstantEvolutionLoopExitValue.find(PN);
4479 if (I != ConstantEvolutionLoopExitValue.end())
4480 return I->second;
4481
Dan Gohmane0567812010-04-08 23:03:40 +00004482 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004483 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4484
4485 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4486
4487 // Since the loop is canonicalized, the PHI node must have two entries. One
4488 // entry must be a constant (coming in from outside of the loop), and the
4489 // second must be derived from the same PHI.
4490 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4491 Constant *StartCST =
4492 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4493 if (StartCST == 0)
4494 return RetVal = 0; // Must be a constant.
4495
4496 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004497 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4498 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004499 return RetVal = 0; // Not derived from same PHI.
4500
4501 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004502 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004503 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004504
Dan Gohman46bdfb02009-02-24 18:55:53 +00004505 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004506 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004507 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4508 if (IterationNum == NumIterations)
4509 return RetVal = PHIVal; // Got exit value!
4510
4511 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004512 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004513 if (NextPHI == PHIVal)
4514 return RetVal = NextPHI; // Stopped evolving!
4515 if (NextPHI == 0)
4516 return 0; // Couldn't evaluate!
4517 PHIVal = NextPHI;
4518 }
4519}
4520
Dan Gohman07ad19b2009-07-27 16:09:48 +00004521/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004522/// constant number of times (the condition evolves only from constants),
4523/// try to evaluate a few iterations of the loop until we get the exit
4524/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004525/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004526const SCEV *
4527ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4528 Value *Cond,
4529 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004530 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004531 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004532
Dan Gohmanb92654d2010-06-19 14:17:24 +00004533 // If the loop is canonicalized, the PHI will have exactly two entries.
4534 // That's the only form we support here.
4535 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4536
4537 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004538 // second must be derived from the same PHI.
4539 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4540 Constant *StartCST =
4541 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004542 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004543
4544 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004545 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4546 !isa<Constant>(BEValue))
4547 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004548
4549 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4550 // the loop symbolically to determine when the condition gets a value of
4551 // "ExitWhen".
4552 unsigned IterationNum = 0;
4553 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4554 for (Constant *PHIVal = StartCST;
4555 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004556 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004557 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004558
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004559 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004560 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004561
Reid Spencere8019bb2007-03-01 07:25:48 +00004562 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004563 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004564 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004565 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004566
Chris Lattner3221ad02004-04-17 22:58:41 +00004567 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004568 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004569 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004570 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004571 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004572 }
4573
4574 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004575 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004576}
4577
Dan Gohmane7125f42009-09-03 15:00:26 +00004578/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004579/// at the specified scope in the program. The L value specifies a loop
4580/// nest to evaluate the expression at, where null is the top-level or a
4581/// specified loop is immediately inside of the loop.
4582///
4583/// This method can be used to compute the exit value for a variable defined
4584/// in a loop by querying what the value will hold in the parent loop.
4585///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004586/// In the case that a relevant loop exit value cannot be computed, the
4587/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004588const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004589 // Check to see if we've folded this expression at this loop before.
4590 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4591 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4592 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4593 if (!Pair.second)
4594 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004595
Dan Gohman42214892009-08-31 21:15:23 +00004596 // Otherwise compute it.
4597 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004598 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004599 return C;
4600}
4601
4602const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004603 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004604
Nick Lewycky3e630762008-02-20 06:48:22 +00004605 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004606 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004607 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004608 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004609 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004610 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4611 if (PHINode *PN = dyn_cast<PHINode>(I))
4612 if (PN->getParent() == LI->getHeader()) {
4613 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004614 // to see if the loop that contains it has a known backedge-taken
4615 // count. If so, we may be able to force computation of the exit
4616 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004617 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004618 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004619 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004620 // Okay, we know how many times the containing loop executes. If
4621 // this is a constant evolving PHI node, get the final value at
4622 // the specified iteration number.
4623 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004624 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004625 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004626 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004627 }
4628 }
4629
Reid Spencer09906f32006-12-04 21:33:23 +00004630 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004631 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004632 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004633 // result. This is particularly useful for computing loop exit values.
4634 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004635 SmallVector<Constant *, 4> Operands;
4636 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004637 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4638 Value *Op = I->getOperand(i);
4639 if (Constant *C = dyn_cast<Constant>(Op)) {
4640 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004641 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004642 }
Dan Gohman11046452010-06-29 23:43:06 +00004643
4644 // If any of the operands is non-constant and if they are
4645 // non-integer and non-pointer, don't even try to analyze them
4646 // with scev techniques.
4647 if (!isSCEVable(Op->getType()))
4648 return V;
4649
4650 const SCEV *OrigV = getSCEV(Op);
4651 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4652 MadeImprovement |= OrigV != OpV;
4653
4654 Constant *C = 0;
4655 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4656 C = SC->getValue();
4657 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4658 C = dyn_cast<Constant>(SU->getValue());
4659 if (!C) return V;
4660 if (C->getType() != Op->getType())
4661 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4662 Op->getType(),
4663 false),
4664 C, Op->getType());
4665 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004666 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004667
Dan Gohman11046452010-06-29 23:43:06 +00004668 // Check to see if getSCEVAtScope actually made an improvement.
4669 if (MadeImprovement) {
4670 Constant *C = 0;
4671 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4672 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4673 Operands[0], Operands[1], TD);
4674 else
4675 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4676 &Operands[0], Operands.size(), TD);
4677 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004678 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004679 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004680 }
4681 }
4682
4683 // This is some other type of SCEVUnknown, just return it.
4684 return V;
4685 }
4686
Dan Gohman622ed672009-05-04 22:02:23 +00004687 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004688 // Avoid performing the look-up in the common case where the specified
4689 // expression has no loop-variant portions.
4690 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004691 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004692 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004693 // Okay, at least one of these operands is loop variant but might be
4694 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004695 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4696 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004697 NewOps.push_back(OpAtScope);
4698
4699 for (++i; i != e; ++i) {
4700 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004701 NewOps.push_back(OpAtScope);
4702 }
4703 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004704 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004705 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004706 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004707 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004708 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004709 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004710 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004711 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004712 }
4713 }
4714 // If we got here, all operands are loop invariant.
4715 return Comm;
4716 }
4717
Dan Gohman622ed672009-05-04 22:02:23 +00004718 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004719 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4720 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004721 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4722 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004723 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004724 }
4725
4726 // If this is a loop recurrence for a loop that does not contain L, then we
4727 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004728 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004729 // First, attempt to evaluate each operand.
4730 // Avoid performing the look-up in the common case where the specified
4731 // expression has no loop-variant portions.
4732 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4733 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4734 if (OpAtScope == AddRec->getOperand(i))
4735 continue;
4736
4737 // Okay, at least one of these operands is loop variant but might be
4738 // foldable. Build a new instance of the folded commutative expression.
4739 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4740 AddRec->op_begin()+i);
4741 NewOps.push_back(OpAtScope);
4742 for (++i; i != e; ++i)
4743 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4744
Andrew Trick3228cc22011-03-14 16:50:06 +00004745 AddRec = cast<SCEVAddRecExpr>(
4746 getAddRecExpr(NewOps, AddRec->getLoop(),
4747 // FIXME: AddRec->getNoWrapFlags(SCEV::FlagNW)
4748 SCEV::FlagAnyWrap));
Dan Gohman11046452010-06-29 23:43:06 +00004749 break;
4750 }
4751
4752 // If the scope is outside the addrec's loop, evaluate it by using the
4753 // loop exit value of the addrec.
4754 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004755 // To evaluate this recurrence, we need to know how many times the AddRec
4756 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004757 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004758 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004759
Eli Friedmanb42a6262008-08-04 23:49:06 +00004760 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004761 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004762 }
Dan Gohman11046452010-06-29 23:43:06 +00004763
Dan Gohmand594e6f2009-05-24 23:25:42 +00004764 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004765 }
4766
Dan Gohman622ed672009-05-04 22:02:23 +00004767 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004768 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004769 if (Op == Cast->getOperand())
4770 return Cast; // must be loop invariant
4771 return getZeroExtendExpr(Op, Cast->getType());
4772 }
4773
Dan Gohman622ed672009-05-04 22:02:23 +00004774 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004775 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004776 if (Op == Cast->getOperand())
4777 return Cast; // must be loop invariant
4778 return getSignExtendExpr(Op, Cast->getType());
4779 }
4780
Dan Gohman622ed672009-05-04 22:02:23 +00004781 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004782 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004783 if (Op == Cast->getOperand())
4784 return Cast; // must be loop invariant
4785 return getTruncateExpr(Op, Cast->getType());
4786 }
4787
Torok Edwinc23197a2009-07-14 16:55:14 +00004788 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004789 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004790}
4791
Dan Gohman66a7e852009-05-08 20:38:54 +00004792/// getSCEVAtScope - This is a convenience function which does
4793/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004794const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004795 return getSCEVAtScope(getSCEV(V), L);
4796}
4797
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004798/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4799/// following equation:
4800///
4801/// A * X = B (mod N)
4802///
4803/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4804/// A and B isn't important.
4805///
4806/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004807static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004808 ScalarEvolution &SE) {
4809 uint32_t BW = A.getBitWidth();
4810 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4811 assert(A != 0 && "A must be non-zero.");
4812
4813 // 1. D = gcd(A, N)
4814 //
4815 // The gcd of A and N may have only one prime factor: 2. The number of
4816 // trailing zeros in A is its multiplicity
4817 uint32_t Mult2 = A.countTrailingZeros();
4818 // D = 2^Mult2
4819
4820 // 2. Check if B is divisible by D.
4821 //
4822 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4823 // is not less than multiplicity of this prime factor for D.
4824 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004825 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004826
4827 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4828 // modulo (N / D).
4829 //
4830 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4831 // bit width during computations.
4832 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4833 APInt Mod(BW + 1, 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00004834 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004835 APInt I = AD.multiplicativeInverse(Mod);
4836
4837 // 4. Compute the minimum unsigned root of the equation:
4838 // I * (B / D) mod (N / D)
4839 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4840
4841 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4842 // bits.
4843 return SE.getConstant(Result.trunc(BW));
4844}
Chris Lattner53e677a2004-04-02 20:23:17 +00004845
4846/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4847/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4848/// might be the same) or two SCEVCouldNotCompute objects.
4849///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004850static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004851SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004852 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004853 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4854 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4855 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004856
Chris Lattner53e677a2004-04-02 20:23:17 +00004857 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004858 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004859 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004860 return std::make_pair(CNC, CNC);
4861 }
4862
Reid Spencere8019bb2007-03-01 07:25:48 +00004863 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004864 const APInt &L = LC->getValue()->getValue();
4865 const APInt &M = MC->getValue()->getValue();
4866 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004867 APInt Two(BitWidth, 2);
4868 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004869
Dan Gohman64a845e2009-06-24 04:48:43 +00004870 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004871 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004872 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004873 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4874 // The B coefficient is M-N/2
4875 APInt B(M);
4876 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004877
Reid Spencere8019bb2007-03-01 07:25:48 +00004878 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004879 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004880
Reid Spencere8019bb2007-03-01 07:25:48 +00004881 // Compute the B^2-4ac term.
4882 APInt SqrtTerm(B);
4883 SqrtTerm *= B;
4884 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004885
Reid Spencere8019bb2007-03-01 07:25:48 +00004886 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4887 // integer value or else APInt::sqrt() will assert.
4888 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004889
Dan Gohman64a845e2009-06-24 04:48:43 +00004890 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004891 // The divisions must be performed as signed divisions.
4892 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004893 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004894 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004895 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004896 return std::make_pair(CNC, CNC);
4897 }
4898
Owen Andersone922c022009-07-22 00:24:57 +00004899 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004900
4901 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004902 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004903 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004904 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004905
Dan Gohman64a845e2009-06-24 04:48:43 +00004906 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004907 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004908 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004909}
4910
4911/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004912/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick3228cc22011-03-14 16:50:06 +00004913///
4914/// This is only used for loops with a "x != y" exit test. The exit condition is
4915/// now expressed as a single expression, V = x-y. So the exit test is
4916/// effectively V != 0. We know and take advantage of the fact that this
4917/// expression only being used in a comparison by zero context.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004918ScalarEvolution::BackedgeTakenInfo
4919ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004920 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004921 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004922 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004923 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004924 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004925 }
4926
Dan Gohman35738ac2009-05-04 22:30:44 +00004927 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004928 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004929 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004930
Chris Lattner7975e3e2011-01-09 22:39:48 +00004931 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4932 // the quadratic equation to solve it.
4933 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4934 std::pair<const SCEV *,const SCEV *> Roots =
4935 SolveQuadraticEquation(AddRec, *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004936 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4937 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner7975e3e2011-01-09 22:39:48 +00004938 if (R1 && R2) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004939#if 0
David Greene25e0e872009-12-23 22:18:14 +00004940 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004941 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004942#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004943 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004944 if (ConstantInt *CB =
Chris Lattner53e1d452011-01-09 22:58:47 +00004945 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
4946 R1->getValue(),
4947 R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004948 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004949 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick635f7182011-03-09 17:23:39 +00004950
Chris Lattner53e677a2004-04-02 20:23:17 +00004951 // We can only use this value if the chrec ends up with an exact zero
4952 // value at this index. When solving for "X*X != 5", for example, we
4953 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004954 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004955 if (Val->isZero())
4956 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004957 }
4958 }
Chris Lattner7975e3e2011-01-09 22:39:48 +00004959 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004960 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004961
Chris Lattner7975e3e2011-01-09 22:39:48 +00004962 // Otherwise we can only handle this if it is affine.
4963 if (!AddRec->isAffine())
4964 return getCouldNotCompute();
4965
4966 // If this is an affine expression, the execution count of this branch is
4967 // the minimum unsigned root of the following equation:
4968 //
4969 // Start + Step*N = 0 (mod 2^BW)
4970 //
4971 // equivalent to:
4972 //
4973 // Step*N = -Start (mod 2^BW)
4974 //
4975 // where BW is the common bit width of Start and Step.
4976
4977 // Get the initial value for the loop.
4978 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
4979 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
4980
4981 // For now we handle only constant steps.
Andrew Trick3228cc22011-03-14 16:50:06 +00004982 //
4983 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
4984 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
4985 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
4986 // We have not yet seen any such cases.
Chris Lattner7975e3e2011-01-09 22:39:48 +00004987 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
4988 if (StepC == 0)
4989 return getCouldNotCompute();
4990
Andrew Trick3228cc22011-03-14 16:50:06 +00004991 // For positive steps (counting up until unsigned overflow):
4992 // N = -Start/Step (as unsigned)
4993 // For negative steps (counting down to zero):
4994 // N = Start/-Step
4995 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickdcfd4042011-03-14 17:28:02 +00004996 bool CountDown = StepC->getValue()->getValue().isNegative();
4997 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick3228cc22011-03-14 16:50:06 +00004998
4999 // Handle unitary steps, which cannot wraparound.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005000 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5001 // N = Distance (as unsigned)
5002 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue())
5003 return Distance;
Andrew Trick635f7182011-03-09 17:23:39 +00005004
Andrew Trickdcfd4042011-03-14 17:28:02 +00005005 // If the recurrence is known not to wraparound, unsigned divide computes the
5006 // back edge count. We know that the value will either become zero (and thus
5007 // the loop terminates), that the loop will terminate through some other exit
5008 // condition first, or that the loop has undefined behavior. This means
5009 // we can't "miss" the exit value, even with nonunit stride.
5010 //
5011 // FIXME: Prove that loops always exhibits *acceptable* undefined
5012 // behavior. Loops must exhibit defined behavior until a wrapped value is
5013 // actually used. So the trip count computed by udiv could be smaller than the
5014 // number of well-defined iterations.
5015 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5016 // FIXME: We really want an "isexact" bit for udiv.
5017 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005018
5019 // Then, try to solve the above equation provided that Start is constant.
5020 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5021 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5022 -StartC->getValue()->getValue(),
5023 *this);
Dan Gohman1c343752009-06-27 21:21:31 +00005024 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005025}
5026
5027/// HowFarToNonZero - Return the number of times a backedge checking the
5028/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005029/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005030ScalarEvolution::BackedgeTakenInfo
5031ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005032 // Loops that look like: while (X == 0) are very strange indeed. We don't
5033 // handle them yet except for the trivial case. This could be expanded in the
5034 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005035
Chris Lattner53e677a2004-04-02 20:23:17 +00005036 // If the value is a constant, check to see if it is known to be non-zero
5037 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00005038 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00005039 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00005040 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00005041 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005042 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005043
Chris Lattner53e677a2004-04-02 20:23:17 +00005044 // We could implement others, but I really doubt anyone writes loops like
5045 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00005046 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005047}
5048
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005049/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5050/// (which may not be an immediate predecessor) which has exactly one
5051/// successor from which BB is reachable, or null if no such block is
5052/// found.
5053///
Dan Gohman005752b2010-04-15 16:19:08 +00005054std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005055ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00005056 // If the block has a unique predecessor, then there is no path from the
5057 // predecessor to the block that does not go through the direct edge
5058 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005059 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00005060 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005061
5062 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00005063 // If the header has a unique predecessor outside the loop, it must be
5064 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005065 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00005066 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005067
Dan Gohman005752b2010-04-15 16:19:08 +00005068 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005069}
5070
Dan Gohman763bad12009-06-20 00:35:32 +00005071/// HasSameValue - SCEV structural equivalence is usually sufficient for
5072/// testing whether two expressions are equal, however for the purposes of
5073/// looking for a condition guarding a loop, it can be useful to be a little
5074/// more general, since a front-end may have replicated the controlling
5075/// expression.
5076///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005077static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00005078 // Quick check to see if they are the same SCEV.
5079 if (A == B) return true;
5080
5081 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5082 // two different instructions with the same value. Check for this case.
5083 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5084 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5085 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5086 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00005087 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00005088 return true;
5089
5090 // Otherwise assume they may have a different value.
5091 return false;
5092}
5093
Dan Gohmane9796502010-04-24 01:28:42 +00005094/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5095/// predicate Pred. Return true iff any changes were made.
5096///
5097bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5098 const SCEV *&LHS, const SCEV *&RHS) {
5099 bool Changed = false;
5100
5101 // Canonicalize a constant to the right side.
5102 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5103 // Check for both operands constant.
5104 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5105 if (ConstantExpr::getICmp(Pred,
5106 LHSC->getValue(),
5107 RHSC->getValue())->isNullValue())
5108 goto trivially_false;
5109 else
5110 goto trivially_true;
5111 }
5112 // Otherwise swap the operands to put the constant on the right.
5113 std::swap(LHS, RHS);
5114 Pred = ICmpInst::getSwappedPredicate(Pred);
5115 Changed = true;
5116 }
5117
5118 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00005119 // addrec's loop, put the addrec on the left. Also make a dominance check,
5120 // as both operands could be addrecs loop-invariant in each other's loop.
5121 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5122 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00005123 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00005124 std::swap(LHS, RHS);
5125 Pred = ICmpInst::getSwappedPredicate(Pred);
5126 Changed = true;
5127 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00005128 }
Dan Gohmane9796502010-04-24 01:28:42 +00005129
5130 // If there's a constant operand, canonicalize comparisons with boundary
5131 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5132 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5133 const APInt &RA = RC->getValue()->getValue();
5134 switch (Pred) {
5135 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5136 case ICmpInst::ICMP_EQ:
5137 case ICmpInst::ICMP_NE:
5138 break;
5139 case ICmpInst::ICMP_UGE:
5140 if ((RA - 1).isMinValue()) {
5141 Pred = ICmpInst::ICMP_NE;
5142 RHS = getConstant(RA - 1);
5143 Changed = true;
5144 break;
5145 }
5146 if (RA.isMaxValue()) {
5147 Pred = ICmpInst::ICMP_EQ;
5148 Changed = true;
5149 break;
5150 }
5151 if (RA.isMinValue()) goto trivially_true;
5152
5153 Pred = ICmpInst::ICMP_UGT;
5154 RHS = getConstant(RA - 1);
5155 Changed = true;
5156 break;
5157 case ICmpInst::ICMP_ULE:
5158 if ((RA + 1).isMaxValue()) {
5159 Pred = ICmpInst::ICMP_NE;
5160 RHS = getConstant(RA + 1);
5161 Changed = true;
5162 break;
5163 }
5164 if (RA.isMinValue()) {
5165 Pred = ICmpInst::ICMP_EQ;
5166 Changed = true;
5167 break;
5168 }
5169 if (RA.isMaxValue()) goto trivially_true;
5170
5171 Pred = ICmpInst::ICMP_ULT;
5172 RHS = getConstant(RA + 1);
5173 Changed = true;
5174 break;
5175 case ICmpInst::ICMP_SGE:
5176 if ((RA - 1).isMinSignedValue()) {
5177 Pred = ICmpInst::ICMP_NE;
5178 RHS = getConstant(RA - 1);
5179 Changed = true;
5180 break;
5181 }
5182 if (RA.isMaxSignedValue()) {
5183 Pred = ICmpInst::ICMP_EQ;
5184 Changed = true;
5185 break;
5186 }
5187 if (RA.isMinSignedValue()) goto trivially_true;
5188
5189 Pred = ICmpInst::ICMP_SGT;
5190 RHS = getConstant(RA - 1);
5191 Changed = true;
5192 break;
5193 case ICmpInst::ICMP_SLE:
5194 if ((RA + 1).isMaxSignedValue()) {
5195 Pred = ICmpInst::ICMP_NE;
5196 RHS = getConstant(RA + 1);
5197 Changed = true;
5198 break;
5199 }
5200 if (RA.isMinSignedValue()) {
5201 Pred = ICmpInst::ICMP_EQ;
5202 Changed = true;
5203 break;
5204 }
5205 if (RA.isMaxSignedValue()) goto trivially_true;
5206
5207 Pred = ICmpInst::ICMP_SLT;
5208 RHS = getConstant(RA + 1);
5209 Changed = true;
5210 break;
5211 case ICmpInst::ICMP_UGT:
5212 if (RA.isMinValue()) {
5213 Pred = ICmpInst::ICMP_NE;
5214 Changed = true;
5215 break;
5216 }
5217 if ((RA + 1).isMaxValue()) {
5218 Pred = ICmpInst::ICMP_EQ;
5219 RHS = getConstant(RA + 1);
5220 Changed = true;
5221 break;
5222 }
5223 if (RA.isMaxValue()) goto trivially_false;
5224 break;
5225 case ICmpInst::ICMP_ULT:
5226 if (RA.isMaxValue()) {
5227 Pred = ICmpInst::ICMP_NE;
5228 Changed = true;
5229 break;
5230 }
5231 if ((RA - 1).isMinValue()) {
5232 Pred = ICmpInst::ICMP_EQ;
5233 RHS = getConstant(RA - 1);
5234 Changed = true;
5235 break;
5236 }
5237 if (RA.isMinValue()) goto trivially_false;
5238 break;
5239 case ICmpInst::ICMP_SGT:
5240 if (RA.isMinSignedValue()) {
5241 Pred = ICmpInst::ICMP_NE;
5242 Changed = true;
5243 break;
5244 }
5245 if ((RA + 1).isMaxSignedValue()) {
5246 Pred = ICmpInst::ICMP_EQ;
5247 RHS = getConstant(RA + 1);
5248 Changed = true;
5249 break;
5250 }
5251 if (RA.isMaxSignedValue()) goto trivially_false;
5252 break;
5253 case ICmpInst::ICMP_SLT:
5254 if (RA.isMaxSignedValue()) {
5255 Pred = ICmpInst::ICMP_NE;
5256 Changed = true;
5257 break;
5258 }
5259 if ((RA - 1).isMinSignedValue()) {
5260 Pred = ICmpInst::ICMP_EQ;
5261 RHS = getConstant(RA - 1);
5262 Changed = true;
5263 break;
5264 }
5265 if (RA.isMinSignedValue()) goto trivially_false;
5266 break;
5267 }
5268 }
5269
5270 // Check for obvious equality.
5271 if (HasSameValue(LHS, RHS)) {
5272 if (ICmpInst::isTrueWhenEqual(Pred))
5273 goto trivially_true;
5274 if (ICmpInst::isFalseWhenEqual(Pred))
5275 goto trivially_false;
5276 }
5277
Dan Gohman03557dc2010-05-03 16:35:17 +00005278 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5279 // adding or subtracting 1 from one of the operands.
5280 switch (Pred) {
5281 case ICmpInst::ICMP_SLE:
5282 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5283 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005284 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005285 Pred = ICmpInst::ICMP_SLT;
5286 Changed = true;
5287 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005288 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005289 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005290 Pred = ICmpInst::ICMP_SLT;
5291 Changed = true;
5292 }
5293 break;
5294 case ICmpInst::ICMP_SGE:
5295 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005296 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005297 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005298 Pred = ICmpInst::ICMP_SGT;
5299 Changed = true;
5300 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5301 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005302 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005303 Pred = ICmpInst::ICMP_SGT;
5304 Changed = true;
5305 }
5306 break;
5307 case ICmpInst::ICMP_ULE:
5308 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005309 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005310 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005311 Pred = ICmpInst::ICMP_ULT;
5312 Changed = true;
5313 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005314 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005315 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005316 Pred = ICmpInst::ICMP_ULT;
5317 Changed = true;
5318 }
5319 break;
5320 case ICmpInst::ICMP_UGE:
5321 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005322 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005323 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005324 Pred = ICmpInst::ICMP_UGT;
5325 Changed = true;
5326 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005327 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005328 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005329 Pred = ICmpInst::ICMP_UGT;
5330 Changed = true;
5331 }
5332 break;
5333 default:
5334 break;
5335 }
5336
Dan Gohmane9796502010-04-24 01:28:42 +00005337 // TODO: More simplifications are possible here.
5338
5339 return Changed;
5340
5341trivially_true:
5342 // Return 0 == 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005343 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005344 Pred = ICmpInst::ICMP_EQ;
5345 return true;
5346
5347trivially_false:
5348 // Return 0 != 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005349 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005350 Pred = ICmpInst::ICMP_NE;
5351 return true;
5352}
5353
Dan Gohman85b05a22009-07-13 21:35:55 +00005354bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5355 return getSignedRange(S).getSignedMax().isNegative();
5356}
5357
5358bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5359 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5360}
5361
5362bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5363 return !getSignedRange(S).getSignedMin().isNegative();
5364}
5365
5366bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5367 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5368}
5369
5370bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5371 return isKnownNegative(S) || isKnownPositive(S);
5372}
5373
5374bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5375 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005376 // Canonicalize the inputs first.
5377 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5378
Dan Gohman53c66ea2010-04-11 22:16:48 +00005379 // If LHS or RHS is an addrec, check to see if the condition is true in
5380 // every iteration of the loop.
5381 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5382 if (isLoopEntryGuardedByCond(
5383 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5384 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005385 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005386 return true;
5387 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5388 if (isLoopEntryGuardedByCond(
5389 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5390 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005391 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005392 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005393
Dan Gohman53c66ea2010-04-11 22:16:48 +00005394 // Otherwise see what can be done with known constant ranges.
5395 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5396}
5397
5398bool
5399ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5400 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005401 if (HasSameValue(LHS, RHS))
5402 return ICmpInst::isTrueWhenEqual(Pred);
5403
Dan Gohman53c66ea2010-04-11 22:16:48 +00005404 // This code is split out from isKnownPredicate because it is called from
5405 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005406 switch (Pred) {
5407 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005408 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005409 break;
5410 case ICmpInst::ICMP_SGT:
5411 Pred = ICmpInst::ICMP_SLT;
5412 std::swap(LHS, RHS);
5413 case ICmpInst::ICMP_SLT: {
5414 ConstantRange LHSRange = getSignedRange(LHS);
5415 ConstantRange RHSRange = getSignedRange(RHS);
5416 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5417 return true;
5418 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5419 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005420 break;
5421 }
5422 case ICmpInst::ICMP_SGE:
5423 Pred = ICmpInst::ICMP_SLE;
5424 std::swap(LHS, RHS);
5425 case ICmpInst::ICMP_SLE: {
5426 ConstantRange LHSRange = getSignedRange(LHS);
5427 ConstantRange RHSRange = getSignedRange(RHS);
5428 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5429 return true;
5430 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5431 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005432 break;
5433 }
5434 case ICmpInst::ICMP_UGT:
5435 Pred = ICmpInst::ICMP_ULT;
5436 std::swap(LHS, RHS);
5437 case ICmpInst::ICMP_ULT: {
5438 ConstantRange LHSRange = getUnsignedRange(LHS);
5439 ConstantRange RHSRange = getUnsignedRange(RHS);
5440 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5441 return true;
5442 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5443 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005444 break;
5445 }
5446 case ICmpInst::ICMP_UGE:
5447 Pred = ICmpInst::ICMP_ULE;
5448 std::swap(LHS, RHS);
5449 case ICmpInst::ICMP_ULE: {
5450 ConstantRange LHSRange = getUnsignedRange(LHS);
5451 ConstantRange RHSRange = getUnsignedRange(RHS);
5452 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5453 return true;
5454 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5455 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005456 break;
5457 }
5458 case ICmpInst::ICMP_NE: {
5459 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5460 return true;
5461 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5462 return true;
5463
5464 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5465 if (isKnownNonZero(Diff))
5466 return true;
5467 break;
5468 }
5469 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005470 // The check at the top of the function catches the case where
5471 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005472 break;
5473 }
5474 return false;
5475}
5476
5477/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5478/// protected by a conditional between LHS and RHS. This is used to
5479/// to eliminate casts.
5480bool
5481ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5482 ICmpInst::Predicate Pred,
5483 const SCEV *LHS, const SCEV *RHS) {
5484 // Interpret a null as meaning no loop, where there is obviously no guard
5485 // (interprocedural conditions notwithstanding).
5486 if (!L) return true;
5487
5488 BasicBlock *Latch = L->getLoopLatch();
5489 if (!Latch)
5490 return false;
5491
5492 BranchInst *LoopContinuePredicate =
5493 dyn_cast<BranchInst>(Latch->getTerminator());
5494 if (!LoopContinuePredicate ||
5495 LoopContinuePredicate->isUnconditional())
5496 return false;
5497
Dan Gohmanaf08a362010-08-10 23:46:30 +00005498 return isImpliedCond(Pred, LHS, RHS,
5499 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005500 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005501}
5502
Dan Gohman3948d0b2010-04-11 19:27:13 +00005503/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005504/// by a conditional between LHS and RHS. This is used to help avoid max
5505/// expressions in loop trip counts, and to eliminate casts.
5506bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005507ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5508 ICmpInst::Predicate Pred,
5509 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005510 // Interpret a null as meaning no loop, where there is obviously no guard
5511 // (interprocedural conditions notwithstanding).
5512 if (!L) return false;
5513
Dan Gohman859b4822009-05-18 15:36:09 +00005514 // Starting at the loop predecessor, climb up the predecessor chain, as long
5515 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005516 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005517 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005518 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005519 Pair.first;
5520 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005521
5522 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005523 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005524 if (!LoopEntryPredicate ||
5525 LoopEntryPredicate->isUnconditional())
5526 continue;
5527
Dan Gohmanaf08a362010-08-10 23:46:30 +00005528 if (isImpliedCond(Pred, LHS, RHS,
5529 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005530 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005531 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005532 }
5533
Dan Gohman38372182008-08-12 20:17:31 +00005534 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005535}
5536
Dan Gohman0f4b2852009-07-21 23:03:19 +00005537/// isImpliedCond - Test whether the condition described by Pred, LHS,
5538/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005539bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005540 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005541 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005542 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005543 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005545 if (BO->getOpcode() == Instruction::And) {
5546 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005547 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5548 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005549 } else if (BO->getOpcode() == Instruction::Or) {
5550 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005551 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5552 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005553 }
5554 }
5555
Dan Gohmanaf08a362010-08-10 23:46:30 +00005556 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005557 if (!ICI) return false;
5558
Dan Gohman85b05a22009-07-13 21:35:55 +00005559 // Bail if the ICmp's operands' types are wider than the needed type
5560 // before attempting to call getSCEV on them. This avoids infinite
5561 // recursion, since the analysis of widening casts can require loop
5562 // exit condition information for overflow checking, which would
5563 // lead back here.
5564 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005565 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005566 return false;
5567
Dan Gohman0f4b2852009-07-21 23:03:19 +00005568 // Now that we found a conditional branch that dominates the loop, check to
5569 // see if it is the comparison we are looking for.
5570 ICmpInst::Predicate FoundPred;
5571 if (Inverse)
5572 FoundPred = ICI->getInversePredicate();
5573 else
5574 FoundPred = ICI->getPredicate();
5575
5576 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5577 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005578
5579 // Balance the types. The case where FoundLHS' type is wider than
5580 // LHS' type is checked for above.
5581 if (getTypeSizeInBits(LHS->getType()) >
5582 getTypeSizeInBits(FoundLHS->getType())) {
5583 if (CmpInst::isSigned(Pred)) {
5584 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5585 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5586 } else {
5587 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5588 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5589 }
5590 }
5591
Dan Gohman0f4b2852009-07-21 23:03:19 +00005592 // Canonicalize the query to match the way instcombine will have
5593 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005594 if (SimplifyICmpOperands(Pred, LHS, RHS))
5595 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005596 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005597 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5598 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005599 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005600
5601 // Check to see if we can make the LHS or RHS match.
5602 if (LHS == FoundRHS || RHS == FoundLHS) {
5603 if (isa<SCEVConstant>(RHS)) {
5604 std::swap(FoundLHS, FoundRHS);
5605 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5606 } else {
5607 std::swap(LHS, RHS);
5608 Pred = ICmpInst::getSwappedPredicate(Pred);
5609 }
5610 }
5611
5612 // Check whether the found predicate is the same as the desired predicate.
5613 if (FoundPred == Pred)
5614 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5615
5616 // Check whether swapping the found predicate makes it the same as the
5617 // desired predicate.
5618 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5619 if (isa<SCEVConstant>(RHS))
5620 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5621 else
5622 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5623 RHS, LHS, FoundLHS, FoundRHS);
5624 }
5625
5626 // Check whether the actual condition is beyond sufficient.
5627 if (FoundPred == ICmpInst::ICMP_EQ)
5628 if (ICmpInst::isTrueWhenEqual(Pred))
5629 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5630 return true;
5631 if (Pred == ICmpInst::ICMP_NE)
5632 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5633 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5634 return true;
5635
5636 // Otherwise assume the worst.
5637 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005638}
5639
Dan Gohman0f4b2852009-07-21 23:03:19 +00005640/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005641/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005642/// and FoundRHS is true.
5643bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5644 const SCEV *LHS, const SCEV *RHS,
5645 const SCEV *FoundLHS,
5646 const SCEV *FoundRHS) {
5647 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5648 FoundLHS, FoundRHS) ||
5649 // ~x < ~y --> x > y
5650 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5651 getNotSCEV(FoundRHS),
5652 getNotSCEV(FoundLHS));
5653}
5654
5655/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005656/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005657/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005658bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005659ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5660 const SCEV *LHS, const SCEV *RHS,
5661 const SCEV *FoundLHS,
5662 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005663 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005664 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5665 case ICmpInst::ICMP_EQ:
5666 case ICmpInst::ICMP_NE:
5667 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5668 return true;
5669 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005670 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005671 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005672 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5673 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005674 return true;
5675 break;
5676 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005677 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005678 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5679 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005680 return true;
5681 break;
5682 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005683 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005684 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5685 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005686 return true;
5687 break;
5688 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005689 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005690 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5691 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005692 return true;
5693 break;
5694 }
5695
5696 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005697}
5698
Dan Gohman51f53b72009-06-21 23:46:38 +00005699/// getBECount - Subtract the end and start values and divide by the step,
5700/// rounding up, to get the number of times the backedge is executed. Return
5701/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005702const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005703 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005704 const SCEV *Step,
5705 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005706 assert(!isKnownNegative(Step) &&
5707 "This code doesn't handle negative strides yet!");
5708
Dan Gohman51f53b72009-06-21 23:46:38 +00005709 const Type *Ty = Start->getType();
Andrew Tricke62289b2011-03-09 17:29:58 +00005710
5711 // When Start == End, we have an exact BECount == 0. Short-circuit this case
5712 // here because SCEV may not be able to determine that the unsigned division
5713 // after rounding is zero.
5714 if (Start == End)
5715 return getConstant(Ty, 0);
5716
Dan Gohmandeff6212010-05-03 22:09:21 +00005717 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005718 const SCEV *Diff = getMinusSCEV(End, Start);
5719 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005720
5721 // Add an adjustment to the difference between End and Start so that
5722 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005723 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005724
Dan Gohman1f96e672009-09-17 18:05:20 +00005725 if (!NoWrap) {
5726 // Check Add for unsigned overflow.
5727 // TODO: More sophisticated things could be done here.
5728 const Type *WideTy = IntegerType::get(getContext(),
5729 getTypeSizeInBits(Ty) + 1);
5730 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5731 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5732 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5733 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5734 return getCouldNotCompute();
5735 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005736
5737 return getUDivExpr(Add, Step);
5738}
5739
Chris Lattnerdb25de42005-08-15 23:33:51 +00005740/// HowManyLessThans - Return the number of times a backedge containing the
5741/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005742/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005743ScalarEvolution::BackedgeTakenInfo
5744ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5745 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005746 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005747 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005748
Dan Gohman35738ac2009-05-04 22:30:44 +00005749 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005750 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005751 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005752
Dan Gohman1f96e672009-09-17 18:05:20 +00005753 // Check to see if we have a flag which makes analysis easy.
Andrew Trick3228cc22011-03-14 16:50:06 +00005754 bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5755 AddRec->getNoWrapFlags(SCEV::FlagNUW);
Dan Gohman1f96e672009-09-17 18:05:20 +00005756
Chris Lattnerdb25de42005-08-15 23:33:51 +00005757 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005758 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005759 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005760
Dan Gohman52fddd32010-01-26 04:40:18 +00005761 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005762 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005763 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005764 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005765 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005766 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005767 // value and past the maximum value for its type in a single step.
5768 // Note that it's not sufficient to check NoWrap here, because even
5769 // though the value after a wrap is undefined, it's not undefined
5770 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005771 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005772 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005773 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005774 if (isSigned) {
5775 APInt Max = APInt::getSignedMaxValue(BitWidth);
5776 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5777 .slt(getSignedRange(RHS).getSignedMax()))
5778 return getCouldNotCompute();
5779 } else {
5780 APInt Max = APInt::getMaxValue(BitWidth);
5781 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5782 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5783 return getCouldNotCompute();
5784 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005785 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005786 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005787 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005788
Dan Gohmana1af7572009-04-30 20:47:05 +00005789 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5790 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5791 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005792 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005793
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005794 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005795 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005796
Dan Gohmana1af7572009-04-30 20:47:05 +00005797 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005798 const SCEV *MinStart = getConstant(isSigned ?
5799 getSignedRange(Start).getSignedMin() :
5800 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005801
Dan Gohmana1af7572009-04-30 20:47:05 +00005802 // If we know that the condition is true in order to enter the loop,
5803 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005804 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5805 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005806 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005807 if (!isLoopEntryGuardedByCond(L,
5808 isSigned ? ICmpInst::ICMP_SLT :
5809 ICmpInst::ICMP_ULT,
5810 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005811 End = isSigned ? getSMaxExpr(RHS, Start)
5812 : getUMaxExpr(RHS, Start);
5813
5814 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005815 const SCEV *MaxEnd = getConstant(isSigned ?
5816 getSignedRange(End).getSignedMax() :
5817 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005818
Dan Gohman52fddd32010-01-26 04:40:18 +00005819 // If MaxEnd is within a step of the maximum integer value in its type,
5820 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005821 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005822 // compute the correct value.
5823 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005824 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005825 MaxEnd = isSigned ?
5826 getSMinExpr(MaxEnd,
5827 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5828 StepMinusOne)) :
5829 getUMinExpr(MaxEnd,
5830 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5831 StepMinusOne));
5832
Dan Gohmana1af7572009-04-30 20:47:05 +00005833 // Finally, we subtract these two values and divide, rounding up, to get
5834 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005835 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005836
5837 // The maximum backedge count is similar, except using the minimum start
5838 // value and the maximum end value.
Andrew Tricke62289b2011-03-09 17:29:58 +00005839 // If we already have an exact constant BECount, use it instead.
5840 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
5841 : getBECount(MinStart, MaxEnd, Step, NoWrap);
5842
5843 // If the stride is nonconstant, and NoWrap == true, then
5844 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
5845 // exact BECount and invalid MaxBECount, which should be avoided to catch
5846 // more optimization opportunities.
5847 if (isa<SCEVCouldNotCompute>(MaxBECount))
5848 MaxBECount = BECount;
Dan Gohmana1af7572009-04-30 20:47:05 +00005849
5850 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005851 }
5852
Dan Gohman1c343752009-06-27 21:21:31 +00005853 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005854}
5855
Chris Lattner53e677a2004-04-02 20:23:17 +00005856/// getNumIterationsInRange - Return the number of iterations of this loop that
5857/// produce values in the specified constant range. Another way of looking at
5858/// this is that it returns the first iteration number where the value is not in
5859/// the condition, thus computing the exit count. If the iteration count can't
5860/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005861const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005862 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005863 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005864 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005865
5866 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005867 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005868 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005869 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005870 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00005871 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
5872 // FIXME: getNoWrapFlags(FlagNW)
5873 FlagAnyWrap);
Dan Gohman622ed672009-05-04 22:02:23 +00005874 if (const SCEVAddRecExpr *ShiftedAddRec =
5875 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005876 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005877 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005878 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005879 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005880 }
5881
5882 // The only time we can solve this is when we have all constant indices.
5883 // Otherwise, we cannot determine the overflow conditions.
5884 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5885 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005886 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005887
5888
5889 // Okay at this point we know that all elements of the chrec are constants and
5890 // that the start element is zero.
5891
5892 // First check to see if the range contains zero. If not, the first
5893 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005894 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005895 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005896 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005897
Chris Lattner53e677a2004-04-02 20:23:17 +00005898 if (isAffine()) {
5899 // If this is an affine expression then we have this situation:
5900 // Solve {0,+,A} in Range === Ax in Range
5901
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005902 // We know that zero is in the range. If A is positive then we know that
5903 // the upper value of the range must be the first possible exit value.
5904 // If A is negative then the lower of the range is the last possible loop
5905 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005906 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005907 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5908 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005909
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005910 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005911 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005912 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005913
5914 // Evaluate at the exit value. If we really did fall out of the valid
5915 // range, then we computed our trip count, otherwise wrap around or other
5916 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005917 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005918 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005919 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005920
5921 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005922 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005923 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005924 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005925 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005926 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005927 } else if (isQuadratic()) {
5928 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5929 // quadratic equation to solve it. To do this, we must frame our problem in
5930 // terms of figuring out when zero is crossed, instead of when
5931 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005932 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005933 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick3228cc22011-03-14 16:50:06 +00005934 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
5935 // getNoWrapFlags(FlagNW)
5936 FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00005937
5938 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005939 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005940 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005941 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5942 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005943 if (R1) {
5944 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005945 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005946 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005947 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005948 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005949 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005950
Chris Lattner53e677a2004-04-02 20:23:17 +00005951 // Make sure the root is not off by one. The returned iteration should
5952 // not be in the range, but the previous one should be. When solving
5953 // for "X*X < 5", for example, we should not return a root of 2.
5954 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005955 R1->getValue(),
5956 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005957 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005958 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005959 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005960 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005961
Dan Gohman246b2562007-10-22 18:31:58 +00005962 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005963 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005964 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005965 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005966 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005967
Chris Lattner53e677a2004-04-02 20:23:17 +00005968 // If R1 was not in the range, then it is a good return value. Make
5969 // sure that R1-1 WAS in the range though, just in case.
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);
Dan Gohman246b2562007-10-22 18:31:58 +00005972 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005973 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005974 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005975 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005976 }
5977 }
5978 }
5979
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005980 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005981}
5982
5983
5984
5985//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005986// SCEVCallbackVH Class Implementation
5987//===----------------------------------------------------------------------===//
5988
Dan Gohman1959b752009-05-19 19:22:47 +00005989void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005990 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005991 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5992 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005993 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00005994 // this now dangles!
5995}
5996
Dan Gohman81f91212010-07-28 01:09:07 +00005997void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005998 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005999
Dan Gohman35738ac2009-05-04 22:30:44 +00006000 // Forget all the expressions associated with users of the old value,
6001 // so that future queries will recompute the expressions using the new
6002 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00006003 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00006004 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00006005 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00006006 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6007 UI != UE; ++UI)
6008 Worklist.push_back(*UI);
6009 while (!Worklist.empty()) {
6010 User *U = Worklist.pop_back_val();
6011 // Deleting the Old value will cause this to dangle. Postpone
6012 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00006013 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00006014 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00006015 if (!Visited.insert(U))
6016 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00006017 if (PHINode *PN = dyn_cast<PHINode>(U))
6018 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006019 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00006020 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6021 UI != UE; ++UI)
6022 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00006023 }
Dan Gohman59846ac2010-07-28 00:28:25 +00006024 // Delete the Old value.
6025 if (PHINode *PN = dyn_cast<PHINode>(Old))
6026 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006027 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00006028 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00006029}
6030
Dan Gohman1959b752009-05-19 19:22:47 +00006031ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00006032 : CallbackVH(V), SE(se) {}
6033
6034//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00006035// ScalarEvolution Class Implementation
6036//===----------------------------------------------------------------------===//
6037
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006038ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00006039 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00006040 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006041}
6042
Chris Lattner53e677a2004-04-02 20:23:17 +00006043bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006044 this->F = &F;
6045 LI = &getAnalysis<LoopInfo>();
6046 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00006047 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00006048 return false;
6049}
6050
6051void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00006052 // Iterate through all the SCEVUnknown instances and call their
6053 // destructors, so that they release their references to their values.
6054 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6055 U->~SCEVUnknown();
6056 FirstUnknown = 0;
6057
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006058 ValueExprMap.clear();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006059 BackedgeTakenCounts.clear();
6060 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00006061 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00006062 LoopDispositions.clear();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006063 BlockDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00006064 UnsignedRanges.clear();
6065 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00006066 UniqueSCEVs.clear();
6067 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00006068}
6069
6070void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6071 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00006072 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00006073 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00006074}
6075
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006076bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006077 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00006078}
6079
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006080static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00006081 const Loop *L) {
6082 // Print all inner loops first
6083 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6084 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006085
Dan Gohman30733292010-01-09 18:17:45 +00006086 OS << "Loop ";
6087 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6088 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006089
Dan Gohman5d984912009-12-18 01:14:11 +00006090 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006091 L->getExitBlocks(ExitBlocks);
6092 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00006093 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006094
Dan Gohman46bdfb02009-02-24 18:55:53 +00006095 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6096 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00006097 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006098 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006099 }
6100
Dan Gohman30733292010-01-09 18:17:45 +00006101 OS << "\n"
6102 "Loop ";
6103 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6104 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00006105
6106 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6107 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6108 } else {
6109 OS << "Unpredictable max backedge-taken count. ";
6110 }
6111
6112 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006113}
6114
Dan Gohman5d984912009-12-18 01:14:11 +00006115void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006116 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006117 // out SCEV values of all instructions that are interesting. Doing
6118 // this potentially causes it to create new SCEV objects though,
6119 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00006120 // observable from outside the class though, so casting away the
6121 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00006122 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00006123
Dan Gohman30733292010-01-09 18:17:45 +00006124 OS << "Classifying expressions for: ";
6125 WriteAsOperand(OS, F, /*PrintType=*/false);
6126 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006127 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00006128 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00006129 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00006130 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006131 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006132 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006133
Dan Gohman0c689c52009-06-19 17:49:54 +00006134 const Loop *L = LI->getLoopFor((*I).getParent());
6135
Dan Gohman0bba49c2009-07-07 17:06:11 +00006136 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00006137 if (AtUse != SV) {
6138 OS << " --> ";
6139 AtUse->print(OS);
6140 }
6141
6142 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00006143 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006144 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00006145 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006146 OS << "<<Unknown>>";
6147 } else {
6148 OS << *ExitValue;
6149 }
6150 }
6151
Chris Lattner53e677a2004-04-02 20:23:17 +00006152 OS << "\n";
6153 }
6154
Dan Gohman30733292010-01-09 18:17:45 +00006155 OS << "Determining loop execution counts for: ";
6156 WriteAsOperand(OS, F, /*PrintType=*/false);
6157 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006158 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6159 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006160}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00006161
Dan Gohman714b5292010-11-17 23:21:44 +00006162ScalarEvolution::LoopDisposition
6163ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6164 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6165 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6166 Values.insert(std::make_pair(L, LoopVariant));
6167 if (!Pair.second)
6168 return Pair.first->second;
6169
6170 LoopDisposition D = computeLoopDisposition(S, L);
6171 return LoopDispositions[S][L] = D;
6172}
6173
6174ScalarEvolution::LoopDisposition
6175ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00006176 switch (S->getSCEVType()) {
6177 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00006178 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006179 case scTruncate:
6180 case scZeroExtend:
6181 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00006182 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006183 case scAddRecExpr: {
6184 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6185
Dan Gohman714b5292010-11-17 23:21:44 +00006186 // If L is the addrec's loop, it's computable.
6187 if (AR->getLoop() == L)
6188 return LoopComputable;
6189
Dan Gohman17ead4f2010-11-17 21:23:15 +00006190 // Add recurrences are never invariant in the function-body (null loop).
6191 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00006192 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006193
6194 // This recurrence is variant w.r.t. L if L contains AR's loop.
6195 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00006196 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006197
6198 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6199 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00006200 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006201
6202 // This recurrence is variant w.r.t. L if any of its operands
6203 // are variant.
6204 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6205 I != E; ++I)
6206 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00006207 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006208
6209 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00006210 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006211 }
6212 case scAddExpr:
6213 case scMulExpr:
6214 case scUMaxExpr:
6215 case scSMaxExpr: {
6216 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006217 bool HasVarying = false;
6218 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6219 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00006220 LoopDisposition D = getLoopDisposition(*I, L);
6221 if (D == LoopVariant)
6222 return LoopVariant;
6223 if (D == LoopComputable)
6224 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006225 }
Dan Gohman714b5292010-11-17 23:21:44 +00006226 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006227 }
6228 case scUDivExpr: {
6229 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00006230 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6231 if (LD == LoopVariant)
6232 return LoopVariant;
6233 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6234 if (RD == LoopVariant)
6235 return LoopVariant;
6236 return (LD == LoopInvariant && RD == LoopInvariant) ?
6237 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006238 }
6239 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00006240 // All non-instruction values are loop invariant. All instructions are loop
6241 // invariant if they are not contained in the specified loop.
6242 // Instructions are never considered invariant in the function body
6243 // (null loop) because they are defined within the "loop".
6244 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6245 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6246 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006247 case scCouldNotCompute:
6248 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00006249 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006250 default: break;
6251 }
6252 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00006253 return LoopVariant;
6254}
6255
6256bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6257 return getLoopDisposition(S, L) == LoopInvariant;
6258}
6259
6260bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6261 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006262}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006263
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006264ScalarEvolution::BlockDisposition
6265ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6266 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6267 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6268 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6269 if (!Pair.second)
6270 return Pair.first->second;
6271
6272 BlockDisposition D = computeBlockDisposition(S, BB);
6273 return BlockDispositions[S][BB] = D;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006274}
6275
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006276ScalarEvolution::BlockDisposition
6277ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006278 switch (S->getSCEVType()) {
6279 case scConstant:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006280 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006281 case scTruncate:
6282 case scZeroExtend:
6283 case scSignExtend:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006284 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006285 case scAddRecExpr: {
6286 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006287 // to test for proper dominance too, because the instruction which
6288 // produces the addrec's value is a PHI, and a PHI effectively properly
6289 // dominates its entire containing block.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006290 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6291 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006292 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006293 }
6294 // FALL THROUGH into SCEVNAryExpr handling.
6295 case scAddExpr:
6296 case scMulExpr:
6297 case scUMaxExpr:
6298 case scSMaxExpr: {
6299 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006300 bool Proper = true;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006301 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006302 I != E; ++I) {
6303 BlockDisposition D = getBlockDisposition(*I, BB);
6304 if (D == DoesNotDominateBlock)
6305 return DoesNotDominateBlock;
6306 if (D == DominatesBlock)
6307 Proper = false;
6308 }
6309 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006310 }
6311 case scUDivExpr: {
6312 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006313 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6314 BlockDisposition LD = getBlockDisposition(LHS, BB);
6315 if (LD == DoesNotDominateBlock)
6316 return DoesNotDominateBlock;
6317 BlockDisposition RD = getBlockDisposition(RHS, BB);
6318 if (RD == DoesNotDominateBlock)
6319 return DoesNotDominateBlock;
6320 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6321 ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006322 }
6323 case scUnknown:
6324 if (Instruction *I =
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006325 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6326 if (I->getParent() == BB)
6327 return DominatesBlock;
6328 if (DT->properlyDominates(I->getParent(), BB))
6329 return ProperlyDominatesBlock;
6330 return DoesNotDominateBlock;
6331 }
6332 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006333 case scCouldNotCompute:
6334 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006335 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006336 default: break;
6337 }
6338 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006339 return DoesNotDominateBlock;
6340}
6341
6342bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6343 return getBlockDisposition(S, BB) >= DominatesBlock;
6344}
6345
6346bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6347 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006348}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006349
6350bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6351 switch (S->getSCEVType()) {
6352 case scConstant:
6353 return false;
6354 case scTruncate:
6355 case scZeroExtend:
6356 case scSignExtend: {
6357 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6358 const SCEV *CastOp = Cast->getOperand();
6359 return Op == CastOp || hasOperand(CastOp, Op);
6360 }
6361 case scAddRecExpr:
6362 case scAddExpr:
6363 case scMulExpr:
6364 case scUMaxExpr:
6365 case scSMaxExpr: {
6366 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6367 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6368 I != E; ++I) {
6369 const SCEV *NAryOp = *I;
6370 if (NAryOp == Op || hasOperand(NAryOp, Op))
6371 return true;
6372 }
6373 return false;
6374 }
6375 case scUDivExpr: {
6376 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6377 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6378 return LHS == Op || hasOperand(LHS, Op) ||
6379 RHS == Op || hasOperand(RHS, Op);
6380 }
6381 case scUnknown:
6382 return false;
6383 case scCouldNotCompute:
6384 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6385 return false;
6386 default: break;
6387 }
6388 llvm_unreachable("Unknown SCEV kind!");
6389 return false;
6390}
Dan Gohman56a75682010-11-17 23:28:48 +00006391
6392void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6393 ValuesAtScopes.erase(S);
6394 LoopDispositions.erase(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006395 BlockDispositions.erase(S);
Dan Gohman56a75682010-11-17 23:28:48 +00006396 UnsignedRanges.erase(S);
6397 SignedRanges.erase(S);
6398}