blob: 4bb69ddb276a17f95c1400d7d832ebdf6472a9ff [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);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000200 Type *AllocTy;
Dan Gohman4ce32db2010-11-17 22:27:42 +0000201 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000210 Type *CTy;
Dan Gohman4ce32db2010-11-17 22:27:42 +0000211 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000231Type *SCEV::getType() const {
Dan Gohman4ce32db2010-11-17 22:27:42 +0000232 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 *
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000300ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
301 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana560fd22010-04-21 16:04:04 +0000302 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000306 unsigned SCEVTy, const SCEV *op, 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000310 const SCEV *op, 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000318 const SCEV *op, 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000326 const SCEV *op, 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000357bool SCEVUnknown::isSizeOf(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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000374bool SCEVUnknown::isAlignOf(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()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000380 Type *Ty =
Dan Gohman8db08df2010-02-02 01:38:49 +0000381 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000382 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman8db08df2010-02-02 01:38:49 +0000383 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000399bool SCEVUnknown::isOffsetOf(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()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000407 Type *Ty =
Dan Gohman4f8eea82010-02-01 18:27:38 +0000408 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,
Nick Lewycky8cfb2f82011-09-06 06:39:54 +0000655 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000745 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000746 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000793 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000880 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 Trickc343c1e2011-03-15 00:37:00 +0000935 L, AR->getNoWrapFlags());
Dan Gohmaneb490a72009-07-25 01:22:26 +0000936
Dan Gohman01ecca22009-04-27 20:16:15 +0000937 // Check whether the backedge-taken count is SCEVCouldNotCompute.
938 // Note that this serves two purposes: It filters out loops that are
939 // simply not analyzable, and it covers the case where this code is
940 // being called from within backedge-taken count analysis, such that
941 // attempting to ask for the backedge-taken count would likely result
942 // in infinite recursion. In the later case, the analysis code will
943 // cope with a conservative value, and it will take care to purge
944 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000945 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000946 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000947 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000948 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000949
950 // Check whether the backedge-taken count can be losslessly casted to
951 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000952 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000953 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000954 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000955 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
956 if (MaxBECount == RecastedMaxBECount) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000957 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000958 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000959 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000960 const SCEV *Add = getAddExpr(Start, ZMul);
961 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000962 getAddExpr(getZeroExtendExpr(Start, WideTy),
963 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
964 getZeroExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +0000965 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
966 // Cache knowledge of AR NUW, which is propagated to this AddRec.
967 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000968 // Return the expression with the addrec on the outside.
969 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
970 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +0000971 L, AR->getNoWrapFlags());
972 }
Dan Gohman01ecca22009-04-27 20:16:15 +0000973 // 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)));
Andrew Trickc343c1e2011-03-15 00:37:00 +0000981 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
982 // Cache knowledge of AR NW, which is propagated to this AddRec.
983 // Negative step causes unsigned wrap, but it still can't self-wrap.
984 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000985 // Return the expression with the addrec on the outside.
986 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
987 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +0000988 L, AR->getNoWrapFlags());
989 }
Dan Gohman85b05a22009-07-13 21:35:55 +0000990 }
991
992 // If the backedge is guarded by a comparison with the pre-inc value
993 // the addrec is safe. Also, if the entry is guarded by a comparison
994 // with the start value and the backedge is guarded by a comparison
995 // with the post-inc value, the addrec is safe.
996 if (isKnownPositive(Step)) {
997 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
998 getUnsignedRange(Step).getUnsignedMax());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001000 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickc343c1e2011-03-15 00:37:00 +00001002 AR->getPostIncExpr(*this), N))) {
1003 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1004 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman85b05a22009-07-13 21:35:55 +00001005 // Return the expression with the addrec on the outside.
1006 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1007 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001008 L, AR->getNoWrapFlags());
1009 }
Dan Gohman85b05a22009-07-13 21:35:55 +00001010 } else if (isKnownNegative(Step)) {
1011 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1012 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +00001013 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1014 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001015 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickc343c1e2011-03-15 00:37:00 +00001016 AR->getPostIncExpr(*this), N))) {
1017 // Cache knowledge of AR NW, which is propagated to this AddRec.
1018 // Negative step causes unsigned wrap, but it still can't self-wrap.
1019 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1020 // Return the expression with the addrec on the outside.
Dan Gohman85b05a22009-07-13 21:35:55 +00001021 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1022 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001023 L, AR->getNoWrapFlags());
1024 }
Dan Gohman01ecca22009-04-27 20:16:15 +00001025 }
1026 }
1027 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001028
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001029 // The cast wasn't folded; create an explicit cast node.
1030 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001031 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001032 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1033 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001034 UniqueSCEVs.InsertNode(S, IP);
1035 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001036}
1037
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001038// Get the limit of a recurrence such that incrementing by Step cannot cause
1039// signed overflow as long as the value of the recurrence within the loop does
1040// not exceed this limit before incrementing.
1041static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1042 ICmpInst::Predicate *Pred,
1043 ScalarEvolution *SE) {
1044 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1045 if (SE->isKnownPositive(Step)) {
1046 *Pred = ICmpInst::ICMP_SLT;
1047 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1048 SE->getSignedRange(Step).getSignedMax());
1049 }
1050 if (SE->isKnownNegative(Step)) {
1051 *Pred = ICmpInst::ICMP_SGT;
1052 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1053 SE->getSignedRange(Step).getSignedMin());
1054 }
1055 return 0;
1056}
1057
1058// The recurrence AR has been shown to have no signed wrap. Typically, if we can
1059// prove NSW for AR, then we can just as easily prove NSW for its preincrement
1060// or postincrement sibling. This allows normalizing a sign extended AddRec as
1061// such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1062// result, the expression "Step + sext(PreIncAR)" is congruent with
1063// "sext(PostIncAR)"
1064static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001065 Type *Ty,
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001066 ScalarEvolution *SE) {
1067 const Loop *L = AR->getLoop();
1068 const SCEV *Start = AR->getStart();
1069 const SCEV *Step = AR->getStepRecurrence(*SE);
1070
1071 // Check for a simple looking step prior to loop entry.
1072 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1073 if (!SA || SA->getNumOperands() != 2 || SA->getOperand(0) != Step)
1074 return 0;
1075
1076 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1077 // same three conditions that getSignExtendedExpr checks.
1078
1079 // 1. NSW flags on the step increment.
1080 const SCEV *PreStart = SA->getOperand(1);
1081 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1082 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1083
Andrew Trickcf31f912011-06-01 19:14:56 +00001084 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001085 return PreStart;
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001086
1087 // 2. Direct overflow check on the step operation's expression.
1088 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001089 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001090 const SCEV *OperandExtendedStart =
1091 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1092 SE->getSignExtendExpr(Step, WideTy));
1093 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1094 // Cache knowledge of PreAR NSW.
1095 if (PreAR)
1096 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1097 // FIXME: this optimization needs a unit test
1098 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1099 return PreStart;
1100 }
1101
1102 // 3. Loop precondition.
1103 ICmpInst::Predicate Pred;
1104 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1105
Andrew Trickcf31f912011-06-01 19:14:56 +00001106 if (OverflowLimit &&
1107 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001108 return PreStart;
1109 }
1110 return 0;
1111}
1112
1113// Get the normalized sign-extended expression for this AddRec's Start.
1114static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001115 Type *Ty,
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001116 ScalarEvolution *SE) {
1117 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1118 if (!PreStart)
1119 return SE->getSignExtendExpr(AR->getStart(), Ty);
1120
1121 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1122 SE->getSignExtendExpr(PreStart, Ty));
1123}
1124
Dan Gohman0bba49c2009-07-07 17:06:11 +00001125const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001126 Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001127 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001128 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001129 assert(isSCEVable(Ty) &&
1130 "This is not a conversion to a SCEVable type!");
1131 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001132
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001133 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001134 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1135 return getConstant(
1136 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1137 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001138
Dan Gohman20900ca2009-04-22 16:20:48 +00001139 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001140 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001141 return getSignExtendExpr(SS->getOperand(), Ty);
1142
Nick Lewycky73f565e2011-01-19 15:56:12 +00001143 // sext(zext(x)) --> zext(x)
1144 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1145 return getZeroExtendExpr(SZ->getOperand(), Ty);
1146
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001147 // Before doing any expensive analysis, check to see if we've already
1148 // computed a SCEV for this Op and Ty.
1149 FoldingSetNodeID ID;
1150 ID.AddInteger(scSignExtend);
1151 ID.AddPointer(Op);
1152 ID.AddPointer(Ty);
1153 void *IP = 0;
1154 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1155
Nick Lewycky9b8d2c22011-01-22 22:06:21 +00001156 // If the input value is provably positive, build a zext instead.
1157 if (isKnownNonNegative(Op))
1158 return getZeroExtendExpr(Op, Ty);
1159
Nick Lewycky630d85a2011-01-23 06:20:19 +00001160 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1161 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1162 // It's possible the bits taken off by the truncate were all sign bits. If
1163 // so, we should be able to simplify this further.
1164 const SCEV *X = ST->getOperand();
1165 ConstantRange CR = getSignedRange(X);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001166 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1167 unsigned NewBits = getTypeSizeInBits(Ty);
1168 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewycky76167af2011-01-23 20:06:05 +00001169 CR.sextOrTrunc(NewBits)))
1170 return getTruncateOrSignExtend(X, Ty);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001171 }
1172
Dan Gohman01ecca22009-04-27 20:16:15 +00001173 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001174 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001175 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001176 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001177 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001178 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001179 const SCEV *Start = AR->getStart();
1180 const SCEV *Step = AR->getStepRecurrence(*this);
1181 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1182 const Loop *L = AR->getLoop();
1183
Dan Gohmaneb490a72009-07-25 01:22:26 +00001184 // If we have special knowledge that this addrec won't overflow,
1185 // we don't need to do any further analysis.
Andrew Trick3228cc22011-03-14 16:50:06 +00001186 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001187 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohmaneb490a72009-07-25 01:22:26 +00001188 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001189 L, SCEV::FlagNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00001190
Dan Gohman01ecca22009-04-27 20:16:15 +00001191 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1192 // Note that this serves two purposes: It filters out loops that are
1193 // simply not analyzable, and it covers the case where this code is
1194 // being called from within backedge-taken count analysis, such that
1195 // attempting to ask for the backedge-taken count would likely result
1196 // in infinite recursion. In the later case, the analysis code will
1197 // cope with a conservative value, and it will take care to purge
1198 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001199 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001200 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001201 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001202 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001203
1204 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001205 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001206 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001207 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001208 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001209 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1210 if (MaxBECount == RecastedMaxBECount) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001211 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001212 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001213 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001214 const SCEV *Add = getAddExpr(Start, SMul);
1215 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001216 getAddExpr(getSignExtendExpr(Start, WideTy),
1217 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1218 getSignExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001219 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1220 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1221 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohmanac70cea2009-04-29 22:28:28 +00001222 // Return the expression with the addrec on the outside.
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001223 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohmanac70cea2009-04-29 22:28:28 +00001224 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001225 L, AR->getNoWrapFlags());
1226 }
Dan Gohman850f7912009-07-16 17:34:36 +00001227 // Similar to above, only this time treat the step value as unsigned.
1228 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001229 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001230 Add = getAddExpr(Start, UMul);
1231 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001232 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001233 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1234 getZeroExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001235 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1236 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1237 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman850f7912009-07-16 17:34:36 +00001238 // Return the expression with the addrec on the outside.
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001239 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman850f7912009-07-16 17:34:36 +00001240 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001241 L, AR->getNoWrapFlags());
1242 }
Dan Gohman85b05a22009-07-13 21:35:55 +00001243 }
1244
1245 // If the backedge is guarded by a comparison with the pre-inc value
1246 // the addrec is safe. Also, if the entry is guarded by a comparison
1247 // with the start value and the backedge is guarded by a comparison
1248 // with the post-inc value, the addrec is safe.
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001249 ICmpInst::Predicate Pred;
1250 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1251 if (OverflowLimit &&
1252 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1253 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1254 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1255 OverflowLimit)))) {
1256 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1257 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1258 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1259 getSignExtendExpr(Step, Ty),
1260 L, AR->getNoWrapFlags());
Dan Gohman01ecca22009-04-27 20:16:15 +00001261 }
1262 }
1263 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001264
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001265 // The cast wasn't folded; create an explicit cast node.
1266 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001268 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1269 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001270 UniqueSCEVs.InsertNode(S, IP);
1271 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001272}
1273
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001274/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1275/// unspecified bits out to the given type.
1276///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001277const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001278 Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001279 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1280 "This is not an extending conversion!");
1281 assert(isSCEVable(Ty) &&
1282 "This is not a conversion to a SCEVable type!");
1283 Ty = getEffectiveSCEVType(Ty);
1284
1285 // Sign-extend negative constants.
1286 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1287 if (SC->getValue()->getValue().isNegative())
1288 return getSignExtendExpr(Op, Ty);
1289
1290 // Peel off a truncate cast.
1291 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001292 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001293 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1294 return getAnyExtendExpr(NewOp, Ty);
1295 return getTruncateOrNoop(NewOp, Ty);
1296 }
1297
1298 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001299 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001300 if (!isa<SCEVZeroExtendExpr>(ZExt))
1301 return ZExt;
1302
1303 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001304 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001305 if (!isa<SCEVSignExtendExpr>(SExt))
1306 return SExt;
1307
Dan Gohmana10756e2010-01-21 02:09:26 +00001308 // Force the cast to be folded into the operands of an addrec.
1309 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1310 SmallVector<const SCEV *, 4> Ops;
1311 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1312 I != E; ++I)
1313 Ops.push_back(getAnyExtendExpr(*I, Ty));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001314 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohmana10756e2010-01-21 02:09:26 +00001315 }
1316
Dan Gohmanf53462d2010-07-15 20:02:11 +00001317 // As a special case, fold anyext(undef) to undef. We don't want to
1318 // know too much about SCEVUnknowns, but this special case is handy
1319 // and harmless.
1320 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1321 if (isa<UndefValue>(U->getValue()))
1322 return getSCEV(UndefValue::get(Ty));
1323
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001324 // If the expression is obviously signed, use the sext cast value.
1325 if (isa<SCEVSMaxExpr>(Op))
1326 return SExt;
1327
1328 // Absent any other information, use the zext cast value.
1329 return ZExt;
1330}
1331
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001332/// CollectAddOperandsWithScales - Process the given Ops list, which is
1333/// a list of operands to be added under the given scale, update the given
1334/// map. This is a helper function for getAddRecExpr. As an example of
1335/// what it does, given a sequence of operands that would form an add
1336/// expression like this:
1337///
1338/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1339///
1340/// where A and B are constants, update the map with these values:
1341///
1342/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1343///
1344/// and add 13 + A*B*29 to AccumulatedConstant.
1345/// This will allow getAddRecExpr to produce this:
1346///
1347/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1348///
1349/// This form often exposes folding opportunities that are hidden in
1350/// the original operand list.
1351///
1352/// Return true iff it appears that any interesting folding opportunities
1353/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1354/// the common case where no interesting opportunities are present, and
1355/// is also used as a check to avoid infinite recursion.
1356///
1357static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001358CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1359 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001360 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001361 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001362 const APInt &Scale,
1363 ScalarEvolution &SE) {
1364 bool Interesting = false;
1365
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001366 // Iterate over the add operands. They are sorted, with constants first.
1367 unsigned i = 0;
1368 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1369 ++i;
1370 // Pull a buried constant out to the outside.
1371 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1372 Interesting = true;
1373 AccumulatedConstant += Scale * C->getValue()->getValue();
1374 }
1375
1376 // Next comes everything else. We're especially interested in multiplies
1377 // here, but they're in the middle, so just visit the rest with one loop.
1378 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001379 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1380 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1381 APInt NewScale =
1382 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1383 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1384 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001385 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001386 Interesting |=
1387 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001388 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001389 NewScale, SE);
1390 } else {
1391 // A multiplication of a constant with some other value. Update
1392 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001393 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1394 const SCEV *Key = SE.getMulExpr(MulOps);
1395 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001396 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001397 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001398 NewOps.push_back(Pair.first->first);
1399 } else {
1400 Pair.first->second += NewScale;
1401 // The map already had an entry for this value, which may indicate
1402 // a folding opportunity.
1403 Interesting = true;
1404 }
1405 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001406 } else {
1407 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001408 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001409 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001410 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001411 NewOps.push_back(Pair.first->first);
1412 } else {
1413 Pair.first->second += Scale;
1414 // The map already had an entry for this value, which may indicate
1415 // a folding opportunity.
1416 Interesting = true;
1417 }
1418 }
1419 }
1420
1421 return Interesting;
1422}
1423
1424namespace {
1425 struct APIntCompare {
1426 bool operator()(const APInt &LHS, const APInt &RHS) const {
1427 return LHS.ult(RHS);
1428 }
1429 };
1430}
1431
Dan Gohman6c0866c2009-05-24 23:45:28 +00001432/// getAddExpr - Get a canonical add expression, or something simpler if
1433/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001434const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001435 SCEV::NoWrapFlags Flags) {
1436 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1437 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001438 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001439 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001440#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001441 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001442 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001443 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001444 "SCEVAddExpr operand types don't match!");
1445#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001446
Andrew Trick3228cc22011-03-14 16:50:06 +00001447 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001448 // And vice-versa.
1449 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1450 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1451 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001452 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001453 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1454 E = Ops.end(); I != E; ++I)
1455 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001456 All = false;
1457 break;
1458 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00001459 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00001460 }
1461
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001463 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001464
1465 // If there are any constants, fold them together.
1466 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001467 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001469 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001470 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001472 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1473 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001474 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001475 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001476 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 }
1478
1479 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001480 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 Ops.erase(Ops.begin());
1482 --Idx;
1483 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001484
Dan Gohmanbca091d2010-04-12 23:08:18 +00001485 if (Ops.size() == 1) return Ops[0];
1486 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001487
Dan Gohman68ff7762010-08-27 21:39:59 +00001488 // Okay, check to see if the same value occurs in the operand list more than
1489 // once. If so, merge them together into an multiply expression. Since we
1490 // sorted the list, these values are required to be adjacent.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001491 Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001492 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001493 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001495 // Scan ahead to count how many equal operands there are.
1496 unsigned Count = 2;
1497 while (i+Count != e && Ops[i+Count] == Ops[i])
1498 ++Count;
1499 // Merge the values into a multiply.
1500 const SCEV *Scale = getConstant(Ty, Count);
1501 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1502 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001504 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001505 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001506 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001507 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001509 if (FoundMatch)
Andrew Trick3228cc22011-03-14 16:50:06 +00001510 return getAddExpr(Ops, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001511
Dan Gohman728c7f32009-05-08 21:03:19 +00001512 // Check for truncates. If all the operands are truncated from the same
1513 // type, see if factoring out the truncate would permit the result to be
1514 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1515 // if the contents of the resulting outer trunc fold to something simple.
1516 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1517 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001518 Type *DstType = Trunc->getType();
1519 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001520 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001521 bool Ok = true;
1522 // Check all the operands to see if they can be represented in the
1523 // source type of the truncate.
1524 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1525 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1526 if (T->getOperand()->getType() != SrcType) {
1527 Ok = false;
1528 break;
1529 }
1530 LargeOps.push_back(T->getOperand());
1531 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001532 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001533 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001534 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001535 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1536 if (const SCEVTruncateExpr *T =
1537 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1538 if (T->getOperand()->getType() != SrcType) {
1539 Ok = false;
1540 break;
1541 }
1542 LargeMulOps.push_back(T->getOperand());
1543 } else if (const SCEVConstant *C =
1544 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001545 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001546 } else {
1547 Ok = false;
1548 break;
1549 }
1550 }
1551 if (Ok)
1552 LargeOps.push_back(getMulExpr(LargeMulOps));
1553 } else {
1554 Ok = false;
1555 break;
1556 }
1557 }
1558 if (Ok) {
1559 // Evaluate the expression in the larger type.
Andrew Trick3228cc22011-03-14 16:50:06 +00001560 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman728c7f32009-05-08 21:03:19 +00001561 // If it folds to something simple, use it. Otherwise, don't.
1562 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1563 return getTruncateExpr(Fold, DstType);
1564 }
1565 }
1566
1567 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001568 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1569 ++Idx;
1570
1571 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 if (Idx < Ops.size()) {
1573 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001574 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 // If we have an add, expand the add operands onto the end of the operands
1576 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001577 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001578 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 DeletedAdd = true;
1580 }
1581
1582 // If we deleted at least one add, we added operands to the end of the list,
1583 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001584 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001585 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001586 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 }
1588
1589 // Skip over the add expression until we get to a multiply.
1590 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1591 ++Idx;
1592
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001593 // Check to see if there are any folding opportunities present with
1594 // operands multiplied by constant values.
1595 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1596 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001597 DenseMap<const SCEV *, APInt> M;
1598 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001599 APInt AccumulatedConstant(BitWidth, 0);
1600 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001601 Ops.data(), Ops.size(),
1602 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001603 // Some interesting folding opportunity is present, so its worthwhile to
1604 // re-generate the operands list. Group the operands by constant scale,
1605 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001606 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001607 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001608 E = NewOps.end(); I != E; ++I)
1609 MulOpLists[M.find(*I)->second].push_back(*I);
1610 // Re-generate the operands list.
1611 Ops.clear();
1612 if (AccumulatedConstant != 0)
1613 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001614 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1615 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001616 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001617 Ops.push_back(getMulExpr(getConstant(I->first),
1618 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001619 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001620 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001621 if (Ops.size() == 1)
1622 return Ops[0];
1623 return getAddExpr(Ops);
1624 }
1625 }
1626
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 // If we are adding something to a multiply expression, make sure the
1628 // something is not already an operand of the multiply. If so, merge it into
1629 // the multiply.
1630 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001631 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001632 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001633 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001634 if (isa<SCEVConstant>(MulOpSCEV))
1635 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001636 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001637 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001638 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001639 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001640 if (Mul->getNumOperands() != 2) {
1641 // If the multiply has more than two operands, we must get the
1642 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001643 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1644 Mul->op_begin()+MulOp);
1645 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001646 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001647 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001648 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001649 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001650 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001651 if (Ops.size() == 2) return OuterMul;
1652 if (AddOp < Idx) {
1653 Ops.erase(Ops.begin()+AddOp);
1654 Ops.erase(Ops.begin()+Idx-1);
1655 } else {
1656 Ops.erase(Ops.begin()+Idx);
1657 Ops.erase(Ops.begin()+AddOp-1);
1658 }
1659 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001660 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001661 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001662
Chris Lattner53e677a2004-04-02 20:23:17 +00001663 // Check this multiply against other multiplies being added together.
1664 for (unsigned OtherMulIdx = Idx+1;
1665 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1666 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001667 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001668 // If MulOp occurs in OtherMul, we can fold the two multiplies
1669 // together.
1670 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1671 OMulOp != e; ++OMulOp)
1672 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1673 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001674 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001675 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001676 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001677 Mul->op_begin()+MulOp);
1678 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001679 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001681 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001683 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001684 OtherMul->op_begin()+OMulOp);
1685 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001686 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001688 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1689 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001690 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001691 Ops.erase(Ops.begin()+Idx);
1692 Ops.erase(Ops.begin()+OtherMulIdx-1);
1693 Ops.push_back(OuterMul);
1694 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001695 }
1696 }
1697 }
1698 }
1699
1700 // If there are any add recurrences in the operands list, see if any other
1701 // added values are loop invariant. If so, we can fold them into the
1702 // recurrence.
1703 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1704 ++Idx;
1705
1706 // Scan over all recurrences, trying to fold loop invariants into them.
1707 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1708 // Scan all of the other operands to this add and add them to the vector if
1709 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001710 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001711 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001712 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001713 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001714 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 LIOps.push_back(Ops[i]);
1716 Ops.erase(Ops.begin()+i);
1717 --i; --e;
1718 }
1719
1720 // If we found some loop invariants, fold them into the recurrence.
1721 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001722 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 LIOps.push_back(AddRec->getStart());
1724
Dan Gohman0bba49c2009-07-07 17:06:11 +00001725 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001726 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001727 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001728
Dan Gohmanb9f96512010-06-30 07:16:37 +00001729 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher87376832011-01-11 09:02:09 +00001730 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001731 // Always propagate NW.
1732 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick3228cc22011-03-14 16:50:06 +00001733 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman59de33e2009-12-18 18:45:31 +00001734
Chris Lattner53e677a2004-04-02 20:23:17 +00001735 // If all of the other operands were loop invariant, we are done.
1736 if (Ops.size() == 1) return NewRec;
1737
Nick Lewycky980e9f32011-09-06 05:08:09 +00001738 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattner53e677a2004-04-02 20:23:17 +00001739 for (unsigned i = 0;; ++i)
1740 if (Ops[i] == AddRec) {
1741 Ops[i] = NewRec;
1742 break;
1743 }
Dan Gohman246b2562007-10-22 18:31:58 +00001744 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 }
1746
1747 // Okay, if there weren't any loop invariants to be folded, check to see if
1748 // there are multiple AddRec's with the same loop induction variable being
1749 // added together. If so, we can fold them.
1750 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001751 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1752 ++OtherIdx)
1753 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1754 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1755 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1756 AddRec->op_end());
1757 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1758 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001759 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001760 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001761 if (OtherAddRec->getLoop() == AddRecLoop) {
1762 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1763 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001764 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001765 AddRecOps.append(OtherAddRec->op_begin()+i,
1766 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001767 break;
1768 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001769 AddRecOps[i] = getAddExpr(AddRecOps[i],
1770 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001771 }
1772 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001773 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001774 // Step size has changed, so we cannot guarantee no self-wraparound.
1775 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohman32527152010-08-27 20:45:56 +00001776 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 }
1778
1779 // Otherwise couldn't fold anything into this recurrence. Move onto the
1780 // next one.
1781 }
1782
1783 // Okay, it looks like we really DO need an add expr. Check to see if we
1784 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001785 FoldingSetNodeID ID;
1786 ID.AddInteger(scAddExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001787 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1788 ID.AddPointer(Ops[i]);
1789 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001790 SCEVAddExpr *S =
1791 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1792 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001793 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1794 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001795 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1796 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001797 UniqueSCEVs.InsertNode(S, IP);
1798 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001799 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001800 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001801}
1802
Dan Gohman6c0866c2009-05-24 23:45:28 +00001803/// getMulExpr - Get a canonical multiply expression, or something simpler if
1804/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001805const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001806 SCEV::NoWrapFlags Flags) {
1807 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1808 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001809 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001810 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001811#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001812 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001813 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001814 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001815 "SCEVMulExpr operand types don't match!");
1816#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001817
Andrew Trick3228cc22011-03-14 16:50:06 +00001818 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001819 // And vice-versa.
1820 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1821 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1822 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001823 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001824 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1825 E = Ops.end(); I != E; ++I)
1826 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001827 All = false;
1828 break;
1829 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00001830 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00001831 }
1832
Chris Lattner53e677a2004-04-02 20:23:17 +00001833 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001834 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001835
1836 // If there are any constants, fold them together.
1837 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001838 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001839
1840 // C1*(C2+V) -> C1*C2 + C1*V
1841 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001842 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001843 if (Add->getNumOperands() == 2 &&
1844 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001845 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1846 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001847
Chris Lattner53e677a2004-04-02 20:23:17 +00001848 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001849 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001850 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001851 ConstantInt *Fold = ConstantInt::get(getContext(),
1852 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001853 RHSC->getValue()->getValue());
1854 Ops[0] = getConstant(Fold);
1855 Ops.erase(Ops.begin()+1); // Erase the folded element
1856 if (Ops.size() == 1) return Ops[0];
1857 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001858 }
1859
1860 // If we are left with a constant one being multiplied, strip it off.
1861 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1862 Ops.erase(Ops.begin());
1863 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001864 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001865 // If we have a multiply of zero, it will always be zero.
1866 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001867 } else if (Ops[0]->isAllOnesValue()) {
1868 // If we have a mul by -1 of an add, try distributing the -1 among the
1869 // add operands.
Andrew Trick3228cc22011-03-14 16:50:06 +00001870 if (Ops.size() == 2) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001871 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1872 SmallVector<const SCEV *, 4> NewOps;
1873 bool AnyFolded = false;
Andrew Trick3228cc22011-03-14 16:50:06 +00001874 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1875 E = Add->op_end(); I != E; ++I) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001876 const SCEV *Mul = getMulExpr(Ops[0], *I);
1877 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1878 NewOps.push_back(Mul);
1879 }
1880 if (AnyFolded)
1881 return getAddExpr(NewOps);
1882 }
Andrew Tricka053b212011-03-14 17:38:54 +00001883 else if (const SCEVAddRecExpr *
1884 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1885 // Negation preserves a recurrence's no self-wrap property.
1886 SmallVector<const SCEV *, 4> Operands;
1887 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1888 E = AddRec->op_end(); I != E; ++I) {
1889 Operands.push_back(getMulExpr(Ops[0], *I));
1890 }
1891 return getAddRecExpr(Operands, AddRec->getLoop(),
1892 AddRec->getNoWrapFlags(SCEV::FlagNW));
1893 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001894 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001895 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001896
1897 if (Ops.size() == 1)
1898 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001899 }
1900
1901 // Skip over the add expression until we get to a multiply.
1902 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1903 ++Idx;
1904
Chris Lattner53e677a2004-04-02 20:23:17 +00001905 // If there are mul operands inline them all into this expression.
1906 if (Idx < Ops.size()) {
1907 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001908 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001909 // If we have an mul, expand the mul operands onto the end of the operands
1910 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001911 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001912 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001913 DeletedMul = true;
1914 }
1915
1916 // If we deleted at least one mul, we added operands to the end of the list,
1917 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001918 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001919 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001920 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001921 }
1922
1923 // If there are any add recurrences in the operands list, see if any other
1924 // added values are loop invariant. If so, we can fold them into the
1925 // recurrence.
1926 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1927 ++Idx;
1928
1929 // Scan over all recurrences, trying to fold loop invariants into them.
1930 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1931 // Scan all of the other operands to this mul and add them to the vector if
1932 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001933 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001934 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001935 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001936 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001937 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001938 LIOps.push_back(Ops[i]);
1939 Ops.erase(Ops.begin()+i);
1940 --i; --e;
1941 }
1942
1943 // If we found some loop invariants, fold them into the recurrence.
1944 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001945 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001946 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001947 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001948 const SCEV *Scale = getMulExpr(LIOps);
1949 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1950 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001951
Dan Gohmanb9f96512010-06-30 07:16:37 +00001952 // Build the new addrec. Propagate the NUW and NSW flags if both the
1953 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick3228cc22011-03-14 16:50:06 +00001954 //
1955 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001956 // will be inferred if either NUW or NSW is true.
Andrew Trick3228cc22011-03-14 16:50:06 +00001957 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1958 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001959
1960 // If all of the other operands were loop invariant, we are done.
1961 if (Ops.size() == 1) return NewRec;
1962
Nick Lewycky980e9f32011-09-06 05:08:09 +00001963 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattner53e677a2004-04-02 20:23:17 +00001964 for (unsigned i = 0;; ++i)
1965 if (Ops[i] == AddRec) {
1966 Ops[i] = NewRec;
1967 break;
1968 }
Dan Gohman246b2562007-10-22 18:31:58 +00001969 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001970 }
1971
1972 // Okay, if there weren't any loop invariants to be folded, check to see if
1973 // there are multiple AddRec's with the same loop induction variable being
1974 // multiplied together. If so, we can fold them.
1975 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001976 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1977 ++OtherIdx)
1978 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
Nick Lewycky8cfb2f82011-09-06 06:39:54 +00001979 // {A,+,B}<L> * {C,+,D}<L> --> {A*C,+,A*D + B*C + B*D,+,2*B*D}<L>
Nick Lewycky28682ae2011-09-06 05:33:18 +00001980 //
Nick Lewycky8cfb2f82011-09-06 06:39:54 +00001981 // {A,+,B} * {C,+,D} = A+It*B * C+It*D = A*C + (A*D + B*C)*It + B*D*It^2
1982 // Given an equation of the form x + y*It + z*It^2 (above), we want to
1983 // express it in terms of {X,+,Y,+,Z}.
1984 // {X,+,Y,+,Z} = X + Y*It + Z*(It^2 - It)/2.
Nick Lewyckye6180992011-09-06 06:46:01 +00001985 // Rearranging, X = x, Y = y+z, Z = 2z.
Nick Lewycky28682ae2011-09-06 05:33:18 +00001986 //
Nick Lewycky8cfb2f82011-09-06 06:39:54 +00001987 // x = A*C, y = (A*D + B*C), z = B*D.
Nick Lewycky28682ae2011-09-06 05:33:18 +00001988 // Therefore X = A*C, Y = (A*D + B*C) - B*D and Z = 2*B*D.
Dan Gohman6a0c1252010-08-31 22:52:12 +00001989 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1990 ++OtherIdx)
1991 if (const SCEVAddRecExpr *OtherAddRec =
1992 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1993 if (OtherAddRec->getLoop() == AddRecLoop) {
Nick Lewyckyfa151a72011-09-06 05:05:14 +00001994 const SCEV *A = AddRec->getStart();
1995 const SCEV *B = AddRec->getStepRecurrence(*this);
1996 const SCEV *C = OtherAddRec->getStart();
1997 const SCEV *D = OtherAddRec->getStepRecurrence(*this);
1998 const SCEV *NewStart = getMulExpr(A, C);
1999 const SCEV *BD = getMulExpr(B, D);
2000 const SCEV *NewStep = getAddExpr(getMulExpr(A, D),
Nick Lewycky28682ae2011-09-06 05:33:18 +00002001 getMulExpr(B, C),
2002 getNegativeSCEV(BD));
Nick Lewyckyfa151a72011-09-06 05:05:14 +00002003 const SCEV *NewSecondOrderStep =
2004 getMulExpr(BD, getConstant(BD->getType(), 2));
2005
2006 SmallVector<const SCEV *, 3> AddRecOps;
2007 AddRecOps.push_back(NewStart);
2008 AddRecOps.push_back(NewStep);
2009 AddRecOps.push_back(NewSecondOrderStep);
2010 const SCEV *NewAddRec = getAddRecExpr(AddRecOps,
2011 AddRec->getLoop(),
Andrew Trick3228cc22011-03-14 16:50:06 +00002012 SCEV::FlagAnyWrap);
Dan Gohman6a0c1252010-08-31 22:52:12 +00002013 if (Ops.size() == 2) return NewAddRec;
2014 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
2015 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2016 }
2017 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002018 }
2019
2020 // Otherwise couldn't fold anything into this recurrence. Move onto the
2021 // next one.
2022 }
2023
2024 // Okay, it looks like we really DO need an mul expr. Check to see if we
2025 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002026 FoldingSetNodeID ID;
2027 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002028 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2029 ID.AddPointer(Ops[i]);
2030 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002031 SCEVMulExpr *S =
2032 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2033 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002034 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2035 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002036 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2037 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00002038 UniqueSCEVs.InsertNode(S, IP);
2039 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002040 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002041 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002042}
2043
Andreas Bolka8a11c982009-08-07 22:55:26 +00002044/// getUDivExpr - Get a canonical unsigned division expression, or something
2045/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00002046const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2047 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00002048 assert(getEffectiveSCEVType(LHS->getType()) ==
2049 getEffectiveSCEVType(RHS->getType()) &&
2050 "SCEVUDivExpr operand types don't match!");
2051
Dan Gohman622ed672009-05-04 22:02:23 +00002052 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002053 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00002054 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002055 // If the denominator is zero, the result of the udiv is undefined. Don't
2056 // try to analyze it, because the resolution chosen here may differ from
2057 // the resolution chosen in other parts of the compiler.
2058 if (!RHSC->getValue()->isZero()) {
2059 // Determine if the division can be folded into the operands of
2060 // its operands.
2061 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002062 Type *Ty = LHS->getType();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002063 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00002064 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002065 // For non-power-of-two values, effectively round the value up to the
2066 // nearest power of two.
2067 if (!RHSC->getValue()->getValue().isPowerOf2())
2068 ++MaxShiftAmt;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002069 IntegerType *ExtTy =
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002070 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002071 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2072 if (const SCEVConstant *Step =
Andrew Trick06988bc2011-08-06 07:00:37 +00002073 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2074 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2075 const APInt &StepInt = Step->getValue()->getValue();
2076 const APInt &DivInt = RHSC->getValue()->getValue();
2077 if (!StepInt.urem(DivInt) &&
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002078 getZeroExtendExpr(AR, ExtTy) ==
2079 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2080 getZeroExtendExpr(Step, ExtTy),
Andrew Trick3228cc22011-03-14 16:50:06 +00002081 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002082 SmallVector<const SCEV *, 4> Operands;
2083 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2084 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick3228cc22011-03-14 16:50:06 +00002085 return getAddRecExpr(Operands, AR->getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00002086 SCEV::FlagNW);
Dan Gohman185cf032009-05-08 20:18:49 +00002087 }
Andrew Trick06988bc2011-08-06 07:00:37 +00002088 /// Get a canonical UDivExpr for a recurrence.
2089 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2090 // We can currently only fold X%N if X is constant.
2091 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2092 if (StartC && !DivInt.urem(StepInt) &&
2093 getZeroExtendExpr(AR, ExtTy) ==
2094 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2095 getZeroExtendExpr(Step, ExtTy),
2096 AR->getLoop(), SCEV::FlagAnyWrap)) {
2097 const APInt &StartInt = StartC->getValue()->getValue();
2098 const APInt &StartRem = StartInt.urem(StepInt);
2099 if (StartRem != 0)
2100 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2101 AR->getLoop(), SCEV::FlagNW);
2102 }
2103 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002104 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2105 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2106 SmallVector<const SCEV *, 4> Operands;
2107 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2108 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2109 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2110 // Find an operand that's safely divisible.
2111 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2112 const SCEV *Op = M->getOperand(i);
2113 const SCEV *Div = getUDivExpr(Op, RHSC);
2114 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2115 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2116 M->op_end());
2117 Operands[i] = Div;
2118 return getMulExpr(Operands);
2119 }
2120 }
Dan Gohman185cf032009-05-08 20:18:49 +00002121 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002122 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Andrew Tricka2a16202011-04-27 18:17:36 +00002123 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002124 SmallVector<const SCEV *, 4> Operands;
2125 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2126 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2127 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2128 Operands.clear();
2129 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2130 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2131 if (isa<SCEVUDivExpr>(Op) ||
2132 getMulExpr(Op, RHS) != A->getOperand(i))
2133 break;
2134 Operands.push_back(Op);
2135 }
2136 if (Operands.size() == A->getNumOperands())
2137 return getAddExpr(Operands);
2138 }
2139 }
Dan Gohman185cf032009-05-08 20:18:49 +00002140
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002141 // Fold if both operands are constant.
2142 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2143 Constant *LHSCV = LHSC->getValue();
2144 Constant *RHSCV = RHSC->getValue();
2145 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2146 RHSCV)));
2147 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002148 }
2149 }
2150
Dan Gohman1c343752009-06-27 21:21:31 +00002151 FoldingSetNodeID ID;
2152 ID.AddInteger(scUDivExpr);
2153 ID.AddPointer(LHS);
2154 ID.AddPointer(RHS);
2155 void *IP = 0;
2156 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00002157 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2158 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00002159 UniqueSCEVs.InsertNode(S, IP);
2160 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002161}
2162
2163
Dan Gohman6c0866c2009-05-24 23:45:28 +00002164/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2165/// Simplify the expression as much as possible.
Andrew Trick3228cc22011-03-14 16:50:06 +00002166const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2167 const Loop *L,
2168 SCEV::NoWrapFlags Flags) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002169 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002170 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002171 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002172 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002173 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickc343c1e2011-03-15 00:37:00 +00002174 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattner53e677a2004-04-02 20:23:17 +00002175 }
2176
2177 Operands.push_back(Step);
Andrew Trick3228cc22011-03-14 16:50:06 +00002178 return getAddRecExpr(Operands, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002179}
2180
Dan Gohman6c0866c2009-05-24 23:45:28 +00002181/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2182/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002183const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002184ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick3228cc22011-03-14 16:50:06 +00002185 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002186 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002187#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002188 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002189 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002190 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002191 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00002192 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002193 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00002194 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00002195#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002196
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002197 if (Operands.back()->isZero()) {
2198 Operands.pop_back();
Andrew Trick3228cc22011-03-14 16:50:06 +00002199 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002200 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002201
Dan Gohmanbc028532010-02-19 18:49:22 +00002202 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2203 // use that information to infer NUW and NSW flags. However, computing a
2204 // BE count requires calling getAddRecExpr, so we may not yet have a
2205 // meaningful BE count at this point (and if we don't, we'd be stuck
2206 // with a SCEVCouldNotCompute as the cached BE count).
2207
Andrew Trick3228cc22011-03-14 16:50:06 +00002208 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002209 // And vice-versa.
2210 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2211 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2212 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002213 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00002214 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2215 E = Operands.end(); I != E; ++I)
2216 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002217 All = false;
2218 break;
2219 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00002220 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00002221 }
2222
Dan Gohmand9cc7492008-08-08 18:33:12 +00002223 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002224 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002225 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002226 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002227 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002228 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002229 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002230 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002231 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002232 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002233 // AddRecs require their operands be loop-invariant with respect to their
2234 // loops. Don't perform this transformation if it would break this
2235 // requirement.
2236 bool AllInvariant = true;
2237 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002238 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002239 AllInvariant = false;
2240 break;
2241 }
2242 if (AllInvariant) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002243 // Create a recurrence for the outer loop with the same step size.
2244 //
Andrew Trick3228cc22011-03-14 16:50:06 +00002245 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2246 // inner recurrence has the same property.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002247 SCEV::NoWrapFlags OuterFlags =
2248 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick3228cc22011-03-14 16:50:06 +00002249
2250 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohman9a80b452009-06-26 22:36:20 +00002251 AllInvariant = true;
2252 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002253 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002254 AllInvariant = false;
2255 break;
2256 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002257 if (AllInvariant) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002258 // Ok, both add recurrences are valid after the transformation.
Andrew Trick3228cc22011-03-14 16:50:06 +00002259 //
Andrew Trick3228cc22011-03-14 16:50:06 +00002260 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2261 // the outer recurrence has the same property.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002262 SCEV::NoWrapFlags InnerFlags =
2263 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick3228cc22011-03-14 16:50:06 +00002264 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2265 }
Dan Gohman9a80b452009-06-26 22:36:20 +00002266 }
2267 // Reset Operands to its original state.
2268 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002269 }
2270 }
2271
Dan Gohman67847532010-01-19 22:27:22 +00002272 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2273 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002274 FoldingSetNodeID ID;
2275 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002276 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2277 ID.AddPointer(Operands[i]);
2278 ID.AddPointer(L);
2279 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002280 SCEVAddRecExpr *S =
2281 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2282 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002283 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2284 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002285 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2286 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002287 UniqueSCEVs.InsertNode(S, IP);
2288 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002289 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002290 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002291}
2292
Dan Gohman9311ef62009-06-24 14:49:00 +00002293const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2294 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002295 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002296 Ops.push_back(LHS);
2297 Ops.push_back(RHS);
2298 return getSMaxExpr(Ops);
2299}
2300
Dan Gohman0bba49c2009-07-07 17:06:11 +00002301const SCEV *
2302ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002303 assert(!Ops.empty() && "Cannot get empty smax!");
2304 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002305#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002306 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002307 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002309 "SCEVSMaxExpr operand types don't match!");
2310#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002311
2312 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002313 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002314
2315 // If there are any constants, fold them together.
2316 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002317 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002318 ++Idx;
2319 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002320 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002321 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002322 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002323 APIntOps::smax(LHSC->getValue()->getValue(),
2324 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002325 Ops[0] = getConstant(Fold);
2326 Ops.erase(Ops.begin()+1); // Erase the folded element
2327 if (Ops.size() == 1) return Ops[0];
2328 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002329 }
2330
Dan Gohmane5aceed2009-06-24 14:46:22 +00002331 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002332 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2333 Ops.erase(Ops.begin());
2334 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002335 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2336 // If we have an smax with a constant maximum-int, it will always be
2337 // maximum-int.
2338 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002339 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002340
Dan Gohman3ab13122010-04-13 16:49:23 +00002341 if (Ops.size() == 1) return Ops[0];
2342 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002343
2344 // Find the first SMax
2345 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2346 ++Idx;
2347
2348 // Check to see if one of the operands is an SMax. If so, expand its operands
2349 // onto our operand list, and recurse to simplify.
2350 if (Idx < Ops.size()) {
2351 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002352 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002353 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002354 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002355 DeletedSMax = true;
2356 }
2357
2358 if (DeletedSMax)
2359 return getSMaxExpr(Ops);
2360 }
2361
2362 // Okay, check to see if the same value occurs in the operand list twice. If
2363 // so, delete one. Since we sorted the list, these values are required to
2364 // be adjacent.
2365 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002366 // X smax Y smax Y --> X smax Y
2367 // X smax Y --> X, if X is always greater than Y
2368 if (Ops[i] == Ops[i+1] ||
2369 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2370 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2371 --i; --e;
2372 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002373 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2374 --i; --e;
2375 }
2376
2377 if (Ops.size() == 1) return Ops[0];
2378
2379 assert(!Ops.empty() && "Reduced smax down to nothing!");
2380
Nick Lewycky3e630762008-02-20 06:48:22 +00002381 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002382 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002383 FoldingSetNodeID ID;
2384 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002385 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2386 ID.AddPointer(Ops[i]);
2387 void *IP = 0;
2388 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002389 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2390 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002391 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2392 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002393 UniqueSCEVs.InsertNode(S, IP);
2394 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002395}
2396
Dan Gohman9311ef62009-06-24 14:49:00 +00002397const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2398 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002399 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002400 Ops.push_back(LHS);
2401 Ops.push_back(RHS);
2402 return getUMaxExpr(Ops);
2403}
2404
Dan Gohman0bba49c2009-07-07 17:06:11 +00002405const SCEV *
2406ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002407 assert(!Ops.empty() && "Cannot get empty umax!");
2408 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002409#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002410 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002411 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002412 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002413 "SCEVUMaxExpr operand types don't match!");
2414#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002415
2416 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002417 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002418
2419 // If there are any constants, fold them together.
2420 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002421 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002422 ++Idx;
2423 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002424 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002425 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002426 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002427 APIntOps::umax(LHSC->getValue()->getValue(),
2428 RHSC->getValue()->getValue()));
2429 Ops[0] = getConstant(Fold);
2430 Ops.erase(Ops.begin()+1); // Erase the folded element
2431 if (Ops.size() == 1) return Ops[0];
2432 LHSC = cast<SCEVConstant>(Ops[0]);
2433 }
2434
Dan Gohmane5aceed2009-06-24 14:46:22 +00002435 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002436 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2437 Ops.erase(Ops.begin());
2438 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002439 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2440 // If we have an umax with a constant maximum-int, it will always be
2441 // maximum-int.
2442 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002443 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002444
Dan Gohman3ab13122010-04-13 16:49:23 +00002445 if (Ops.size() == 1) return Ops[0];
2446 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002447
2448 // Find the first UMax
2449 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2450 ++Idx;
2451
2452 // Check to see if one of the operands is a UMax. If so, expand its operands
2453 // onto our operand list, and recurse to simplify.
2454 if (Idx < Ops.size()) {
2455 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002456 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002457 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002458 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002459 DeletedUMax = true;
2460 }
2461
2462 if (DeletedUMax)
2463 return getUMaxExpr(Ops);
2464 }
2465
2466 // Okay, check to see if the same value occurs in the operand list twice. If
2467 // so, delete one. Since we sorted the list, these values are required to
2468 // be adjacent.
2469 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002470 // X umax Y umax Y --> X umax Y
2471 // X umax Y --> X, if X is always greater than Y
2472 if (Ops[i] == Ops[i+1] ||
2473 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2474 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2475 --i; --e;
2476 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002477 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2478 --i; --e;
2479 }
2480
2481 if (Ops.size() == 1) return Ops[0];
2482
2483 assert(!Ops.empty() && "Reduced umax down to nothing!");
2484
2485 // Okay, it looks like we really DO need a umax expr. Check to see if we
2486 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002487 FoldingSetNodeID ID;
2488 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002489 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2490 ID.AddPointer(Ops[i]);
2491 void *IP = 0;
2492 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002493 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2494 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002495 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2496 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002497 UniqueSCEVs.InsertNode(S, IP);
2498 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002499}
2500
Dan Gohman9311ef62009-06-24 14:49:00 +00002501const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2502 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002503 // ~smax(~x, ~y) == smin(x, y).
2504 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2505}
2506
Dan Gohman9311ef62009-06-24 14:49:00 +00002507const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2508 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002509 // ~umax(~x, ~y) == umin(x, y)
2510 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2511}
2512
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002513const SCEV *ScalarEvolution::getSizeOfExpr(Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002514 // If we have TargetData, we can bypass creating a target-independent
2515 // constant expression and then folding it back into a ConstantInt.
2516 // This is just a compile-time optimization.
2517 if (TD)
2518 return getConstant(TD->getIntPtrType(getContext()),
2519 TD->getTypeAllocSize(AllocTy));
2520
Dan Gohman4f8eea82010-02-01 18:27:38 +00002521 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002523 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2524 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002525 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Dan Gohman4f8eea82010-02-01 18:27:38 +00002526 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2527}
2528
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002529const SCEV *ScalarEvolution::getAlignOfExpr(Type *AllocTy) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00002530 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002532 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2533 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002534 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Dan Gohman4f8eea82010-02-01 18:27:38 +00002535 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2536}
2537
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002538const SCEV *ScalarEvolution::getOffsetOfExpr(StructType *STy,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002539 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002540 // If we have TargetData, we can bypass creating a target-independent
2541 // constant expression and then folding it back into a ConstantInt.
2542 // This is just a compile-time optimization.
2543 if (TD)
2544 return getConstant(TD->getIntPtrType(getContext()),
2545 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2546
Dan Gohman0f5efe52010-01-28 02:15:55 +00002547 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2548 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002549 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2550 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002551 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002552 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002553}
2554
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002555const SCEV *ScalarEvolution::getOffsetOfExpr(Type *CTy,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002556 Constant *FieldNo) {
2557 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002558 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002559 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2560 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002561 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002562 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002563}
2564
Dan Gohman0bba49c2009-07-07 17:06:11 +00002565const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002566 // Don't attempt to do anything other than create a SCEVUnknown object
2567 // here. createSCEV only calls getUnknown after checking for all other
2568 // interesting possibilities, and any other code that calls getUnknown
2569 // is doing so in order to hide a value from SCEV canonicalization.
2570
Dan Gohman1c343752009-06-27 21:21:31 +00002571 FoldingSetNodeID ID;
2572 ID.AddInteger(scUnknown);
2573 ID.AddPointer(V);
2574 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002575 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2576 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2577 "Stale SCEVUnknown in uniquing map!");
2578 return S;
2579 }
2580 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2581 FirstUnknown);
2582 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002583 UniqueSCEVs.InsertNode(S, IP);
2584 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002585}
2586
Chris Lattner53e677a2004-04-02 20:23:17 +00002587//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002588// Basic SCEV Analysis and PHI Idiom Recognition Code
2589//
2590
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002591/// isSCEVable - Test if values of the given type are analyzable within
2592/// the SCEV framework. This primarily includes integer types, and it
2593/// can optionally include pointer types if the ScalarEvolution class
2594/// has access to target-specific information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002595bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002596 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002597 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002598}
2599
2600/// getTypeSizeInBits - Return the size in bits of the specified type,
2601/// for which isSCEVable must return true.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002602uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002603 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2604
2605 // If we have a TargetData, use it!
2606 if (TD)
2607 return TD->getTypeSizeInBits(Ty);
2608
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002609 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002610 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002611 return Ty->getPrimitiveSizeInBits();
2612
2613 // The only other support type is pointer. Without TargetData, conservatively
2614 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002615 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002616 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002617}
2618
2619/// getEffectiveSCEVType - Return a type with the same bitwidth as
2620/// the given type and which represents how SCEV will treat the given
2621/// type, for which isSCEVable must return true. For pointer types,
2622/// this is the pointer-sized integer type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002623Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002624 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2625
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002626 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002627 return Ty;
2628
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002629 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002630 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002631 if (TD) return TD->getIntPtrType(getContext());
2632
2633 // Without TargetData, conservatively assume pointers are 64-bit.
2634 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002635}
Chris Lattner53e677a2004-04-02 20:23:17 +00002636
Dan Gohman0bba49c2009-07-07 17:06:11 +00002637const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002638 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002639}
2640
Chris Lattner53e677a2004-04-02 20:23:17 +00002641/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2642/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002643const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002644 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002645
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002646 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2647 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002648 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002649
2650 // The process of creating a SCEV for V may have caused other SCEVs
2651 // to have been created, so it's necessary to insert the new entry
2652 // from scratch, rather than trying to remember the insert position
2653 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002654 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002655 return S;
2656}
2657
Dan Gohman2d1be872009-04-16 03:18:22 +00002658/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2659///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002660const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002661 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002662 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002663 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002664
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002665 Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002666 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002667 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002668 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002669}
2670
2671/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002672const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002673 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002674 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002675 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002676
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002677 Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002678 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002679 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002680 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002681 return getMinusSCEV(AllOnes, V);
2682}
2683
Andrew Trick3228cc22011-03-14 16:50:06 +00002684/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattner992efb02011-01-09 22:26:35 +00002685const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00002686 SCEV::NoWrapFlags Flags) {
Andrew Trick4dbe2002011-03-15 01:16:14 +00002687 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
2688
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002689 // Fast path: X - X --> 0.
2690 if (LHS == RHS)
2691 return getConstant(LHS->getType(), 0);
2692
Dan Gohman2d1be872009-04-16 03:18:22 +00002693 // X - Y --> X + -Y
Andrew Trick3228cc22011-03-14 16:50:06 +00002694 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman2d1be872009-04-16 03:18:22 +00002695}
2696
2697/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2698/// input value to the specified type. If the type must be extended, it is zero
2699/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002700const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002701ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
2702 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002703 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2704 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002705 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002706 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002707 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002708 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002709 return getTruncateExpr(V, Ty);
2710 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002711}
2712
2713/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2714/// input value to the specified type. If the type must be extended, it is sign
2715/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002716const SCEV *
2717ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002718 Type *Ty) {
2719 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002720 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2721 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002722 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002723 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002724 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002725 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002726 return getTruncateExpr(V, Ty);
2727 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002728}
2729
Dan Gohman467c4302009-05-13 03:46:30 +00002730/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2731/// input value to the specified type. If the type must be extended, it is zero
2732/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002733const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002734ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
2735 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002736 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2737 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002738 "Cannot noop or zero extend with non-integer arguments!");
2739 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2740 "getNoopOrZeroExtend cannot truncate!");
2741 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2742 return V; // No conversion
2743 return getZeroExtendExpr(V, Ty);
2744}
2745
2746/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2747/// input value to the specified type. If the type must be extended, it is sign
2748/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002749const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002750ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
2751 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002752 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2753 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002754 "Cannot noop or sign extend with non-integer arguments!");
2755 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2756 "getNoopOrSignExtend cannot truncate!");
2757 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2758 return V; // No conversion
2759 return getSignExtendExpr(V, Ty);
2760}
2761
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002762/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2763/// the input value to the specified type. If the type must be extended,
2764/// it is extended with unspecified bits. The conversion must not be
2765/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002766const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002767ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
2768 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002769 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2770 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002771 "Cannot noop or any extend with non-integer arguments!");
2772 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2773 "getNoopOrAnyExtend cannot truncate!");
2774 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2775 return V; // No conversion
2776 return getAnyExtendExpr(V, Ty);
2777}
2778
Dan Gohman467c4302009-05-13 03:46:30 +00002779/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2780/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002781const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002782ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
2783 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002784 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2785 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002786 "Cannot truncate or noop with non-integer arguments!");
2787 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2788 "getTruncateOrNoop cannot extend!");
2789 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2790 return V; // No conversion
2791 return getTruncateExpr(V, Ty);
2792}
2793
Dan Gohmana334aa72009-06-22 00:31:57 +00002794/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2795/// the types using zero-extension, and then perform a umax operation
2796/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002797const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2798 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002799 const SCEV *PromotedLHS = LHS;
2800 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002801
2802 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2803 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2804 else
2805 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2806
2807 return getUMaxExpr(PromotedLHS, PromotedRHS);
2808}
2809
Dan Gohmanc9759e82009-06-22 15:03:27 +00002810/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2811/// the types using zero-extension, and then perform a umin operation
2812/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002813const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2814 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002815 const SCEV *PromotedLHS = LHS;
2816 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002817
2818 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2819 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2820 else
2821 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2822
2823 return getUMinExpr(PromotedLHS, PromotedRHS);
2824}
2825
Andrew Trickb12a7542011-03-17 23:51:11 +00002826/// getPointerBase - Transitively follow the chain of pointer-type operands
2827/// until reaching a SCEV that does not have a single pointer operand. This
2828/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
2829/// but corner cases do exist.
2830const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
2831 // A pointer operand may evaluate to a nonpointer expression, such as null.
2832 if (!V->getType()->isPointerTy())
2833 return V;
2834
2835 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
2836 return getPointerBase(Cast->getOperand());
2837 }
2838 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
2839 const SCEV *PtrOp = 0;
2840 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
2841 I != E; ++I) {
2842 if ((*I)->getType()->isPointerTy()) {
2843 // Cannot find the base of an expression with multiple pointer operands.
2844 if (PtrOp)
2845 return V;
2846 PtrOp = *I;
2847 }
2848 }
2849 if (!PtrOp)
2850 return V;
2851 return getPointerBase(PtrOp);
2852 }
2853 return V;
2854}
2855
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002856/// PushDefUseChildren - Push users of the given Instruction
2857/// onto the given Worklist.
2858static void
2859PushDefUseChildren(Instruction *I,
2860 SmallVectorImpl<Instruction *> &Worklist) {
2861 // Push the def-use children onto the Worklist stack.
2862 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2863 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002864 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002865}
2866
2867/// ForgetSymbolicValue - This looks up computed SCEV values for all
2868/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002869/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002870/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002871void
Dan Gohman85669632010-02-25 06:57:05 +00002872ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002873 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002874 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002875
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002876 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002877 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002878 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002879 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002880 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002881
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002882 ValueExprMapType::iterator It =
2883 ValueExprMap.find(static_cast<Value *>(I));
2884 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002885 const SCEV *Old = It->second;
2886
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002887 // Short-circuit the def-use traversal if the symbolic name
2888 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002889 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002890 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002891
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002892 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002893 // structure, it's a PHI that's in the progress of being computed
2894 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2895 // additional loop trip count information isn't going to change anything.
2896 // In the second case, createNodeForPHI will perform the necessary
2897 // updates on its own when it gets to that point. In the third, we do
2898 // want to forget the SCEVUnknown.
2899 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002900 !isa<SCEVUnknown>(Old) ||
2901 (I != PN && Old == SymName)) {
Dan Gohman56a75682010-11-17 23:28:48 +00002902 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002903 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002904 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002905 }
2906
2907 PushDefUseChildren(I, Worklist);
2908 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002909}
Chris Lattner53e677a2004-04-02 20:23:17 +00002910
2911/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2912/// a loop header, making it a potential recurrence, or it doesn't.
2913///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002914const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002915 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2916 if (L->getHeader() == PN->getParent()) {
2917 // The loop may have multiple entrances or multiple exits; we can analyze
2918 // this phi as an addrec if it has a unique entry value and a unique
2919 // backedge value.
2920 Value *BEValueV = 0, *StartValueV = 0;
2921 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2922 Value *V = PN->getIncomingValue(i);
2923 if (L->contains(PN->getIncomingBlock(i))) {
2924 if (!BEValueV) {
2925 BEValueV = V;
2926 } else if (BEValueV != V) {
2927 BEValueV = 0;
2928 break;
2929 }
2930 } else if (!StartValueV) {
2931 StartValueV = V;
2932 } else if (StartValueV != V) {
2933 StartValueV = 0;
2934 break;
2935 }
2936 }
2937 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002938 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002939 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002940 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002941 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002942 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002943
2944 // Using this symbolic name for the PHI, analyze the value coming around
2945 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002946 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002947
2948 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2949 // has a special value for the first iteration of the loop.
2950
2951 // If the value coming around the backedge is an add with the symbolic
2952 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002953 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002954 // If there is a single occurrence of the symbolic value, replace it
2955 // with a recurrence.
2956 unsigned FoundIndex = Add->getNumOperands();
2957 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2958 if (Add->getOperand(i) == SymbolicName)
2959 if (FoundIndex == e) {
2960 FoundIndex = i;
2961 break;
2962 }
2963
2964 if (FoundIndex != Add->getNumOperands()) {
2965 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002966 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002967 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2968 if (i != FoundIndex)
2969 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002970 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002971
2972 // This is not a valid addrec if the step amount is varying each
2973 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002974 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002975 (isa<SCEVAddRecExpr>(Accum) &&
2976 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002977 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohmana10756e2010-01-21 02:09:26 +00002978
2979 // If the increment doesn't overflow, then neither the addrec nor
2980 // the post-increment will overflow.
2981 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2982 if (OBO->hasNoUnsignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002983 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002984 if (OBO->hasNoSignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002985 Flags = setFlags(Flags, SCEV::FlagNSW);
Andrew Trick635f7182011-03-09 17:23:39 +00002986 } else if (const GEPOperator *GEP =
Andrew Trick3228cc22011-03-14 16:50:06 +00002987 dyn_cast<GEPOperator>(BEValueV)) {
2988 // If the increment is an inbounds GEP, then we know the address
2989 // space cannot be wrapped around. We cannot make any guarantee
2990 // about signed or unsigned overflow because pointers are
2991 // unsigned but we may have a negative index from the base
2992 // pointer.
2993 if (GEP->isInBounds())
Andrew Trickc343c1e2011-03-15 00:37:00 +00002994 Flags = setFlags(Flags, SCEV::FlagNW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002995 }
2996
Dan Gohman27dead42010-04-12 07:49:36 +00002997 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick3228cc22011-03-14 16:50:06 +00002998 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002999
Dan Gohmana10756e2010-01-21 02:09:26 +00003000 // Since the no-wrap flags are on the increment, they apply to the
3001 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00003002 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00003003 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick3228cc22011-03-14 16:50:06 +00003004 Accum, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00003005
3006 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00003007 // to be symbolic. We now need to go back and purge all of the
3008 // entries for the scalars that use the symbolic expression.
3009 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003010 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00003011 return PHISCEV;
3012 }
3013 }
Dan Gohman622ed672009-05-04 22:02:23 +00003014 } else if (const SCEVAddRecExpr *AddRec =
3015 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00003016 // Otherwise, this could be a loop like this:
3017 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3018 // In this case, j = {1,+,1} and BEValue is j.
3019 // Because the other in-value of i (0) fits the evolution of BEValue
3020 // i really is an addrec evolution.
3021 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00003022 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00003023
3024 // If StartVal = j.start - j.stride, we can use StartVal as the
3025 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003026 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00003027 AddRec->getOperand(1))) {
Andrew Trick3228cc22011-03-14 16:50:06 +00003028 // FIXME: For constant StartVal, we should be able to infer
3029 // no-wrap flags.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003030 const SCEV *PHISCEV =
Andrew Trick3228cc22011-03-14 16:50:06 +00003031 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3032 SCEV::FlagAnyWrap);
Chris Lattner97156e72006-04-26 18:34:07 +00003033
3034 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00003035 // to be symbolic. We now need to go back and purge all of the
3036 // entries for the scalars that use the symbolic expression.
3037 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003038 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00003039 return PHISCEV;
3040 }
3041 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003042 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003043 }
Dan Gohman27dead42010-04-12 07:49:36 +00003044 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003045
Dan Gohman85669632010-02-25 06:57:05 +00003046 // If the PHI has a single incoming value, follow that value, unless the
3047 // PHI's incoming blocks are in a different loop, in which case doing so
3048 // risks breaking LCSSA form. Instcombine would normally zap these, but
3049 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00003050 if (Value *V = SimplifyInstruction(PN, TD, DT))
3051 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohman85669632010-02-25 06:57:05 +00003052 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00003053
Chris Lattner53e677a2004-04-02 20:23:17 +00003054 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003055 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00003056}
3057
Dan Gohman26466c02009-05-08 20:26:55 +00003058/// createNodeForGEP - Expand GEP instructions into add and multiply
3059/// operations. This allows them to be analyzed by regular SCEV code.
3060///
Dan Gohmand281ed22009-12-18 02:09:29 +00003061const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00003062
Dan Gohmanb9f96512010-06-30 07:16:37 +00003063 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3064 // Add expression, because the Instruction may be guarded by control flow
3065 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00003066 // context.
Chris Lattner8ebaf902011-02-13 03:14:49 +00003067 bool isInBounds = GEP->isInBounds();
Dan Gohman7a642572010-06-29 01:41:41 +00003068
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003069 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00003070 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00003071 // Don't attempt to analyze GEPs over unsized objects.
3072 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
3073 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00003074 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00003075 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00003076 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00003077 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00003078 I != E; ++I) {
3079 Value *Index = *I;
3080 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003081 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Dan Gohman26466c02009-05-08 20:26:55 +00003082 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00003083 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00003084 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
3085
Dan Gohmanb9f96512010-06-30 07:16:37 +00003086 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00003087 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00003088 } else {
3089 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00003090 const SCEV *ElementSize = getSizeOfExpr(*GTI);
3091 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003092 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00003093 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3094
Dan Gohmanb9f96512010-06-30 07:16:37 +00003095 // Multiply the index by the element size to compute the element offset.
Andrew Trick3228cc22011-03-14 16:50:06 +00003096 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
3097 isInBounds ? SCEV::FlagNSW :
3098 SCEV::FlagAnyWrap);
Dan Gohmanb9f96512010-06-30 07:16:37 +00003099
3100 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00003101 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00003102 }
3103 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00003104
3105 // Get the SCEV for the GEP base.
3106 const SCEV *BaseS = getSCEV(Base);
3107
Dan Gohmanb9f96512010-06-30 07:16:37 +00003108 // Add the total offset from all the GEP indices to the base.
Andrew Trick3228cc22011-03-14 16:50:06 +00003109 return getAddExpr(BaseS, TotalOffset,
3110 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
Dan Gohman26466c02009-05-08 20:26:55 +00003111}
3112
Nick Lewycky83bb0052007-11-22 07:59:40 +00003113/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3114/// guaranteed to end in (at every loop iteration). It is, at the same time,
3115/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3116/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003117uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00003118ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00003119 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00003120 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00003121
Dan Gohman622ed672009-05-04 22:02:23 +00003122 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00003123 return std::min(GetMinTrailingZeros(T->getOperand()),
3124 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003125
Dan Gohman622ed672009-05-04 22:02:23 +00003126 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003127 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3128 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3129 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00003130 }
3131
Dan Gohman622ed672009-05-04 22:02:23 +00003132 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003133 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3134 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3135 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00003136 }
3137
Dan Gohman622ed672009-05-04 22:02:23 +00003138 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003139 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003140 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003141 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003142 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003143 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003144 }
3145
Dan Gohman622ed672009-05-04 22:02:23 +00003146 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003147 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003148 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3149 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00003150 for (unsigned i = 1, e = M->getNumOperands();
3151 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003152 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00003153 BitWidth);
3154 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003155 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003156
Dan Gohman622ed672009-05-04 22:02:23 +00003157 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003158 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003159 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003160 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003161 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003162 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003163 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003164
Dan Gohman622ed672009-05-04 22:02:23 +00003165 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003166 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003167 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003168 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003169 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003170 return MinOpRes;
3171 }
3172
Dan Gohman622ed672009-05-04 22:02:23 +00003173 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00003174 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003175 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00003176 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003177 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00003178 return MinOpRes;
3179 }
3180
Dan Gohman2c364ad2009-06-19 23:29:04 +00003181 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3182 // For a SCEVUnknown, ask ValueTracking.
3183 unsigned BitWidth = getTypeSizeInBits(U->getType());
3184 APInt Mask = APInt::getAllOnesValue(BitWidth);
3185 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3186 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3187 return Zeros.countTrailingOnes();
3188 }
3189
3190 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00003191 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00003192}
Chris Lattner53e677a2004-04-02 20:23:17 +00003193
Dan Gohman85b05a22009-07-13 21:35:55 +00003194/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3195///
3196ConstantRange
3197ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003198 // See if we've computed this range already.
3199 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3200 if (I != UnsignedRanges.end())
3201 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003202
3203 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003204 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003205
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003206 unsigned BitWidth = getTypeSizeInBits(S->getType());
3207 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3208
3209 // If the value has known zeros, the maximum unsigned value will have those
3210 // known zeros as well.
3211 uint32_t TZ = GetMinTrailingZeros(S);
3212 if (TZ != 0)
3213 ConservativeResult =
3214 ConstantRange(APInt::getMinValue(BitWidth),
3215 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3216
Dan Gohman85b05a22009-07-13 21:35:55 +00003217 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3218 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3219 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3220 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003221 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003222 }
3223
3224 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3225 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3226 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3227 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003228 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003229 }
3230
3231 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3232 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3233 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3234 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003235 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003236 }
3237
3238 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3239 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3240 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3241 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003242 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003243 }
3244
3245 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3246 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3247 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003248 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003249 }
3250
3251 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3252 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003253 return setUnsignedRange(ZExt,
3254 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003255 }
3256
3257 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3258 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003259 return setUnsignedRange(SExt,
3260 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003261 }
3262
3263 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3264 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003265 return setUnsignedRange(Trunc,
3266 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003267 }
3268
Dan Gohman85b05a22009-07-13 21:35:55 +00003269 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003270 // If there's no unsigned wrap, the value will never be less than its
3271 // initial value.
Andrew Trick3228cc22011-03-14 16:50:06 +00003272 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmana10756e2010-01-21 02:09:26 +00003273 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003274 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003275 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003276 ConservativeResult.intersectWith(
3277 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003278
3279 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003280 if (AddRec->isAffine()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003281 Type *Ty = AddRec->getType();
Dan Gohman85b05a22009-07-13 21:35:55 +00003282 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003283 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3284 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003285 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3286
3287 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003288 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003289
3290 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003291 ConstantRange StepRange = getSignedRange(Step);
3292 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3293 ConstantRange EndRange =
3294 StartRange.add(MaxBECountRange.multiply(StepRange));
3295
3296 // Check for overflow. This must be done with ConstantRange arithmetic
3297 // because we could be called from within the ScalarEvolution overflow
3298 // checking code.
3299 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3300 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3301 ConstantRange ExtMaxBECountRange =
3302 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3303 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3304 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3305 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003306 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003307
Dan Gohman85b05a22009-07-13 21:35:55 +00003308 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3309 EndRange.getUnsignedMin());
3310 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3311 EndRange.getUnsignedMax());
3312 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003313 return setUnsignedRange(AddRec, ConservativeResult);
3314 return setUnsignedRange(AddRec,
3315 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003316 }
3317 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003318
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003319 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003320 }
3321
3322 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3323 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003324 APInt Mask = APInt::getAllOnesValue(BitWidth);
3325 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3326 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003327 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003328 return setUnsignedRange(U, ConservativeResult);
3329 return setUnsignedRange(U,
3330 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003331 }
3332
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003333 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003334}
3335
Dan Gohman85b05a22009-07-13 21:35:55 +00003336/// getSignedRange - Determine the signed range for a particular SCEV.
3337///
3338ConstantRange
3339ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohmana3bbf242011-01-24 17:54:18 +00003340 // See if we've computed this range already.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003341 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3342 if (I != SignedRanges.end())
3343 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003344
Dan Gohman85b05a22009-07-13 21:35:55 +00003345 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003346 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003347
Dan Gohman52fddd32010-01-26 04:40:18 +00003348 unsigned BitWidth = getTypeSizeInBits(S->getType());
3349 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3350
3351 // If the value has known zeros, the maximum signed value will have those
3352 // known zeros as well.
3353 uint32_t TZ = GetMinTrailingZeros(S);
3354 if (TZ != 0)
3355 ConservativeResult =
3356 ConstantRange(APInt::getSignedMinValue(BitWidth),
3357 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3358
Dan Gohman85b05a22009-07-13 21:35:55 +00003359 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3360 ConstantRange X = getSignedRange(Add->getOperand(0));
3361 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3362 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003363 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003364 }
3365
Dan Gohman85b05a22009-07-13 21:35:55 +00003366 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3367 ConstantRange X = getSignedRange(Mul->getOperand(0));
3368 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3369 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003370 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003371 }
3372
Dan Gohman85b05a22009-07-13 21:35:55 +00003373 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3374 ConstantRange X = getSignedRange(SMax->getOperand(0));
3375 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3376 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003377 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003378 }
Dan Gohman62849c02009-06-24 01:05:09 +00003379
Dan Gohman85b05a22009-07-13 21:35:55 +00003380 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3381 ConstantRange X = getSignedRange(UMax->getOperand(0));
3382 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3383 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003384 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003385 }
Dan Gohman62849c02009-06-24 01:05:09 +00003386
Dan Gohman85b05a22009-07-13 21:35:55 +00003387 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3388 ConstantRange X = getSignedRange(UDiv->getLHS());
3389 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003390 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003391 }
Dan Gohman62849c02009-06-24 01:05:09 +00003392
Dan Gohman85b05a22009-07-13 21:35:55 +00003393 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3394 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003395 return setSignedRange(ZExt,
3396 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003397 }
3398
3399 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3400 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003401 return setSignedRange(SExt,
3402 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003403 }
3404
3405 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3406 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003407 return setSignedRange(Trunc,
3408 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003409 }
3410
Dan Gohman85b05a22009-07-13 21:35:55 +00003411 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003412 // If there's no signed wrap, and all the operands have the same sign or
3413 // zero, the value won't ever change sign.
Andrew Trick3228cc22011-03-14 16:50:06 +00003414 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003415 bool AllNonNeg = true;
3416 bool AllNonPos = true;
3417 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3418 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3419 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3420 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003421 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003422 ConservativeResult = ConservativeResult.intersectWith(
3423 ConstantRange(APInt(BitWidth, 0),
3424 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003425 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003426 ConservativeResult = ConservativeResult.intersectWith(
3427 ConstantRange(APInt::getSignedMinValue(BitWidth),
3428 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003429 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003430
3431 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003432 if (AddRec->isAffine()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003433 Type *Ty = AddRec->getType();
Dan Gohman85b05a22009-07-13 21:35:55 +00003434 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003435 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3436 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003437 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3438
3439 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003440 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003441
3442 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003443 ConstantRange StepRange = getSignedRange(Step);
3444 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3445 ConstantRange EndRange =
3446 StartRange.add(MaxBECountRange.multiply(StepRange));
3447
3448 // Check for overflow. This must be done with ConstantRange arithmetic
3449 // because we could be called from within the ScalarEvolution overflow
3450 // checking code.
3451 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3452 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3453 ConstantRange ExtMaxBECountRange =
3454 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3455 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3456 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3457 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003458 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003459
Dan Gohman85b05a22009-07-13 21:35:55 +00003460 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3461 EndRange.getSignedMin());
3462 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3463 EndRange.getSignedMax());
3464 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003465 return setSignedRange(AddRec, ConservativeResult);
3466 return setSignedRange(AddRec,
3467 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003468 }
Dan Gohman62849c02009-06-24 01:05:09 +00003469 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003470
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003471 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003472 }
3473
Dan Gohman2c364ad2009-06-19 23:29:04 +00003474 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3475 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003476 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003477 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003478 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3479 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003480 return setSignedRange(U, ConservativeResult);
3481 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003482 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003483 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003484 }
3485
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003486 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003487}
3488
Chris Lattner53e677a2004-04-02 20:23:17 +00003489/// createSCEV - We know that there is no SCEV for the specified value.
3490/// Analyze the expression.
3491///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003492const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003493 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003494 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003495
Dan Gohman6c459a22008-06-22 19:56:46 +00003496 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003497 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003498 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003499
3500 // Don't attempt to analyze instructions in blocks that aren't
3501 // reachable. Such instructions don't matter, and they aren't required
3502 // to obey basic rules for definitions dominating uses which this
3503 // analysis depends on.
3504 if (!DT->isReachableFromEntry(I->getParent()))
3505 return getUnknown(V);
3506 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003507 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003508 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3509 return getConstant(CI);
3510 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003511 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003512 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3513 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003514 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003515 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003516
Dan Gohmanca178902009-07-17 20:47:02 +00003517 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003518 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003519 case Instruction::Add: {
3520 // The simple thing to do would be to just call getSCEV on both operands
3521 // and call getAddExpr with the result. However if we're looking at a
3522 // bunch of things all added together, this can be quite inefficient,
3523 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3524 // Instead, gather up all the operands and make a single getAddExpr call.
3525 // LLVM IR canonical form means we need only traverse the left operands.
3526 SmallVector<const SCEV *, 4> AddOps;
3527 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003528 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3529 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3530 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3531 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003532 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003533 const SCEV *Op1 = getSCEV(U->getOperand(1));
3534 if (Opcode == Instruction::Sub)
3535 AddOps.push_back(getNegativeSCEV(Op1));
3536 else
3537 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003538 }
3539 AddOps.push_back(getSCEV(U->getOperand(0)));
3540 return getAddExpr(AddOps);
3541 }
3542 case Instruction::Mul: {
3543 // See the Add code above.
3544 SmallVector<const SCEV *, 4> MulOps;
3545 MulOps.push_back(getSCEV(U->getOperand(1)));
3546 for (Value *Op = U->getOperand(0);
Andrew Trick635f7182011-03-09 17:23:39 +00003547 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003548 Op = U->getOperand(0)) {
3549 U = cast<Operator>(Op);
3550 MulOps.push_back(getSCEV(U->getOperand(1)));
3551 }
3552 MulOps.push_back(getSCEV(U->getOperand(0)));
3553 return getMulExpr(MulOps);
3554 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003555 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003556 return getUDivExpr(getSCEV(U->getOperand(0)),
3557 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003558 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003559 return getMinusSCEV(getSCEV(U->getOperand(0)),
3560 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003561 case Instruction::And:
3562 // For an expression like x&255 that merely masks off the high bits,
3563 // use zext(trunc(x)) as the SCEV expression.
3564 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003565 if (CI->isNullValue())
3566 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003567 if (CI->isAllOnesValue())
3568 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003569 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003570
3571 // Instcombine's ShrinkDemandedConstant may strip bits out of
3572 // constants, obscuring what would otherwise be a low-bits mask.
3573 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3574 // knew about to reconstruct a low-bits mask value.
3575 unsigned LZ = A.countLeadingZeros();
3576 unsigned BitWidth = A.getBitWidth();
3577 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3578 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3579 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3580
3581 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3582
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003583 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003584 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003585 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003586 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003587 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003588 }
3589 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003590
Dan Gohman6c459a22008-06-22 19:56:46 +00003591 case Instruction::Or:
3592 // If the RHS of the Or is a constant, we may have something like:
3593 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3594 // optimizations will transparently handle this case.
3595 //
3596 // In order for this transformation to be safe, the LHS must be of the
3597 // form X*(2^n) and the Or constant must be less than 2^n.
3598 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003599 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003600 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003601 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003602 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3603 // Build a plain add SCEV.
3604 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3605 // If the LHS of the add was an addrec and it has no-wrap flags,
3606 // transfer the no-wrap flags, since an or won't introduce a wrap.
3607 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3608 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick3228cc22011-03-14 16:50:06 +00003609 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3610 OldAR->getNoWrapFlags());
Dan Gohman1f96e672009-09-17 18:05:20 +00003611 }
3612 return S;
3613 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003614 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003615 break;
3616 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003617 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003618 // If the RHS of the xor is a signbit, then this is just an add.
3619 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003620 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003621 return getAddExpr(getSCEV(U->getOperand(0)),
3622 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003623
3624 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003625 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003626 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003627
3628 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3629 // This is a variant of the check for xor with -1, and it handles
3630 // the case where instcombine has trimmed non-demanded bits out
3631 // of an xor with -1.
3632 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3633 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3634 if (BO->getOpcode() == Instruction::And &&
3635 LCI->getValue() == CI->getValue())
3636 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003637 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003638 Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003639 const SCEV *Z0 = Z->getOperand();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003640 Type *Z0Ty = Z0->getType();
Dan Gohman82052832009-06-18 00:00:20 +00003641 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3642
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003643 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003644 // mask off the high bits. Complement the operand and
3645 // re-apply the zext.
3646 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3647 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3648
3649 // If C is a single bit, it may be in the sign-bit position
3650 // before the zero-extend. In this case, represent the xor
3651 // using an add, which is equivalent, and re-apply the zext.
Jay Foad40f8f622010-12-07 08:25:19 +00003652 APInt Trunc = CI->getValue().trunc(Z0TySize);
3653 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohman82052832009-06-18 00:00:20 +00003654 Trunc.isSignBit())
3655 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3656 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003657 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003658 }
3659 break;
3660
3661 case Instruction::Shl:
3662 // Turn shift left of a constant amount into a multiply.
3663 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003664 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003665
3666 // If the shift count is not less than the bitwidth, the result of
3667 // the shift is undefined. Don't try to analyze it, because the
3668 // resolution chosen here may differ from the resolution chosen in
3669 // other parts of the compiler.
3670 if (SA->getValue().uge(BitWidth))
3671 break;
3672
Owen Andersoneed707b2009-07-24 23:12:02 +00003673 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003674 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003675 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003676 }
3677 break;
3678
Nick Lewycky01eaf802008-07-07 06:15:49 +00003679 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003680 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003681 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003682 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003683
3684 // If the shift count is not less than the bitwidth, the result of
3685 // the shift is undefined. Don't try to analyze it, because the
3686 // resolution chosen here may differ from the resolution chosen in
3687 // other parts of the compiler.
3688 if (SA->getValue().uge(BitWidth))
3689 break;
3690
Owen Andersoneed707b2009-07-24 23:12:02 +00003691 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003692 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003693 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003694 }
3695 break;
3696
Dan Gohman4ee29af2009-04-21 02:26:00 +00003697 case Instruction::AShr:
3698 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3699 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003700 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003701 if (L->getOpcode() == Instruction::Shl &&
3702 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003703 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3704
3705 // If the shift count is not less than the bitwidth, the result of
3706 // the shift is undefined. Don't try to analyze it, because the
3707 // resolution chosen here may differ from the resolution chosen in
3708 // other parts of the compiler.
3709 if (CI->getValue().uge(BitWidth))
3710 break;
3711
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003712 uint64_t Amt = BitWidth - CI->getZExtValue();
3713 if (Amt == BitWidth)
3714 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003715 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003716 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003717 IntegerType::get(getContext(),
3718 Amt)),
3719 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003720 }
3721 break;
3722
Dan Gohman6c459a22008-06-22 19:56:46 +00003723 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003724 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003725
3726 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003727 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003728
3729 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003730 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003731
3732 case Instruction::BitCast:
3733 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003734 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003735 return getSCEV(U->getOperand(0));
3736 break;
3737
Dan Gohman4f8eea82010-02-01 18:27:38 +00003738 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3739 // lead to pointer expressions which cannot safely be expanded to GEPs,
3740 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3741 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003742
Dan Gohman26466c02009-05-08 20:26:55 +00003743 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003744 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003745
Dan Gohman6c459a22008-06-22 19:56:46 +00003746 case Instruction::PHI:
3747 return createNodeForPHI(cast<PHINode>(U));
3748
3749 case Instruction::Select:
3750 // This could be a smax or umax that was lowered earlier.
3751 // Try to recover it.
3752 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3753 Value *LHS = ICI->getOperand(0);
3754 Value *RHS = ICI->getOperand(1);
3755 switch (ICI->getPredicate()) {
3756 case ICmpInst::ICMP_SLT:
3757 case ICmpInst::ICMP_SLE:
3758 std::swap(LHS, RHS);
3759 // fall through
3760 case ICmpInst::ICMP_SGT:
3761 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003762 // a >s b ? a+x : b+x -> smax(a, b)+x
3763 // a >s b ? b+x : a+x -> smin(a, b)+x
3764 if (LHS->getType() == U->getType()) {
3765 const SCEV *LS = getSCEV(LHS);
3766 const SCEV *RS = getSCEV(RHS);
3767 const SCEV *LA = getSCEV(U->getOperand(1));
3768 const SCEV *RA = getSCEV(U->getOperand(2));
3769 const SCEV *LDiff = getMinusSCEV(LA, LS);
3770 const SCEV *RDiff = getMinusSCEV(RA, RS);
3771 if (LDiff == RDiff)
3772 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3773 LDiff = getMinusSCEV(LA, RS);
3774 RDiff = getMinusSCEV(RA, LS);
3775 if (LDiff == RDiff)
3776 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3777 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003778 break;
3779 case ICmpInst::ICMP_ULT:
3780 case ICmpInst::ICMP_ULE:
3781 std::swap(LHS, RHS);
3782 // fall through
3783 case ICmpInst::ICMP_UGT:
3784 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003785 // a >u b ? a+x : b+x -> umax(a, b)+x
3786 // a >u b ? b+x : a+x -> umin(a, b)+x
3787 if (LHS->getType() == U->getType()) {
3788 const SCEV *LS = getSCEV(LHS);
3789 const SCEV *RS = getSCEV(RHS);
3790 const SCEV *LA = getSCEV(U->getOperand(1));
3791 const SCEV *RA = getSCEV(U->getOperand(2));
3792 const SCEV *LDiff = getMinusSCEV(LA, LS);
3793 const SCEV *RDiff = getMinusSCEV(RA, RS);
3794 if (LDiff == RDiff)
3795 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3796 LDiff = getMinusSCEV(LA, RS);
3797 RDiff = getMinusSCEV(RA, LS);
3798 if (LDiff == RDiff)
3799 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3800 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003801 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003802 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003803 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3804 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003805 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003806 cast<ConstantInt>(RHS)->isZero()) {
3807 const SCEV *One = getConstant(LHS->getType(), 1);
3808 const SCEV *LS = getSCEV(LHS);
3809 const SCEV *LA = getSCEV(U->getOperand(1));
3810 const SCEV *RA = getSCEV(U->getOperand(2));
3811 const SCEV *LDiff = getMinusSCEV(LA, LS);
3812 const SCEV *RDiff = getMinusSCEV(RA, One);
3813 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003814 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003815 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003816 break;
3817 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003818 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3819 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003820 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003821 cast<ConstantInt>(RHS)->isZero()) {
3822 const SCEV *One = getConstant(LHS->getType(), 1);
3823 const SCEV *LS = getSCEV(LHS);
3824 const SCEV *LA = getSCEV(U->getOperand(1));
3825 const SCEV *RA = getSCEV(U->getOperand(2));
3826 const SCEV *LDiff = getMinusSCEV(LA, One);
3827 const SCEV *RDiff = getMinusSCEV(RA, LS);
3828 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003829 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003830 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003831 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003832 default:
3833 break;
3834 }
3835 }
3836
3837 default: // We cannot analyze this expression.
3838 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003839 }
3840
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003841 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003842}
3843
3844
3845
3846//===----------------------------------------------------------------------===//
3847// Iteration Count Computation Code
3848//
3849
Andrew Trickb1831c62011-08-11 23:36:16 +00003850/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
3851/// normal unsigned value, if possible. Returns 0 if the trip count is unknown
3852/// or not constant. Will also return 0 if the maximum trip count is very large
3853/// (>= 2^32)
3854unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
3855 BasicBlock *ExitBlock) {
3856 const SCEVConstant *ExitCount =
3857 dyn_cast<SCEVConstant>(getExitCount(L, ExitBlock));
3858 if (!ExitCount)
3859 return 0;
3860
3861 ConstantInt *ExitConst = ExitCount->getValue();
3862
3863 // Guard against huge trip counts.
3864 if (ExitConst->getValue().getActiveBits() > 32)
3865 return 0;
3866
3867 // In case of integer overflow, this returns 0, which is correct.
3868 return ((unsigned)ExitConst->getZExtValue()) + 1;
3869}
3870
3871/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
3872/// trip count of this loop as a normal unsigned value, if possible. This
3873/// means that the actual trip count is always a multiple of the returned
3874/// value (don't forget the trip count could very well be zero as well!).
3875///
3876/// Returns 1 if the trip count is unknown or not guaranteed to be the
3877/// multiple of a constant (which is also the case if the trip count is simply
3878/// constant, use getSmallConstantTripCount for that case), Will also return 1
3879/// if the trip count is very large (>= 2^32).
3880unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
3881 BasicBlock *ExitBlock) {
3882 const SCEV *ExitCount = getExitCount(L, ExitBlock);
3883 if (ExitCount == getCouldNotCompute())
3884 return 1;
3885
3886 // Get the trip count from the BE count by adding 1.
3887 const SCEV *TCMul = getAddExpr(ExitCount,
3888 getConstant(ExitCount->getType(), 1));
3889 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
3890 // to factor simple cases.
3891 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
3892 TCMul = Mul->getOperand(0);
3893
3894 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
3895 if (!MulC)
3896 return 1;
3897
3898 ConstantInt *Result = MulC->getValue();
3899
3900 // Guard against huge trip counts.
3901 if (!Result || Result->getValue().getActiveBits() > 32)
3902 return 1;
3903
3904 return (unsigned)Result->getZExtValue();
3905}
3906
Andrew Trick5116ff62011-07-26 17:19:55 +00003907// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickfcb43562011-08-02 04:23:35 +00003908// this loop is guaranteed not to exit via ExitintBlock. Otherwise return
Andrew Trick5116ff62011-07-26 17:19:55 +00003909// SCEVCouldNotCompute.
Andrew Trickfcb43562011-08-02 04:23:35 +00003910const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
3911 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick5116ff62011-07-26 17:19:55 +00003912}
3913
Dan Gohman46bdfb02009-02-24 18:55:53 +00003914/// getBackedgeTakenCount - If the specified loop has a predictable
3915/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3916/// object. The backedge-taken count is the number of times the loop header
3917/// will be branched to from within the loop. This is one less than the
3918/// trip count of the loop, since it doesn't count the first iteration,
3919/// when the header is branched to from outside the loop.
3920///
3921/// Note that it is not valid to call this method on a loop without a
3922/// loop-invariant backedge-taken count (see
3923/// hasLoopInvariantBackedgeTakenCount).
3924///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003925const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick5116ff62011-07-26 17:19:55 +00003926 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohmana1af7572009-04-30 20:47:05 +00003927}
3928
3929/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3930/// return the least SCEV value that is known never to be less than the
3931/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003932const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick5116ff62011-07-26 17:19:55 +00003933 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohmana1af7572009-04-30 20:47:05 +00003934}
3935
Dan Gohman59ae6b92009-07-08 19:23:34 +00003936/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3937/// onto the given Worklist.
3938static void
3939PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3940 BasicBlock *Header = L->getHeader();
3941
3942 // Push all Loop-header PHIs onto the Worklist stack.
3943 for (BasicBlock::iterator I = Header->begin();
3944 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3945 Worklist.push_back(PN);
3946}
3947
Dan Gohmana1af7572009-04-30 20:47:05 +00003948const ScalarEvolution::BackedgeTakenInfo &
3949ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick5116ff62011-07-26 17:19:55 +00003950 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003951 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003952 // update the value. The temporary CouldNotCompute value tells SCEV
3953 // code elsewhere that it shouldn't attempt to request a new
3954 // backedge-taken count, which could result in infinite recursion.
Dan Gohman77a2c4c2011-05-09 18:44:09 +00003955 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick5116ff62011-07-26 17:19:55 +00003956 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnerf1859892011-01-09 02:16:18 +00003957 if (!Pair.second)
3958 return Pair.first->second;
Dan Gohman01ecca22009-04-27 20:16:15 +00003959
Andrew Trick5116ff62011-07-26 17:19:55 +00003960 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
3961 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
3962 // must be cleared in this scope.
3963 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
3964
3965 if (Result.getExact(this) != getCouldNotCompute()) {
3966 assert(isLoopInvariant(Result.getExact(this), L) &&
3967 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnerf1859892011-01-09 02:16:18 +00003968 "Computed backedge-taken count isn't loop invariant for loop!");
3969 ++NumTripCountsComputed;
Andrew Trick5116ff62011-07-26 17:19:55 +00003970 }
3971 else if (Result.getMax(this) == getCouldNotCompute() &&
3972 isa<PHINode>(L->getHeader()->begin())) {
3973 // Only count loops that have phi nodes as not being computable.
3974 ++NumTripCountsNotComputed;
Chris Lattnerf1859892011-01-09 02:16:18 +00003975 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003976
Chris Lattnerf1859892011-01-09 02:16:18 +00003977 // Now that we know more about the trip count for this loop, forget any
3978 // existing SCEV values for PHI nodes in this loop since they are only
3979 // conservative estimates made without the benefit of trip count
3980 // information. This is similar to the code in forgetLoop, except that
3981 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick5116ff62011-07-26 17:19:55 +00003982 if (Result.hasAnyInfo()) {
Chris Lattnerf1859892011-01-09 02:16:18 +00003983 SmallVector<Instruction *, 16> Worklist;
3984 PushLoopPHIs(L, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003985
Chris Lattnerf1859892011-01-09 02:16:18 +00003986 SmallPtrSet<Instruction *, 8> Visited;
3987 while (!Worklist.empty()) {
3988 Instruction *I = Worklist.pop_back_val();
3989 if (!Visited.insert(I)) continue;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003990
Chris Lattnerf1859892011-01-09 02:16:18 +00003991 ValueExprMapType::iterator It =
3992 ValueExprMap.find(static_cast<Value *>(I));
3993 if (It != ValueExprMap.end()) {
3994 const SCEV *Old = It->second;
Dan Gohman6678e7b2010-11-17 02:44:44 +00003995
Chris Lattnerf1859892011-01-09 02:16:18 +00003996 // SCEVUnknown for a PHI either means that it has an unrecognized
3997 // structure, or it's a PHI that's in the progress of being computed
3998 // by createNodeForPHI. In the former case, additional loop trip
3999 // count information isn't going to change anything. In the later
4000 // case, createNodeForPHI will perform the necessary updates on its
4001 // own when it gets to that point.
4002 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4003 forgetMemoizedResults(Old);
4004 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004005 }
Chris Lattnerf1859892011-01-09 02:16:18 +00004006 if (PHINode *PN = dyn_cast<PHINode>(I))
4007 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004008 }
Chris Lattnerf1859892011-01-09 02:16:18 +00004009
4010 PushDefUseChildren(I, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004011 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004012 }
Dan Gohman308bec32011-04-25 22:48:29 +00004013
4014 // Re-lookup the insert position, since the call to
4015 // ComputeBackedgeTakenCount above could result in a
4016 // recusive call to getBackedgeTakenInfo (on a different
4017 // loop), which would invalidate the iterator computed
4018 // earlier.
4019 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattner53e677a2004-04-02 20:23:17 +00004020}
4021
Dan Gohman4c7279a2009-10-31 15:04:55 +00004022/// forgetLoop - This method should be called by the client when it has
4023/// changed a loop in a way that may effect ScalarEvolution's ability to
4024/// compute a trip count, or if the loop is deleted.
4025void ScalarEvolution::forgetLoop(const Loop *L) {
4026 // Drop any stored trip count value.
Andrew Trick5116ff62011-07-26 17:19:55 +00004027 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4028 BackedgeTakenCounts.find(L);
4029 if (BTCPos != BackedgeTakenCounts.end()) {
4030 BTCPos->second.clear();
4031 BackedgeTakenCounts.erase(BTCPos);
4032 }
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00004033
Dan Gohman4c7279a2009-10-31 15:04:55 +00004034 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00004035 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00004036 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00004037
Dan Gohman59ae6b92009-07-08 19:23:34 +00004038 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00004039 while (!Worklist.empty()) {
4040 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00004041 if (!Visited.insert(I)) continue;
4042
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004043 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4044 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00004045 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004046 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004047 if (PHINode *PN = dyn_cast<PHINode>(I))
4048 ConstantEvolutionLoopExitValue.erase(PN);
4049 }
4050
4051 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00004052 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00004053
4054 // Forget all contained loops too, to avoid dangling entries in the
4055 // ValuesAtScopes map.
4056 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4057 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00004058}
4059
Eric Christophere6cbfa62010-07-29 01:25:38 +00004060/// forgetValue - This method should be called by the client when it has
4061/// changed a value in a way that may effect its value, or which may
4062/// disconnect it from a def-use chain linking it to a loop.
4063void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00004064 Instruction *I = dyn_cast<Instruction>(V);
4065 if (!I) return;
4066
4067 // Drop information about expressions based on loop-header PHIs.
4068 SmallVector<Instruction *, 16> Worklist;
4069 Worklist.push_back(I);
4070
4071 SmallPtrSet<Instruction *, 8> Visited;
4072 while (!Worklist.empty()) {
4073 I = Worklist.pop_back_val();
4074 if (!Visited.insert(I)) continue;
4075
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004076 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4077 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00004078 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004079 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00004080 if (PHINode *PN = dyn_cast<PHINode>(I))
4081 ConstantEvolutionLoopExitValue.erase(PN);
4082 }
4083
4084 PushDefUseChildren(I, Worklist);
4085 }
4086}
4087
Andrew Trick5116ff62011-07-26 17:19:55 +00004088/// getExact - Get the exact loop backedge taken count considering all loop
4089/// exits. If all exits are computable, this is the minimum computed count.
4090const SCEV *
4091ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4092 // If any exits were not computable, the loop is not computable.
4093 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4094
4095 // We need at least one computable exit.
Andrew Trickfcb43562011-08-02 04:23:35 +00004096 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick5116ff62011-07-26 17:19:55 +00004097 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4098
4099 const SCEV *BECount = 0;
4100 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4101 ENT != 0; ENT = ENT->getNextExit()) {
4102
4103 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4104
4105 if (!BECount)
4106 BECount = ENT->ExactNotTaken;
4107 else
4108 BECount = SE->getUMinFromMismatchedTypes(BECount, ENT->ExactNotTaken);
4109 }
Andrew Trick252ef7a2011-09-02 21:20:46 +00004110 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick5116ff62011-07-26 17:19:55 +00004111 return BECount;
4112}
4113
4114/// getExact - Get the exact not taken count for this loop exit.
4115const SCEV *
Andrew Trickfcb43562011-08-02 04:23:35 +00004116ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick5116ff62011-07-26 17:19:55 +00004117 ScalarEvolution *SE) const {
4118 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4119 ENT != 0; ENT = ENT->getNextExit()) {
4120
Andrew Trickfcb43562011-08-02 04:23:35 +00004121 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick5116ff62011-07-26 17:19:55 +00004122 return ENT->ExactNotTaken;
4123 }
4124 return SE->getCouldNotCompute();
4125}
4126
4127/// getMax - Get the max backedge taken count for the loop.
4128const SCEV *
4129ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4130 return Max ? Max : SE->getCouldNotCompute();
4131}
4132
4133/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4134/// computable exit into a persistent ExitNotTakenInfo array.
4135ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4136 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4137 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4138
4139 if (!Complete)
4140 ExitNotTaken.setIncomplete();
4141
4142 unsigned NumExits = ExitCounts.size();
4143 if (NumExits == 0) return;
4144
Andrew Trickfcb43562011-08-02 04:23:35 +00004145 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick5116ff62011-07-26 17:19:55 +00004146 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4147 if (NumExits == 1) return;
4148
4149 // Handle the rare case of multiple computable exits.
4150 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4151
4152 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4153 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4154 PrevENT->setNextExit(ENT);
Andrew Trickfcb43562011-08-02 04:23:35 +00004155 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick5116ff62011-07-26 17:19:55 +00004156 ENT->ExactNotTaken = ExitCounts[i].second;
4157 }
4158}
4159
4160/// clear - Invalidate this result and free the ExitNotTakenInfo array.
4161void ScalarEvolution::BackedgeTakenInfo::clear() {
Andrew Trickfcb43562011-08-02 04:23:35 +00004162 ExitNotTaken.ExitingBlock = 0;
Andrew Trick5116ff62011-07-26 17:19:55 +00004163 ExitNotTaken.ExactNotTaken = 0;
4164 delete[] ExitNotTaken.getNextExit();
4165}
4166
Dan Gohman46bdfb02009-02-24 18:55:53 +00004167/// ComputeBackedgeTakenCount - Compute the number of times the backedge
4168/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00004169ScalarEvolution::BackedgeTakenInfo
4170ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00004171 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00004172 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00004173
Dan Gohmana334aa72009-06-22 00:31:57 +00004174 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004175 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5116ff62011-07-26 17:19:55 +00004176 bool CouldComputeBECount = true;
4177 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Dan Gohmana334aa72009-06-22 00:31:57 +00004178 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick5116ff62011-07-26 17:19:55 +00004179 ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]);
4180 if (EL.Exact == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004181 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00004182 // we won't be able to compute an exact value for the loop.
Andrew Trick5116ff62011-07-26 17:19:55 +00004183 CouldComputeBECount = false;
4184 else
4185 ExitCounts.push_back(std::make_pair(ExitingBlocks[i], EL.Exact));
4186
Dan Gohman1c343752009-06-27 21:21:31 +00004187 if (MaxBECount == getCouldNotCompute())
Andrew Trick5116ff62011-07-26 17:19:55 +00004188 MaxBECount = EL.Max;
4189 else if (EL.Max != getCouldNotCompute())
4190 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, EL.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004191 }
4192
Andrew Trick5116ff62011-07-26 17:19:55 +00004193 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohmana334aa72009-06-22 00:31:57 +00004194}
4195
Andrew Trick5116ff62011-07-26 17:19:55 +00004196/// ComputeExitLimit - Compute the number of times the backedge of the specified
4197/// loop will execute if it exits via the specified block.
4198ScalarEvolution::ExitLimit
4199ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohmana334aa72009-06-22 00:31:57 +00004200
4201 // Okay, we've chosen an exiting block. See what condition causes us to
4202 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00004203 //
4204 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00004205 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00004206 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004207 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00004208
Chris Lattner8b0e3602007-01-07 02:24:26 +00004209 // At this point, we know we have a conditional branch that determines whether
4210 // the loop is exited. However, we don't know if the branch is executed each
4211 // time through the loop. If not, then the execution count of the branch will
4212 // not be equal to the trip count of the loop.
4213 //
4214 // Currently we check for this by checking to see if the Exit branch goes to
4215 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00004216 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00004217 // loop header. This is common for un-rotated loops.
4218 //
4219 // If both of those tests fail, walk up the unique predecessor chain to the
4220 // header, stopping if there is an edge that doesn't exit the loop. If the
4221 // header is reached, the execution count of the branch will be equal to the
4222 // trip count of the loop.
4223 //
4224 // More extensive analysis could be done to handle more cases here.
4225 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00004226 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00004227 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00004228 ExitBr->getParent() != L->getHeader()) {
4229 // The simple checks failed, try climbing the unique predecessor chain
4230 // up to the header.
4231 bool Ok = false;
4232 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
4233 BasicBlock *Pred = BB->getUniquePredecessor();
4234 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00004235 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004236 TerminatorInst *PredTerm = Pred->getTerminator();
4237 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4238 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4239 if (PredSucc == BB)
4240 continue;
4241 // If the predecessor has a successor that isn't BB and isn't
4242 // outside the loop, assume the worst.
4243 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00004244 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004245 }
4246 if (Pred == L->getHeader()) {
4247 Ok = true;
4248 break;
4249 }
4250 BB = Pred;
4251 }
4252 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00004253 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004254 }
4255
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004256 // Proceed to the next level to examine the exit condition expression.
Andrew Trick5116ff62011-07-26 17:19:55 +00004257 return ComputeExitLimitFromCond(L, ExitBr->getCondition(),
4258 ExitBr->getSuccessor(0),
4259 ExitBr->getSuccessor(1));
Dan Gohmana334aa72009-06-22 00:31:57 +00004260}
4261
Andrew Trick5116ff62011-07-26 17:19:55 +00004262/// ComputeExitLimitFromCond - Compute the number of times the
Dan Gohmana334aa72009-06-22 00:31:57 +00004263/// backedge of the specified loop will execute if its exit condition
4264/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5116ff62011-07-26 17:19:55 +00004265ScalarEvolution::ExitLimit
4266ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4267 Value *ExitCond,
4268 BasicBlock *TBB,
4269 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004270 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00004271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4272 if (BO->getOpcode() == Instruction::And) {
4273 // Recurse on the operands of the and.
Andrew Trick5116ff62011-07-26 17:19:55 +00004274 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4275 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004276 const SCEV *BECount = getCouldNotCompute();
4277 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004278 if (L->contains(TBB)) {
4279 // Both conditions must be true for the loop to continue executing.
4280 // Choose the less conservative count.
Andrew Trick5116ff62011-07-26 17:19:55 +00004281 if (EL0.Exact == getCouldNotCompute() ||
4282 EL1.Exact == getCouldNotCompute())
Dan Gohman1c343752009-06-27 21:21:31 +00004283 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004284 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004285 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4286 if (EL0.Max == getCouldNotCompute())
4287 MaxBECount = EL1.Max;
4288 else if (EL1.Max == getCouldNotCompute())
4289 MaxBECount = EL0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004290 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004291 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004292 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004293 // Both conditions must be true at the same time for the loop to exit.
4294 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004295 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick5116ff62011-07-26 17:19:55 +00004296 if (EL0.Max == EL1.Max)
4297 MaxBECount = EL0.Max;
4298 if (EL0.Exact == EL1.Exact)
4299 BECount = EL0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004300 }
4301
Andrew Trick5116ff62011-07-26 17:19:55 +00004302 return ExitLimit(BECount, MaxBECount);
Dan Gohmana334aa72009-06-22 00:31:57 +00004303 }
4304 if (BO->getOpcode() == Instruction::Or) {
4305 // Recurse on the operands of the or.
Andrew Trick5116ff62011-07-26 17:19:55 +00004306 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4307 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004308 const SCEV *BECount = getCouldNotCompute();
4309 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004310 if (L->contains(FBB)) {
4311 // Both conditions must be false for the loop to continue executing.
4312 // Choose the less conservative count.
Andrew Trick5116ff62011-07-26 17:19:55 +00004313 if (EL0.Exact == getCouldNotCompute() ||
4314 EL1.Exact == getCouldNotCompute())
Dan Gohman1c343752009-06-27 21:21:31 +00004315 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004316 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004317 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4318 if (EL0.Max == getCouldNotCompute())
4319 MaxBECount = EL1.Max;
4320 else if (EL1.Max == getCouldNotCompute())
4321 MaxBECount = EL0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004322 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004323 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004324 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004325 // Both conditions must be false at the same time for the loop to exit.
4326 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004327 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick5116ff62011-07-26 17:19:55 +00004328 if (EL0.Max == EL1.Max)
4329 MaxBECount = EL0.Max;
4330 if (EL0.Exact == EL1.Exact)
4331 BECount = EL0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004332 }
4333
Andrew Trick5116ff62011-07-26 17:19:55 +00004334 return ExitLimit(BECount, MaxBECount);
Dan Gohmana334aa72009-06-22 00:31:57 +00004335 }
4336 }
4337
4338 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004339 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00004340 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Andrew Trick5116ff62011-07-26 17:19:55 +00004341 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004342
Dan Gohman00cb5b72010-02-19 18:12:07 +00004343 // Check for a constant condition. These are normally stripped out by
4344 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4345 // preserve the CFG and is temporarily leaving constant conditions
4346 // in place.
4347 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4348 if (L->contains(FBB) == !CI->getZExtValue())
4349 // The backedge is always taken.
4350 return getCouldNotCompute();
4351 else
4352 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00004353 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00004354 }
4355
Eli Friedman361e54d2009-05-09 12:32:42 +00004356 // If it's not an integer or pointer comparison then compute it the hard way.
Andrew Trick5116ff62011-07-26 17:19:55 +00004357 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmana334aa72009-06-22 00:31:57 +00004358}
4359
Andrew Trick5116ff62011-07-26 17:19:55 +00004360/// ComputeExitLimitFromICmp - Compute the number of times the
Dan Gohmana334aa72009-06-22 00:31:57 +00004361/// backedge of the specified loop will execute if its exit condition
4362/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
Andrew Trick5116ff62011-07-26 17:19:55 +00004363ScalarEvolution::ExitLimit
4364ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
4365 ICmpInst *ExitCond,
4366 BasicBlock *TBB,
4367 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004368
Reid Spencere4d87aa2006-12-23 06:05:41 +00004369 // If the condition was exit on true, convert the condition to exit on false
4370 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00004371 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004372 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004373 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004374 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004375
4376 // Handle common loops like: for (X = "string"; *X; ++X)
4377 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4378 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick5116ff62011-07-26 17:19:55 +00004379 ExitLimit ItCnt =
4380 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004381 if (ItCnt.hasAnyInfo())
4382 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00004383 }
4384
Dan Gohman0bba49c2009-07-07 17:06:11 +00004385 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4386 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00004387
4388 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00004389 LHS = getSCEVAtScope(LHS, L);
4390 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004391
Dan Gohman64a845e2009-06-24 04:48:43 +00004392 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004393 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00004394 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004395 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004396 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004397 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004398 }
4399
Dan Gohman03557dc2010-05-03 16:35:17 +00004400 // Simplify the operands before analyzing them.
4401 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4402
Chris Lattner53e677a2004-04-02 20:23:17 +00004403 // If we have a comparison of a chrec against a constant, try to use value
4404 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004405 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4406 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004407 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004408 // Form the constant range.
4409 ConstantRange CompRange(
4410 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004411
Dan Gohman0bba49c2009-07-07 17:06:11 +00004412 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004413 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004414 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004415
Chris Lattner53e677a2004-04-02 20:23:17 +00004416 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004417 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004418 // Convert to: while (X-Y != 0)
Andrew Trick5116ff62011-07-26 17:19:55 +00004419 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4420 if (EL.hasAnyInfo()) return EL;
Chris Lattner53e677a2004-04-02 20:23:17 +00004421 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004422 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004423 case ICmpInst::ICMP_EQ: { // while (X == Y)
4424 // Convert to: while (X-Y == 0)
Andrew Trick5116ff62011-07-26 17:19:55 +00004425 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4426 if (EL.hasAnyInfo()) return EL;
Chris Lattner53e677a2004-04-02 20:23:17 +00004427 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004428 }
4429 case ICmpInst::ICMP_SLT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004430 ExitLimit EL = HowManyLessThans(LHS, RHS, L, true);
4431 if (EL.hasAnyInfo()) return EL;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004432 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004433 }
4434 case ICmpInst::ICMP_SGT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004435 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
Dan Gohmana1af7572009-04-30 20:47:05 +00004436 getNotSCEV(RHS), L, true);
Andrew Trick5116ff62011-07-26 17:19:55 +00004437 if (EL.hasAnyInfo()) return EL;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004438 break;
4439 }
4440 case ICmpInst::ICMP_ULT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004441 ExitLimit EL = HowManyLessThans(LHS, RHS, L, false);
4442 if (EL.hasAnyInfo()) return EL;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004443 break;
4444 }
4445 case ICmpInst::ICMP_UGT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004446 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
Dan Gohmana1af7572009-04-30 20:47:05 +00004447 getNotSCEV(RHS), L, false);
Andrew Trick5116ff62011-07-26 17:19:55 +00004448 if (EL.hasAnyInfo()) return EL;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004449 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004450 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004451 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004452#if 0
David Greene25e0e872009-12-23 22:18:14 +00004453 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004454 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004455 dbgs() << "[unsigned] ";
4456 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004457 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004458 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004459#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004460 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004461 }
Andrew Trick5116ff62011-07-26 17:19:55 +00004462 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004463}
4464
Chris Lattner673e02b2004-10-12 01:49:27 +00004465static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004466EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4467 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004468 const SCEV *InVal = SE.getConstant(C);
4469 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004470 assert(isa<SCEVConstant>(Val) &&
4471 "Evaluation of SCEV at constant didn't fold correctly?");
4472 return cast<SCEVConstant>(Val)->getValue();
4473}
4474
4475/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4476/// and a GEP expression (missing the pointer index) indexing into it, return
4477/// the addressed element of the initializer or null if the index expression is
4478/// invalid.
4479static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004480GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004481 const std::vector<ConstantInt*> &Indices) {
4482 Constant *Init = GV->getInitializer();
4483 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004484 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004485 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4486 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4487 Init = cast<Constant>(CS->getOperand(Idx));
4488 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4489 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4490 Init = cast<Constant>(CA->getOperand(Idx));
4491 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004492 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004493 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004494 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004495 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004496 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004497 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004498 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004499 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004500 }
4501 return 0;
4502 } else {
4503 return 0; // Unknown initializer type
4504 }
4505 }
4506 return Init;
4507}
4508
Andrew Trick5116ff62011-07-26 17:19:55 +00004509/// ComputeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman46bdfb02009-02-24 18:55:53 +00004510/// 'icmp op load X, cst', try to see if we can compute the backedge
4511/// execution count.
Andrew Trick5116ff62011-07-26 17:19:55 +00004512ScalarEvolution::ExitLimit
4513ScalarEvolution::ComputeLoadConstantCompareExitLimit(
4514 LoadInst *LI,
4515 Constant *RHS,
4516 const Loop *L,
4517 ICmpInst::Predicate predicate) {
4518
Dan Gohman1c343752009-06-27 21:21:31 +00004519 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004520
4521 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004522 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004523 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004524 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004525
4526 // Make sure that it is really a constant global we are gepping, with an
4527 // initializer, and make sure the first IDX is really 0.
4528 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004529 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004530 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4531 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004532 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004533
4534 // Okay, we allow one non-constant index into the GEP instruction.
4535 Value *VarIdx = 0;
4536 std::vector<ConstantInt*> Indexes;
4537 unsigned VarIdxNum = 0;
4538 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4539 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4540 Indexes.push_back(CI);
4541 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004542 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004543 VarIdx = GEP->getOperand(i);
4544 VarIdxNum = i-2;
4545 Indexes.push_back(0);
4546 }
4547
4548 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4549 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004550 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004551 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004552
4553 // We can only recognize very limited forms of loop index expressions, in
4554 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004555 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004556 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004557 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4558 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004559 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004560
4561 unsigned MaxSteps = MaxBruteForceIterations;
4562 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004563 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004564 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004565 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004566
4567 // Form the GEP offset.
4568 Indexes[VarIdxNum] = Val;
4569
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004570 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004571 if (Result == 0) break; // Cannot compute!
4572
4573 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004574 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004575 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004576 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004577#if 0
David Greene25e0e872009-12-23 22:18:14 +00004578 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004579 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4580 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004581#endif
4582 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004583 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004584 }
4585 }
Dan Gohman1c343752009-06-27 21:21:31 +00004586 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004587}
4588
4589
Chris Lattner3221ad02004-04-17 22:58:41 +00004590/// CanConstantFold - Return true if we can constant fold an instruction of the
4591/// specified type, assuming that all operands were constants.
4592static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004593 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004594 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4595 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004596
Chris Lattner3221ad02004-04-17 22:58:41 +00004597 if (const CallInst *CI = dyn_cast<CallInst>(I))
4598 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004599 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004600 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004601}
4602
Chris Lattner3221ad02004-04-17 22:58:41 +00004603/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4604/// in the loop that V is derived from. We allow arbitrary operations along the
4605/// way, but the operands of an operation must either be constants or a value
4606/// derived from a constant PHI. If this expression does not fit with these
4607/// constraints, return null.
4608static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4609 // If this is not an instruction, or if this is an instruction outside of the
4610 // loop, it can't be derived from a loop PHI.
4611 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004612 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004613
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004614 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004615 if (L->getHeader() == I->getParent())
4616 return PN;
4617 else
4618 // We don't currently keep track of the control flow needed to evaluate
4619 // PHIs, so we cannot handle PHIs inside of loops.
4620 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004621 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004622
4623 // If we won't be able to constant fold this expression even if the operands
4624 // are constants, return early.
4625 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004626
Chris Lattner3221ad02004-04-17 22:58:41 +00004627 // Otherwise, we can evaluate this instruction if all of its operands are
4628 // constant or derived from a PHI node themselves.
4629 PHINode *PHI = 0;
4630 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004631 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004632 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4633 if (P == 0) return 0; // Not evolving from PHI
4634 if (PHI == 0)
4635 PHI = P;
4636 else if (PHI != P)
4637 return 0; // Evolving from multiple different PHIs.
4638 }
4639
4640 // This is a expression evolving from a constant PHI!
4641 return PHI;
4642}
4643
4644/// EvaluateExpression - Given an expression that passes the
4645/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4646/// in the loop has the value PHIVal. If we can't fold this expression for some
4647/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004648static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4649 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004650 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004651 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004652 Instruction *I = cast<Instruction>(V);
4653
Dan Gohman9d4588f2010-06-22 13:15:46 +00004654 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004655
4656 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004657 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004658 if (Operands[i] == 0) return 0;
4659 }
4660
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004661 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004662 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004663 Operands[1], TD);
Jay Foad1d2f5692011-07-19 13:32:40 +00004664 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004665}
4666
4667/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4668/// in the header of its containing loop, we know the loop executes a
4669/// constant number of times, and the PHI node is just a recurrence
4670/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004671Constant *
4672ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004673 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004674 const Loop *L) {
Dan Gohman77a2c4c2011-05-09 18:44:09 +00004675 DenseMap<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004676 ConstantEvolutionLoopExitValue.find(PN);
4677 if (I != ConstantEvolutionLoopExitValue.end())
4678 return I->second;
4679
Dan Gohmane0567812010-04-08 23:03:40 +00004680 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004681 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4682
4683 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4684
4685 // Since the loop is canonicalized, the PHI node must have two entries. One
4686 // entry must be a constant (coming in from outside of the loop), and the
4687 // second must be derived from the same PHI.
4688 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4689 Constant *StartCST =
4690 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4691 if (StartCST == 0)
4692 return RetVal = 0; // Must be a constant.
4693
4694 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004695 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4696 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004697 return RetVal = 0; // Not derived from same PHI.
4698
4699 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004700 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004701 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004702
Dan Gohman46bdfb02009-02-24 18:55:53 +00004703 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004704 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004705 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4706 if (IterationNum == NumIterations)
4707 return RetVal = PHIVal; // Got exit value!
4708
4709 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004710 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004711 if (NextPHI == PHIVal)
4712 return RetVal = NextPHI; // Stopped evolving!
4713 if (NextPHI == 0)
4714 return 0; // Couldn't evaluate!
4715 PHIVal = NextPHI;
4716 }
4717}
4718
Andrew Trick5116ff62011-07-26 17:19:55 +00004719/// ComputeExitCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004720/// constant number of times (the condition evolves only from constants),
4721/// try to evaluate a few iterations of the loop until we get the exit
4722/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004723/// evaluate the trip count of the loop, return getCouldNotCompute().
Andrew Trick5116ff62011-07-26 17:19:55 +00004724const SCEV * ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
4725 Value *Cond,
4726 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004727 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004728 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004729
Dan Gohmanb92654d2010-06-19 14:17:24 +00004730 // If the loop is canonicalized, the PHI will have exactly two entries.
4731 // That's the only form we support here.
4732 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4733
4734 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004735 // second must be derived from the same PHI.
4736 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4737 Constant *StartCST =
4738 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004739 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004740
4741 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004742 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4743 !isa<Constant>(BEValue))
4744 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004745
4746 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4747 // the loop symbolically to determine when the condition gets a value of
4748 // "ExitWhen".
4749 unsigned IterationNum = 0;
4750 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4751 for (Constant *PHIVal = StartCST;
4752 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004753 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004754 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004755
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004756 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004757 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004758
Reid Spencere8019bb2007-03-01 07:25:48 +00004759 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004760 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004761 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004762 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004763
Chris Lattner3221ad02004-04-17 22:58:41 +00004764 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004765 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004766 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004767 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004768 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004769 }
4770
4771 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004772 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004773}
4774
Dan Gohmane7125f42009-09-03 15:00:26 +00004775/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004776/// at the specified scope in the program. The L value specifies a loop
4777/// nest to evaluate the expression at, where null is the top-level or a
4778/// specified loop is immediately inside of the loop.
4779///
4780/// This method can be used to compute the exit value for a variable defined
4781/// in a loop by querying what the value will hold in the parent loop.
4782///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004783/// In the case that a relevant loop exit value cannot be computed, the
4784/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004785const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004786 // Check to see if we've folded this expression at this loop before.
4787 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4788 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4789 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4790 if (!Pair.second)
4791 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004792
Dan Gohman42214892009-08-31 21:15:23 +00004793 // Otherwise compute it.
4794 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004795 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004796 return C;
4797}
4798
4799const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004800 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004801
Nick Lewycky3e630762008-02-20 06:48:22 +00004802 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004803 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004804 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004805 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004806 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004807 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4808 if (PHINode *PN = dyn_cast<PHINode>(I))
4809 if (PN->getParent() == LI->getHeader()) {
4810 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004811 // to see if the loop that contains it has a known backedge-taken
4812 // count. If so, we may be able to force computation of the exit
4813 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004814 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004815 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004816 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004817 // Okay, we know how many times the containing loop executes. If
4818 // this is a constant evolving PHI node, get the final value at
4819 // the specified iteration number.
4820 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004821 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004822 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004823 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004824 }
4825 }
4826
Reid Spencer09906f32006-12-04 21:33:23 +00004827 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004828 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004829 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004830 // result. This is particularly useful for computing loop exit values.
4831 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004832 SmallVector<Constant *, 4> Operands;
4833 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004834 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4835 Value *Op = I->getOperand(i);
4836 if (Constant *C = dyn_cast<Constant>(Op)) {
4837 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004838 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004839 }
Dan Gohman11046452010-06-29 23:43:06 +00004840
4841 // If any of the operands is non-constant and if they are
4842 // non-integer and non-pointer, don't even try to analyze them
4843 // with scev techniques.
4844 if (!isSCEVable(Op->getType()))
4845 return V;
4846
4847 const SCEV *OrigV = getSCEV(Op);
4848 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4849 MadeImprovement |= OrigV != OpV;
4850
4851 Constant *C = 0;
4852 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4853 C = SC->getValue();
4854 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4855 C = dyn_cast<Constant>(SU->getValue());
4856 if (!C) return V;
4857 if (C->getType() != Op->getType())
4858 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4859 Op->getType(),
4860 false),
4861 C, Op->getType());
4862 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004863 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004864
Dan Gohman11046452010-06-29 23:43:06 +00004865 // Check to see if getSCEVAtScope actually made an improvement.
4866 if (MadeImprovement) {
4867 Constant *C = 0;
4868 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4869 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4870 Operands[0], Operands[1], TD);
4871 else
4872 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00004873 Operands, TD);
Dan Gohman11046452010-06-29 23:43:06 +00004874 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004875 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004876 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004877 }
4878 }
4879
4880 // This is some other type of SCEVUnknown, just return it.
4881 return V;
4882 }
4883
Dan Gohman622ed672009-05-04 22:02:23 +00004884 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004885 // Avoid performing the look-up in the common case where the specified
4886 // expression has no loop-variant portions.
4887 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004888 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004889 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004890 // Okay, at least one of these operands is loop variant but might be
4891 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004892 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4893 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004894 NewOps.push_back(OpAtScope);
4895
4896 for (++i; i != e; ++i) {
4897 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004898 NewOps.push_back(OpAtScope);
4899 }
4900 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004901 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004902 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004903 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004904 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004905 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004906 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004907 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004908 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004909 }
4910 }
4911 // If we got here, all operands are loop invariant.
4912 return Comm;
4913 }
4914
Dan Gohman622ed672009-05-04 22:02:23 +00004915 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004916 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4917 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004918 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4919 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004920 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004921 }
4922
4923 // If this is a loop recurrence for a loop that does not contain L, then we
4924 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004925 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004926 // First, attempt to evaluate each operand.
4927 // Avoid performing the look-up in the common case where the specified
4928 // expression has no loop-variant portions.
4929 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4930 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4931 if (OpAtScope == AddRec->getOperand(i))
4932 continue;
4933
4934 // Okay, at least one of these operands is loop variant but might be
4935 // foldable. Build a new instance of the folded commutative expression.
4936 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4937 AddRec->op_begin()+i);
4938 NewOps.push_back(OpAtScope);
4939 for (++i; i != e; ++i)
4940 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4941
Andrew Trick3f95c882011-04-27 01:21:25 +00004942 const SCEV *FoldedRec =
Andrew Trick3228cc22011-03-14 16:50:06 +00004943 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick3f95c882011-04-27 01:21:25 +00004944 AddRec->getNoWrapFlags(SCEV::FlagNW));
4945 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick104f4ad2011-04-27 05:42:17 +00004946 // The addrec may be folded to a nonrecurrence, for example, if the
4947 // induction variable is multiplied by zero after constant folding. Go
4948 // ahead and return the folded value.
Andrew Trick3f95c882011-04-27 01:21:25 +00004949 if (!AddRec)
4950 return FoldedRec;
Dan Gohman11046452010-06-29 23:43:06 +00004951 break;
4952 }
4953
4954 // If the scope is outside the addrec's loop, evaluate it by using the
4955 // loop exit value of the addrec.
4956 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004957 // To evaluate this recurrence, we need to know how many times the AddRec
4958 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004959 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004960 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004961
Eli Friedmanb42a6262008-08-04 23:49:06 +00004962 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004963 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004964 }
Dan Gohman11046452010-06-29 23:43:06 +00004965
Dan Gohmand594e6f2009-05-24 23:25:42 +00004966 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004967 }
4968
Dan Gohman622ed672009-05-04 22:02:23 +00004969 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004970 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004971 if (Op == Cast->getOperand())
4972 return Cast; // must be loop invariant
4973 return getZeroExtendExpr(Op, Cast->getType());
4974 }
4975
Dan Gohman622ed672009-05-04 22:02:23 +00004976 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004977 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004978 if (Op == Cast->getOperand())
4979 return Cast; // must be loop invariant
4980 return getSignExtendExpr(Op, Cast->getType());
4981 }
4982
Dan Gohman622ed672009-05-04 22:02:23 +00004983 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004984 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004985 if (Op == Cast->getOperand())
4986 return Cast; // must be loop invariant
4987 return getTruncateExpr(Op, Cast->getType());
4988 }
4989
Torok Edwinc23197a2009-07-14 16:55:14 +00004990 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004991 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004992}
4993
Dan Gohman66a7e852009-05-08 20:38:54 +00004994/// getSCEVAtScope - This is a convenience function which does
4995/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004996const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004997 return getSCEVAtScope(getSCEV(V), L);
4998}
4999
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005000/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5001/// following equation:
5002///
5003/// A * X = B (mod N)
5004///
5005/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5006/// A and B isn't important.
5007///
5008/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005009static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005010 ScalarEvolution &SE) {
5011 uint32_t BW = A.getBitWidth();
5012 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5013 assert(A != 0 && "A must be non-zero.");
5014
5015 // 1. D = gcd(A, N)
5016 //
5017 // The gcd of A and N may have only one prime factor: 2. The number of
5018 // trailing zeros in A is its multiplicity
5019 uint32_t Mult2 = A.countTrailingZeros();
5020 // D = 2^Mult2
5021
5022 // 2. Check if B is divisible by D.
5023 //
5024 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5025 // is not less than multiplicity of this prime factor for D.
5026 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005027 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005028
5029 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5030 // modulo (N / D).
5031 //
5032 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5033 // bit width during computations.
5034 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5035 APInt Mod(BW + 1, 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00005036 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005037 APInt I = AD.multiplicativeInverse(Mod);
5038
5039 // 4. Compute the minimum unsigned root of the equation:
5040 // I * (B / D) mod (N / D)
5041 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5042
5043 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5044 // bits.
5045 return SE.getConstant(Result.trunc(BW));
5046}
Chris Lattner53e677a2004-04-02 20:23:17 +00005047
5048/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5049/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5050/// might be the same) or two SCEVCouldNotCompute objects.
5051///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005052static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00005053SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005054 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005055 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5056 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5057 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005058
Chris Lattner53e677a2004-04-02 20:23:17 +00005059 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00005060 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00005061 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005062 return std::make_pair(CNC, CNC);
5063 }
5064
Reid Spencere8019bb2007-03-01 07:25:48 +00005065 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00005066 const APInt &L = LC->getValue()->getValue();
5067 const APInt &M = MC->getValue()->getValue();
5068 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00005069 APInt Two(BitWidth, 2);
5070 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005071
Dan Gohman64a845e2009-06-24 04:48:43 +00005072 {
Reid Spencere8019bb2007-03-01 07:25:48 +00005073 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00005074 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00005075 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5076 // The B coefficient is M-N/2
5077 APInt B(M);
5078 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005079
Reid Spencere8019bb2007-03-01 07:25:48 +00005080 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00005081 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00005082
Reid Spencere8019bb2007-03-01 07:25:48 +00005083 // Compute the B^2-4ac term.
5084 APInt SqrtTerm(B);
5085 SqrtTerm *= B;
5086 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00005087
Reid Spencere8019bb2007-03-01 07:25:48 +00005088 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5089 // integer value or else APInt::sqrt() will assert.
5090 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005091
Dan Gohman64a845e2009-06-24 04:48:43 +00005092 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00005093 // The divisions must be performed as signed divisions.
5094 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00005095 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00005096 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00005097 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00005098 return std::make_pair(CNC, CNC);
5099 }
5100
Owen Andersone922c022009-07-22 00:24:57 +00005101 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00005102
5103 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00005104 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00005105 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00005106 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005107
Dan Gohman64a845e2009-06-24 04:48:43 +00005108 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00005109 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00005110 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00005111}
5112
5113/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005114/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick3228cc22011-03-14 16:50:06 +00005115///
5116/// This is only used for loops with a "x != y" exit test. The exit condition is
5117/// now expressed as a single expression, V = x-y. So the exit test is
5118/// effectively V != 0. We know and take advantage of the fact that this
5119/// expression only being used in a comparison by zero context.
Andrew Trick5116ff62011-07-26 17:19:55 +00005120ScalarEvolution::ExitLimit
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005121ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005122 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00005123 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005124 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00005125 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00005126 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005127 }
5128
Dan Gohman35738ac2009-05-04 22:30:44 +00005129 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00005130 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005131 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005132
Chris Lattner7975e3e2011-01-09 22:39:48 +00005133 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
5134 // the quadratic equation to solve it.
5135 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
5136 std::pair<const SCEV *,const SCEV *> Roots =
5137 SolveQuadraticEquation(AddRec, *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00005138 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5139 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005140 if (R1 && R2) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00005141#if 0
David Greene25e0e872009-12-23 22:18:14 +00005142 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005143 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00005144#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00005145 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005146 if (ConstantInt *CB =
Chris Lattner53e1d452011-01-09 22:58:47 +00005147 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
5148 R1->getValue(),
5149 R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005150 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005151 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick635f7182011-03-09 17:23:39 +00005152
Chris Lattner53e677a2004-04-02 20:23:17 +00005153 // We can only use this value if the chrec ends up with an exact zero
5154 // value at this index. When solving for "X*X != 5", for example, we
5155 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005156 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00005157 if (Val->isZero())
5158 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00005159 }
5160 }
Chris Lattner7975e3e2011-01-09 22:39:48 +00005161 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005162 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005163
Chris Lattner7975e3e2011-01-09 22:39:48 +00005164 // Otherwise we can only handle this if it is affine.
5165 if (!AddRec->isAffine())
5166 return getCouldNotCompute();
5167
5168 // If this is an affine expression, the execution count of this branch is
5169 // the minimum unsigned root of the following equation:
5170 //
5171 // Start + Step*N = 0 (mod 2^BW)
5172 //
5173 // equivalent to:
5174 //
5175 // Step*N = -Start (mod 2^BW)
5176 //
5177 // where BW is the common bit width of Start and Step.
5178
5179 // Get the initial value for the loop.
5180 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
5181 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
5182
5183 // For now we handle only constant steps.
Andrew Trick3228cc22011-03-14 16:50:06 +00005184 //
5185 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
5186 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
5187 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
5188 // We have not yet seen any such cases.
Chris Lattner7975e3e2011-01-09 22:39:48 +00005189 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5190 if (StepC == 0)
5191 return getCouldNotCompute();
5192
Andrew Trick3228cc22011-03-14 16:50:06 +00005193 // For positive steps (counting up until unsigned overflow):
5194 // N = -Start/Step (as unsigned)
5195 // For negative steps (counting down to zero):
5196 // N = Start/-Step
5197 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005198 bool CountDown = StepC->getValue()->getValue().isNegative();
5199 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick3228cc22011-03-14 16:50:06 +00005200
5201 // Handle unitary steps, which cannot wraparound.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005202 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5203 // N = Distance (as unsigned)
Nick Lewyckyb2840fd2011-09-06 02:43:13 +00005204 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue())
5205 return Distance;
Andrew Trick635f7182011-03-09 17:23:39 +00005206
Andrew Trickdcfd4042011-03-14 17:28:02 +00005207 // If the recurrence is known not to wraparound, unsigned divide computes the
5208 // back edge count. We know that the value will either become zero (and thus
5209 // the loop terminates), that the loop will terminate through some other exit
5210 // condition first, or that the loop has undefined behavior. This means
5211 // we can't "miss" the exit value, even with nonunit stride.
5212 //
5213 // FIXME: Prove that loops always exhibits *acceptable* undefined
5214 // behavior. Loops must exhibit defined behavior until a wrapped value is
5215 // actually used. So the trip count computed by udiv could be smaller than the
5216 // number of well-defined iterations.
5217 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5218 // FIXME: We really want an "isexact" bit for udiv.
5219 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005220
5221 // Then, try to solve the above equation provided that Start is constant.
5222 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5223 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5224 -StartC->getValue()->getValue(),
5225 *this);
Dan Gohman1c343752009-06-27 21:21:31 +00005226 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005227}
5228
5229/// HowFarToNonZero - Return the number of times a backedge checking the
5230/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005231/// CouldNotCompute
Andrew Trick5116ff62011-07-26 17:19:55 +00005232ScalarEvolution::ExitLimit
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005233ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005234 // Loops that look like: while (X == 0) are very strange indeed. We don't
5235 // handle them yet except for the trivial case. This could be expanded in the
5236 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005237
Chris Lattner53e677a2004-04-02 20:23:17 +00005238 // If the value is a constant, check to see if it is known to be non-zero
5239 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00005240 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00005241 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00005242 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00005243 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005244 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005245
Chris Lattner53e677a2004-04-02 20:23:17 +00005246 // We could implement others, but I really doubt anyone writes loops like
5247 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00005248 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005249}
5250
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005251/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5252/// (which may not be an immediate predecessor) which has exactly one
5253/// successor from which BB is reachable, or null if no such block is
5254/// found.
5255///
Dan Gohman005752b2010-04-15 16:19:08 +00005256std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005257ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00005258 // If the block has a unique predecessor, then there is no path from the
5259 // predecessor to the block that does not go through the direct edge
5260 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005261 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00005262 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005263
5264 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00005265 // If the header has a unique predecessor outside the loop, it must be
5266 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005267 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00005268 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005269
Dan Gohman005752b2010-04-15 16:19:08 +00005270 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005271}
5272
Dan Gohman763bad12009-06-20 00:35:32 +00005273/// HasSameValue - SCEV structural equivalence is usually sufficient for
5274/// testing whether two expressions are equal, however for the purposes of
5275/// looking for a condition guarding a loop, it can be useful to be a little
5276/// more general, since a front-end may have replicated the controlling
5277/// expression.
5278///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005279static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00005280 // Quick check to see if they are the same SCEV.
5281 if (A == B) return true;
5282
5283 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5284 // two different instructions with the same value. Check for this case.
5285 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5286 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5287 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5288 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00005289 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00005290 return true;
5291
5292 // Otherwise assume they may have a different value.
5293 return false;
5294}
5295
Dan Gohmane9796502010-04-24 01:28:42 +00005296/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5297/// predicate Pred. Return true iff any changes were made.
5298///
5299bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5300 const SCEV *&LHS, const SCEV *&RHS) {
5301 bool Changed = false;
5302
5303 // Canonicalize a constant to the right side.
5304 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5305 // Check for both operands constant.
5306 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5307 if (ConstantExpr::getICmp(Pred,
5308 LHSC->getValue(),
5309 RHSC->getValue())->isNullValue())
5310 goto trivially_false;
5311 else
5312 goto trivially_true;
5313 }
5314 // Otherwise swap the operands to put the constant on the right.
5315 std::swap(LHS, RHS);
5316 Pred = ICmpInst::getSwappedPredicate(Pred);
5317 Changed = true;
5318 }
5319
5320 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00005321 // addrec's loop, put the addrec on the left. Also make a dominance check,
5322 // as both operands could be addrecs loop-invariant in each other's loop.
5323 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5324 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00005325 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00005326 std::swap(LHS, RHS);
5327 Pred = ICmpInst::getSwappedPredicate(Pred);
5328 Changed = true;
5329 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00005330 }
Dan Gohmane9796502010-04-24 01:28:42 +00005331
5332 // If there's a constant operand, canonicalize comparisons with boundary
5333 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5334 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5335 const APInt &RA = RC->getValue()->getValue();
5336 switch (Pred) {
5337 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5338 case ICmpInst::ICMP_EQ:
5339 case ICmpInst::ICMP_NE:
5340 break;
5341 case ICmpInst::ICMP_UGE:
5342 if ((RA - 1).isMinValue()) {
5343 Pred = ICmpInst::ICMP_NE;
5344 RHS = getConstant(RA - 1);
5345 Changed = true;
5346 break;
5347 }
5348 if (RA.isMaxValue()) {
5349 Pred = ICmpInst::ICMP_EQ;
5350 Changed = true;
5351 break;
5352 }
5353 if (RA.isMinValue()) goto trivially_true;
5354
5355 Pred = ICmpInst::ICMP_UGT;
5356 RHS = getConstant(RA - 1);
5357 Changed = true;
5358 break;
5359 case ICmpInst::ICMP_ULE:
5360 if ((RA + 1).isMaxValue()) {
5361 Pred = ICmpInst::ICMP_NE;
5362 RHS = getConstant(RA + 1);
5363 Changed = true;
5364 break;
5365 }
5366 if (RA.isMinValue()) {
5367 Pred = ICmpInst::ICMP_EQ;
5368 Changed = true;
5369 break;
5370 }
5371 if (RA.isMaxValue()) goto trivially_true;
5372
5373 Pred = ICmpInst::ICMP_ULT;
5374 RHS = getConstant(RA + 1);
5375 Changed = true;
5376 break;
5377 case ICmpInst::ICMP_SGE:
5378 if ((RA - 1).isMinSignedValue()) {
5379 Pred = ICmpInst::ICMP_NE;
5380 RHS = getConstant(RA - 1);
5381 Changed = true;
5382 break;
5383 }
5384 if (RA.isMaxSignedValue()) {
5385 Pred = ICmpInst::ICMP_EQ;
5386 Changed = true;
5387 break;
5388 }
5389 if (RA.isMinSignedValue()) goto trivially_true;
5390
5391 Pred = ICmpInst::ICMP_SGT;
5392 RHS = getConstant(RA - 1);
5393 Changed = true;
5394 break;
5395 case ICmpInst::ICMP_SLE:
5396 if ((RA + 1).isMaxSignedValue()) {
5397 Pred = ICmpInst::ICMP_NE;
5398 RHS = getConstant(RA + 1);
5399 Changed = true;
5400 break;
5401 }
5402 if (RA.isMinSignedValue()) {
5403 Pred = ICmpInst::ICMP_EQ;
5404 Changed = true;
5405 break;
5406 }
5407 if (RA.isMaxSignedValue()) goto trivially_true;
5408
5409 Pred = ICmpInst::ICMP_SLT;
5410 RHS = getConstant(RA + 1);
5411 Changed = true;
5412 break;
5413 case ICmpInst::ICMP_UGT:
5414 if (RA.isMinValue()) {
5415 Pred = ICmpInst::ICMP_NE;
5416 Changed = true;
5417 break;
5418 }
5419 if ((RA + 1).isMaxValue()) {
5420 Pred = ICmpInst::ICMP_EQ;
5421 RHS = getConstant(RA + 1);
5422 Changed = true;
5423 break;
5424 }
5425 if (RA.isMaxValue()) goto trivially_false;
5426 break;
5427 case ICmpInst::ICMP_ULT:
5428 if (RA.isMaxValue()) {
5429 Pred = ICmpInst::ICMP_NE;
5430 Changed = true;
5431 break;
5432 }
5433 if ((RA - 1).isMinValue()) {
5434 Pred = ICmpInst::ICMP_EQ;
5435 RHS = getConstant(RA - 1);
5436 Changed = true;
5437 break;
5438 }
5439 if (RA.isMinValue()) goto trivially_false;
5440 break;
5441 case ICmpInst::ICMP_SGT:
5442 if (RA.isMinSignedValue()) {
5443 Pred = ICmpInst::ICMP_NE;
5444 Changed = true;
5445 break;
5446 }
5447 if ((RA + 1).isMaxSignedValue()) {
5448 Pred = ICmpInst::ICMP_EQ;
5449 RHS = getConstant(RA + 1);
5450 Changed = true;
5451 break;
5452 }
5453 if (RA.isMaxSignedValue()) goto trivially_false;
5454 break;
5455 case ICmpInst::ICMP_SLT:
5456 if (RA.isMaxSignedValue()) {
5457 Pred = ICmpInst::ICMP_NE;
5458 Changed = true;
5459 break;
5460 }
5461 if ((RA - 1).isMinSignedValue()) {
5462 Pred = ICmpInst::ICMP_EQ;
5463 RHS = getConstant(RA - 1);
5464 Changed = true;
5465 break;
5466 }
5467 if (RA.isMinSignedValue()) goto trivially_false;
5468 break;
5469 }
5470 }
5471
5472 // Check for obvious equality.
5473 if (HasSameValue(LHS, RHS)) {
5474 if (ICmpInst::isTrueWhenEqual(Pred))
5475 goto trivially_true;
5476 if (ICmpInst::isFalseWhenEqual(Pred))
5477 goto trivially_false;
5478 }
5479
Dan Gohman03557dc2010-05-03 16:35:17 +00005480 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5481 // adding or subtracting 1 from one of the operands.
5482 switch (Pred) {
5483 case ICmpInst::ICMP_SLE:
5484 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5485 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005486 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005487 Pred = ICmpInst::ICMP_SLT;
5488 Changed = true;
5489 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005490 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005491 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005492 Pred = ICmpInst::ICMP_SLT;
5493 Changed = true;
5494 }
5495 break;
5496 case ICmpInst::ICMP_SGE:
5497 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005498 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005499 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005500 Pred = ICmpInst::ICMP_SGT;
5501 Changed = true;
5502 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5503 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005504 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005505 Pred = ICmpInst::ICMP_SGT;
5506 Changed = true;
5507 }
5508 break;
5509 case ICmpInst::ICMP_ULE:
5510 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005511 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005512 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005513 Pred = ICmpInst::ICMP_ULT;
5514 Changed = true;
5515 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005516 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005517 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005518 Pred = ICmpInst::ICMP_ULT;
5519 Changed = true;
5520 }
5521 break;
5522 case ICmpInst::ICMP_UGE:
5523 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005524 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005525 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005526 Pred = ICmpInst::ICMP_UGT;
5527 Changed = true;
5528 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005529 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005530 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005531 Pred = ICmpInst::ICMP_UGT;
5532 Changed = true;
5533 }
5534 break;
5535 default:
5536 break;
5537 }
5538
Dan Gohmane9796502010-04-24 01:28:42 +00005539 // TODO: More simplifications are possible here.
5540
5541 return Changed;
5542
5543trivially_true:
5544 // Return 0 == 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005545 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005546 Pred = ICmpInst::ICMP_EQ;
5547 return true;
5548
5549trivially_false:
5550 // Return 0 != 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005551 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005552 Pred = ICmpInst::ICMP_NE;
5553 return true;
5554}
5555
Dan Gohman85b05a22009-07-13 21:35:55 +00005556bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5557 return getSignedRange(S).getSignedMax().isNegative();
5558}
5559
5560bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5561 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5562}
5563
5564bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5565 return !getSignedRange(S).getSignedMin().isNegative();
5566}
5567
5568bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5569 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5570}
5571
5572bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5573 return isKnownNegative(S) || isKnownPositive(S);
5574}
5575
5576bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5577 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005578 // Canonicalize the inputs first.
5579 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5580
Dan Gohman53c66ea2010-04-11 22:16:48 +00005581 // If LHS or RHS is an addrec, check to see if the condition is true in
5582 // every iteration of the loop.
5583 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5584 if (isLoopEntryGuardedByCond(
5585 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5586 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005587 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005588 return true;
5589 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5590 if (isLoopEntryGuardedByCond(
5591 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5592 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005593 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005594 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005595
Dan Gohman53c66ea2010-04-11 22:16:48 +00005596 // Otherwise see what can be done with known constant ranges.
5597 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5598}
5599
5600bool
5601ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5602 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005603 if (HasSameValue(LHS, RHS))
5604 return ICmpInst::isTrueWhenEqual(Pred);
5605
Dan Gohman53c66ea2010-04-11 22:16:48 +00005606 // This code is split out from isKnownPredicate because it is called from
5607 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005608 switch (Pred) {
5609 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005610 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005611 break;
5612 case ICmpInst::ICMP_SGT:
5613 Pred = ICmpInst::ICMP_SLT;
5614 std::swap(LHS, RHS);
5615 case ICmpInst::ICMP_SLT: {
5616 ConstantRange LHSRange = getSignedRange(LHS);
5617 ConstantRange RHSRange = getSignedRange(RHS);
5618 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5619 return true;
5620 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5621 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005622 break;
5623 }
5624 case ICmpInst::ICMP_SGE:
5625 Pred = ICmpInst::ICMP_SLE;
5626 std::swap(LHS, RHS);
5627 case ICmpInst::ICMP_SLE: {
5628 ConstantRange LHSRange = getSignedRange(LHS);
5629 ConstantRange RHSRange = getSignedRange(RHS);
5630 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5631 return true;
5632 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5633 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005634 break;
5635 }
5636 case ICmpInst::ICMP_UGT:
5637 Pred = ICmpInst::ICMP_ULT;
5638 std::swap(LHS, RHS);
5639 case ICmpInst::ICMP_ULT: {
5640 ConstantRange LHSRange = getUnsignedRange(LHS);
5641 ConstantRange RHSRange = getUnsignedRange(RHS);
5642 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5643 return true;
5644 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5645 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005646 break;
5647 }
5648 case ICmpInst::ICMP_UGE:
5649 Pred = ICmpInst::ICMP_ULE;
5650 std::swap(LHS, RHS);
5651 case ICmpInst::ICMP_ULE: {
5652 ConstantRange LHSRange = getUnsignedRange(LHS);
5653 ConstantRange RHSRange = getUnsignedRange(RHS);
5654 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5655 return true;
5656 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5657 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005658 break;
5659 }
5660 case ICmpInst::ICMP_NE: {
5661 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5662 return true;
5663 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5664 return true;
5665
5666 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5667 if (isKnownNonZero(Diff))
5668 return true;
5669 break;
5670 }
5671 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005672 // The check at the top of the function catches the case where
5673 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005674 break;
5675 }
5676 return false;
5677}
5678
5679/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5680/// protected by a conditional between LHS and RHS. This is used to
5681/// to eliminate casts.
5682bool
5683ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5684 ICmpInst::Predicate Pred,
5685 const SCEV *LHS, const SCEV *RHS) {
5686 // Interpret a null as meaning no loop, where there is obviously no guard
5687 // (interprocedural conditions notwithstanding).
5688 if (!L) return true;
5689
5690 BasicBlock *Latch = L->getLoopLatch();
5691 if (!Latch)
5692 return false;
5693
5694 BranchInst *LoopContinuePredicate =
5695 dyn_cast<BranchInst>(Latch->getTerminator());
5696 if (!LoopContinuePredicate ||
5697 LoopContinuePredicate->isUnconditional())
5698 return false;
5699
Dan Gohmanaf08a362010-08-10 23:46:30 +00005700 return isImpliedCond(Pred, LHS, RHS,
5701 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005702 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005703}
5704
Dan Gohman3948d0b2010-04-11 19:27:13 +00005705/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005706/// by a conditional between LHS and RHS. This is used to help avoid max
5707/// expressions in loop trip counts, and to eliminate casts.
5708bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005709ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5710 ICmpInst::Predicate Pred,
5711 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005712 // Interpret a null as meaning no loop, where there is obviously no guard
5713 // (interprocedural conditions notwithstanding).
5714 if (!L) return false;
5715
Dan Gohman859b4822009-05-18 15:36:09 +00005716 // Starting at the loop predecessor, climb up the predecessor chain, as long
5717 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005718 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005719 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005720 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005721 Pair.first;
5722 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005723
5724 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005725 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005726 if (!LoopEntryPredicate ||
5727 LoopEntryPredicate->isUnconditional())
5728 continue;
5729
Dan Gohmanaf08a362010-08-10 23:46:30 +00005730 if (isImpliedCond(Pred, LHS, RHS,
5731 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005732 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005733 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005734 }
5735
Dan Gohman38372182008-08-12 20:17:31 +00005736 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005737}
5738
Dan Gohman0f4b2852009-07-21 23:03:19 +00005739/// isImpliedCond - Test whether the condition described by Pred, LHS,
5740/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005741bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005742 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005743 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005744 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005745 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005747 if (BO->getOpcode() == Instruction::And) {
5748 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005749 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5750 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005751 } else if (BO->getOpcode() == Instruction::Or) {
5752 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005753 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5754 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005755 }
5756 }
5757
Dan Gohmanaf08a362010-08-10 23:46:30 +00005758 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005759 if (!ICI) return false;
5760
Dan Gohman85b05a22009-07-13 21:35:55 +00005761 // Bail if the ICmp's operands' types are wider than the needed type
5762 // before attempting to call getSCEV on them. This avoids infinite
5763 // recursion, since the analysis of widening casts can require loop
5764 // exit condition information for overflow checking, which would
5765 // lead back here.
5766 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005767 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005768 return false;
5769
Dan Gohman0f4b2852009-07-21 23:03:19 +00005770 // Now that we found a conditional branch that dominates the loop, check to
5771 // see if it is the comparison we are looking for.
5772 ICmpInst::Predicate FoundPred;
5773 if (Inverse)
5774 FoundPred = ICI->getInversePredicate();
5775 else
5776 FoundPred = ICI->getPredicate();
5777
5778 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5779 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005780
5781 // Balance the types. The case where FoundLHS' type is wider than
5782 // LHS' type is checked for above.
5783 if (getTypeSizeInBits(LHS->getType()) >
5784 getTypeSizeInBits(FoundLHS->getType())) {
5785 if (CmpInst::isSigned(Pred)) {
5786 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5787 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5788 } else {
5789 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5790 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5791 }
5792 }
5793
Dan Gohman0f4b2852009-07-21 23:03:19 +00005794 // Canonicalize the query to match the way instcombine will have
5795 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005796 if (SimplifyICmpOperands(Pred, LHS, RHS))
5797 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005798 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005799 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5800 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005801 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005802
5803 // Check to see if we can make the LHS or RHS match.
5804 if (LHS == FoundRHS || RHS == FoundLHS) {
5805 if (isa<SCEVConstant>(RHS)) {
5806 std::swap(FoundLHS, FoundRHS);
5807 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5808 } else {
5809 std::swap(LHS, RHS);
5810 Pred = ICmpInst::getSwappedPredicate(Pred);
5811 }
5812 }
5813
5814 // Check whether the found predicate is the same as the desired predicate.
5815 if (FoundPred == Pred)
5816 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5817
5818 // Check whether swapping the found predicate makes it the same as the
5819 // desired predicate.
5820 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5821 if (isa<SCEVConstant>(RHS))
5822 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5823 else
5824 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5825 RHS, LHS, FoundLHS, FoundRHS);
5826 }
5827
5828 // Check whether the actual condition is beyond sufficient.
5829 if (FoundPred == ICmpInst::ICMP_EQ)
5830 if (ICmpInst::isTrueWhenEqual(Pred))
5831 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5832 return true;
5833 if (Pred == ICmpInst::ICMP_NE)
5834 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5835 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5836 return true;
5837
5838 // Otherwise assume the worst.
5839 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005840}
5841
Dan Gohman0f4b2852009-07-21 23:03:19 +00005842/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005843/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005844/// and FoundRHS is true.
5845bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5846 const SCEV *LHS, const SCEV *RHS,
5847 const SCEV *FoundLHS,
5848 const SCEV *FoundRHS) {
5849 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5850 FoundLHS, FoundRHS) ||
5851 // ~x < ~y --> x > y
5852 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5853 getNotSCEV(FoundRHS),
5854 getNotSCEV(FoundLHS));
5855}
5856
5857/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005858/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005859/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005860bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005861ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5862 const SCEV *LHS, const SCEV *RHS,
5863 const SCEV *FoundLHS,
5864 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005865 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005866 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5867 case ICmpInst::ICMP_EQ:
5868 case ICmpInst::ICMP_NE:
5869 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5870 return true;
5871 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005872 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005873 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005874 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5875 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005876 return true;
5877 break;
5878 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005879 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005880 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5881 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005882 return true;
5883 break;
5884 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005885 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005886 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5887 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005888 return true;
5889 break;
5890 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005891 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005892 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5893 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005894 return true;
5895 break;
5896 }
5897
5898 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005899}
5900
Dan Gohman51f53b72009-06-21 23:46:38 +00005901/// getBECount - Subtract the end and start values and divide by the step,
5902/// rounding up, to get the number of times the backedge is executed. Return
5903/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005904const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005905 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005906 const SCEV *Step,
5907 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005908 assert(!isKnownNegative(Step) &&
5909 "This code doesn't handle negative strides yet!");
5910
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005911 Type *Ty = Start->getType();
Andrew Tricke62289b2011-03-09 17:29:58 +00005912
5913 // When Start == End, we have an exact BECount == 0. Short-circuit this case
5914 // here because SCEV may not be able to determine that the unsigned division
5915 // after rounding is zero.
5916 if (Start == End)
5917 return getConstant(Ty, 0);
5918
Dan Gohmandeff6212010-05-03 22:09:21 +00005919 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005920 const SCEV *Diff = getMinusSCEV(End, Start);
5921 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005922
5923 // Add an adjustment to the difference between End and Start so that
5924 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005925 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005926
Dan Gohman1f96e672009-09-17 18:05:20 +00005927 if (!NoWrap) {
5928 // Check Add for unsigned overflow.
5929 // TODO: More sophisticated things could be done here.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005930 Type *WideTy = IntegerType::get(getContext(),
Dan Gohman1f96e672009-09-17 18:05:20 +00005931 getTypeSizeInBits(Ty) + 1);
5932 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5933 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5934 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5935 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5936 return getCouldNotCompute();
5937 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005938
5939 return getUDivExpr(Add, Step);
5940}
5941
Chris Lattnerdb25de42005-08-15 23:33:51 +00005942/// HowManyLessThans - Return the number of times a backedge containing the
5943/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005944/// CouldNotCompute.
Andrew Trick5116ff62011-07-26 17:19:55 +00005945ScalarEvolution::ExitLimit
Dan Gohman64a845e2009-06-24 04:48:43 +00005946ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5947 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005948 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005949 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005950
Dan Gohman35738ac2009-05-04 22:30:44 +00005951 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005952 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005953 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005954
Dan Gohman1f96e672009-09-17 18:05:20 +00005955 // Check to see if we have a flag which makes analysis easy.
Andrew Trick3228cc22011-03-14 16:50:06 +00005956 bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5957 AddRec->getNoWrapFlags(SCEV::FlagNUW);
Dan Gohman1f96e672009-09-17 18:05:20 +00005958
Chris Lattnerdb25de42005-08-15 23:33:51 +00005959 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005960 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005961 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005962
Dan Gohman52fddd32010-01-26 04:40:18 +00005963 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005964 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005965 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005966 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005967 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005968 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005969 // value and past the maximum value for its type in a single step.
5970 // Note that it's not sufficient to check NoWrap here, because even
5971 // though the value after a wrap is undefined, it's not undefined
5972 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005973 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005974 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005975 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005976 if (isSigned) {
5977 APInt Max = APInt::getSignedMaxValue(BitWidth);
5978 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5979 .slt(getSignedRange(RHS).getSignedMax()))
5980 return getCouldNotCompute();
5981 } else {
5982 APInt Max = APInt::getMaxValue(BitWidth);
5983 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5984 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5985 return getCouldNotCompute();
5986 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005987 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005988 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005989 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005990
Dan Gohmana1af7572009-04-30 20:47:05 +00005991 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5992 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5993 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005994 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005995
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005996 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005997 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005998
Dan Gohmana1af7572009-04-30 20:47:05 +00005999 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00006000 const SCEV *MinStart = getConstant(isSigned ?
6001 getSignedRange(Start).getSignedMin() :
6002 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00006003
Dan Gohmana1af7572009-04-30 20:47:05 +00006004 // If we know that the condition is true in order to enter the loop,
6005 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00006006 // only know that it will execute (max(m,n)-n)/s times. In both cases,
6007 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006008 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00006009 if (!isLoopEntryGuardedByCond(L,
6010 isSigned ? ICmpInst::ICMP_SLT :
6011 ICmpInst::ICMP_ULT,
6012 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00006013 End = isSigned ? getSMaxExpr(RHS, Start)
6014 : getUMaxExpr(RHS, Start);
6015
6016 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00006017 const SCEV *MaxEnd = getConstant(isSigned ?
6018 getSignedRange(End).getSignedMax() :
6019 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00006020
Dan Gohman52fddd32010-01-26 04:40:18 +00006021 // If MaxEnd is within a step of the maximum integer value in its type,
6022 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006023 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00006024 // compute the correct value.
6025 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00006026 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00006027 MaxEnd = isSigned ?
6028 getSMinExpr(MaxEnd,
6029 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
6030 StepMinusOne)) :
6031 getUMinExpr(MaxEnd,
6032 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
6033 StepMinusOne));
6034
Dan Gohmana1af7572009-04-30 20:47:05 +00006035 // Finally, we subtract these two values and divide, rounding up, to get
6036 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00006037 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00006038
6039 // The maximum backedge count is similar, except using the minimum start
6040 // value and the maximum end value.
Andrew Tricke62289b2011-03-09 17:29:58 +00006041 // If we already have an exact constant BECount, use it instead.
6042 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
6043 : getBECount(MinStart, MaxEnd, Step, NoWrap);
6044
6045 // If the stride is nonconstant, and NoWrap == true, then
6046 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
6047 // exact BECount and invalid MaxBECount, which should be avoided to catch
6048 // more optimization opportunities.
6049 if (isa<SCEVCouldNotCompute>(MaxBECount))
6050 MaxBECount = BECount;
Dan Gohmana1af7572009-04-30 20:47:05 +00006051
Andrew Trick5116ff62011-07-26 17:19:55 +00006052 return ExitLimit(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00006053 }
6054
Dan Gohman1c343752009-06-27 21:21:31 +00006055 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00006056}
6057
Chris Lattner53e677a2004-04-02 20:23:17 +00006058/// getNumIterationsInRange - Return the number of iterations of this loop that
6059/// produce values in the specified constant range. Another way of looking at
6060/// this is that it returns the first iteration number where the value is not in
6061/// the condition, thus computing the exit count. If the iteration count can't
6062/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006063const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00006064 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00006065 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006066 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006067
6068 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00006069 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00006070 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00006071 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00006072 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00006073 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00006074 getNoWrapFlags(FlagNW));
Dan Gohman622ed672009-05-04 22:02:23 +00006075 if (const SCEVAddRecExpr *ShiftedAddRec =
6076 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00006077 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00006078 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00006079 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006080 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006081 }
6082
6083 // The only time we can solve this is when we have all constant indices.
6084 // Otherwise, we cannot determine the overflow conditions.
6085 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6086 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006087 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006088
6089
6090 // Okay at this point we know that all elements of the chrec are constants and
6091 // that the start element is zero.
6092
6093 // First check to see if the range contains zero. If not, the first
6094 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00006095 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00006096 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00006097 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006098
Chris Lattner53e677a2004-04-02 20:23:17 +00006099 if (isAffine()) {
6100 // If this is an affine expression then we have this situation:
6101 // Solve {0,+,A} in Range === Ax in Range
6102
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00006103 // We know that zero is in the range. If A is positive then we know that
6104 // the upper value of the range must be the first possible exit value.
6105 // If A is negative then the lower of the range is the last possible loop
6106 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00006107 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00006108 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
6109 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00006110
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00006111 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00006112 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00006113 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00006114
6115 // Evaluate at the exit value. If we really did fall out of the valid
6116 // range, then we computed our trip count, otherwise wrap around or other
6117 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00006118 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006119 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006120 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00006121
6122 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00006123 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00006124 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00006125 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00006126 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00006127 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00006128 } else if (isQuadratic()) {
6129 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
6130 // quadratic equation to solve it. To do this, we must frame our problem in
6131 // terms of figuring out when zero is crossed, instead of when
6132 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006133 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00006134 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick3228cc22011-03-14 16:50:06 +00006135 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
6136 // getNoWrapFlags(FlagNW)
6137 FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00006138
6139 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00006140 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00006141 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00006142 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6143 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00006144 if (R1) {
6145 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006146 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006147 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00006148 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00006149 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00006150 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006151
Chris Lattner53e677a2004-04-02 20:23:17 +00006152 // Make sure the root is not off by one. The returned iteration should
6153 // not be in the range, but the previous one should be. When solving
6154 // for "X*X < 5", for example, we should not return a root of 2.
6155 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00006156 R1->getValue(),
6157 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006158 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006159 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00006160 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00006161 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006162
Dan Gohman246b2562007-10-22 18:31:58 +00006163 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006164 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00006165 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006166 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00006167 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006168
Chris Lattner53e677a2004-04-02 20:23:17 +00006169 // If R1 was not in the range, then it is a good return value. Make
6170 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00006171 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00006172 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00006173 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006174 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00006175 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006176 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00006177 }
6178 }
6179 }
6180
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006181 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006182}
6183
6184
6185
6186//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00006187// SCEVCallbackVH Class Implementation
6188//===----------------------------------------------------------------------===//
6189
Dan Gohman1959b752009-05-19 19:22:47 +00006190void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006191 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00006192 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6193 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006194 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00006195 // this now dangles!
6196}
6197
Dan Gohman81f91212010-07-28 01:09:07 +00006198void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006199 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00006200
Dan Gohman35738ac2009-05-04 22:30:44 +00006201 // Forget all the expressions associated with users of the old value,
6202 // so that future queries will recompute the expressions using the new
6203 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00006204 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00006205 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00006206 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00006207 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6208 UI != UE; ++UI)
6209 Worklist.push_back(*UI);
6210 while (!Worklist.empty()) {
6211 User *U = Worklist.pop_back_val();
6212 // Deleting the Old value will cause this to dangle. Postpone
6213 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00006214 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00006215 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00006216 if (!Visited.insert(U))
6217 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00006218 if (PHINode *PN = dyn_cast<PHINode>(U))
6219 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006220 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00006221 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6222 UI != UE; ++UI)
6223 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00006224 }
Dan Gohman59846ac2010-07-28 00:28:25 +00006225 // Delete the Old value.
6226 if (PHINode *PN = dyn_cast<PHINode>(Old))
6227 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006228 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00006229 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00006230}
6231
Dan Gohman1959b752009-05-19 19:22:47 +00006232ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00006233 : CallbackVH(V), SE(se) {}
6234
6235//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00006236// ScalarEvolution Class Implementation
6237//===----------------------------------------------------------------------===//
6238
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006239ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00006240 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00006241 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006242}
6243
Chris Lattner53e677a2004-04-02 20:23:17 +00006244bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006245 this->F = &F;
6246 LI = &getAnalysis<LoopInfo>();
6247 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00006248 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00006249 return false;
6250}
6251
6252void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00006253 // Iterate through all the SCEVUnknown instances and call their
6254 // destructors, so that they release their references to their values.
6255 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6256 U->~SCEVUnknown();
6257 FirstUnknown = 0;
6258
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006259 ValueExprMap.clear();
Andrew Trick5116ff62011-07-26 17:19:55 +00006260
6261 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
6262 // that a loop had multiple computable exits.
6263 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
6264 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
6265 I != E; ++I) {
6266 I->second.clear();
6267 }
6268
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006269 BackedgeTakenCounts.clear();
6270 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00006271 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00006272 LoopDispositions.clear();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006273 BlockDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00006274 UnsignedRanges.clear();
6275 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00006276 UniqueSCEVs.clear();
6277 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00006278}
6279
6280void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6281 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00006282 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00006283 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00006284}
6285
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006286bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006287 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00006288}
6289
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006290static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00006291 const Loop *L) {
6292 // Print all inner loops first
6293 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6294 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006295
Dan Gohman30733292010-01-09 18:17:45 +00006296 OS << "Loop ";
6297 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6298 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006299
Dan Gohman5d984912009-12-18 01:14:11 +00006300 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006301 L->getExitBlocks(ExitBlocks);
6302 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00006303 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006304
Dan Gohman46bdfb02009-02-24 18:55:53 +00006305 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6306 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00006307 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006308 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006309 }
6310
Dan Gohman30733292010-01-09 18:17:45 +00006311 OS << "\n"
6312 "Loop ";
6313 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6314 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00006315
6316 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6317 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6318 } else {
6319 OS << "Unpredictable max backedge-taken count. ";
6320 }
6321
6322 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006323}
6324
Dan Gohman5d984912009-12-18 01:14:11 +00006325void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006326 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006327 // out SCEV values of all instructions that are interesting. Doing
6328 // this potentially causes it to create new SCEV objects though,
6329 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00006330 // observable from outside the class though, so casting away the
6331 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00006332 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00006333
Dan Gohman30733292010-01-09 18:17:45 +00006334 OS << "Classifying expressions for: ";
6335 WriteAsOperand(OS, F, /*PrintType=*/false);
6336 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006337 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00006338 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00006339 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00006340 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006341 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006342 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006343
Dan Gohman0c689c52009-06-19 17:49:54 +00006344 const Loop *L = LI->getLoopFor((*I).getParent());
6345
Dan Gohman0bba49c2009-07-07 17:06:11 +00006346 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00006347 if (AtUse != SV) {
6348 OS << " --> ";
6349 AtUse->print(OS);
6350 }
6351
6352 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00006353 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006354 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00006355 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006356 OS << "<<Unknown>>";
6357 } else {
6358 OS << *ExitValue;
6359 }
6360 }
6361
Chris Lattner53e677a2004-04-02 20:23:17 +00006362 OS << "\n";
6363 }
6364
Dan Gohman30733292010-01-09 18:17:45 +00006365 OS << "Determining loop execution counts for: ";
6366 WriteAsOperand(OS, F, /*PrintType=*/false);
6367 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006368 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6369 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006370}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00006371
Dan Gohman714b5292010-11-17 23:21:44 +00006372ScalarEvolution::LoopDisposition
6373ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6374 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6375 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6376 Values.insert(std::make_pair(L, LoopVariant));
6377 if (!Pair.second)
6378 return Pair.first->second;
6379
6380 LoopDisposition D = computeLoopDisposition(S, L);
6381 return LoopDispositions[S][L] = D;
6382}
6383
6384ScalarEvolution::LoopDisposition
6385ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00006386 switch (S->getSCEVType()) {
6387 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00006388 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006389 case scTruncate:
6390 case scZeroExtend:
6391 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00006392 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006393 case scAddRecExpr: {
6394 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6395
Dan Gohman714b5292010-11-17 23:21:44 +00006396 // If L is the addrec's loop, it's computable.
6397 if (AR->getLoop() == L)
6398 return LoopComputable;
6399
Dan Gohman17ead4f2010-11-17 21:23:15 +00006400 // Add recurrences are never invariant in the function-body (null loop).
6401 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00006402 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006403
6404 // This recurrence is variant w.r.t. L if L contains AR's loop.
6405 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00006406 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006407
6408 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6409 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00006410 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006411
6412 // This recurrence is variant w.r.t. L if any of its operands
6413 // are variant.
6414 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6415 I != E; ++I)
6416 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00006417 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006418
6419 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00006420 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006421 }
6422 case scAddExpr:
6423 case scMulExpr:
6424 case scUMaxExpr:
6425 case scSMaxExpr: {
6426 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006427 bool HasVarying = false;
6428 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6429 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00006430 LoopDisposition D = getLoopDisposition(*I, L);
6431 if (D == LoopVariant)
6432 return LoopVariant;
6433 if (D == LoopComputable)
6434 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006435 }
Dan Gohman714b5292010-11-17 23:21:44 +00006436 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006437 }
6438 case scUDivExpr: {
6439 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00006440 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6441 if (LD == LoopVariant)
6442 return LoopVariant;
6443 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6444 if (RD == LoopVariant)
6445 return LoopVariant;
6446 return (LD == LoopInvariant && RD == LoopInvariant) ?
6447 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006448 }
6449 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00006450 // All non-instruction values are loop invariant. All instructions are loop
6451 // invariant if they are not contained in the specified loop.
6452 // Instructions are never considered invariant in the function body
6453 // (null loop) because they are defined within the "loop".
6454 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6455 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6456 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006457 case scCouldNotCompute:
6458 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00006459 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006460 default: break;
6461 }
6462 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00006463 return LoopVariant;
6464}
6465
6466bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6467 return getLoopDisposition(S, L) == LoopInvariant;
6468}
6469
6470bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6471 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006472}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006473
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006474ScalarEvolution::BlockDisposition
6475ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6476 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6477 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6478 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6479 if (!Pair.second)
6480 return Pair.first->second;
6481
6482 BlockDisposition D = computeBlockDisposition(S, BB);
6483 return BlockDispositions[S][BB] = D;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006484}
6485
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006486ScalarEvolution::BlockDisposition
6487ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006488 switch (S->getSCEVType()) {
6489 case scConstant:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006490 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006491 case scTruncate:
6492 case scZeroExtend:
6493 case scSignExtend:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006494 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006495 case scAddRecExpr: {
6496 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006497 // to test for proper dominance too, because the instruction which
6498 // produces the addrec's value is a PHI, and a PHI effectively properly
6499 // dominates its entire containing block.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006500 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6501 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006502 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006503 }
6504 // FALL THROUGH into SCEVNAryExpr handling.
6505 case scAddExpr:
6506 case scMulExpr:
6507 case scUMaxExpr:
6508 case scSMaxExpr: {
6509 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006510 bool Proper = true;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006511 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006512 I != E; ++I) {
6513 BlockDisposition D = getBlockDisposition(*I, BB);
6514 if (D == DoesNotDominateBlock)
6515 return DoesNotDominateBlock;
6516 if (D == DominatesBlock)
6517 Proper = false;
6518 }
6519 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006520 }
6521 case scUDivExpr: {
6522 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006523 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6524 BlockDisposition LD = getBlockDisposition(LHS, BB);
6525 if (LD == DoesNotDominateBlock)
6526 return DoesNotDominateBlock;
6527 BlockDisposition RD = getBlockDisposition(RHS, BB);
6528 if (RD == DoesNotDominateBlock)
6529 return DoesNotDominateBlock;
6530 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6531 ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006532 }
6533 case scUnknown:
6534 if (Instruction *I =
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006535 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6536 if (I->getParent() == BB)
6537 return DominatesBlock;
6538 if (DT->properlyDominates(I->getParent(), BB))
6539 return ProperlyDominatesBlock;
6540 return DoesNotDominateBlock;
6541 }
6542 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006543 case scCouldNotCompute:
6544 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006545 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006546 default: break;
6547 }
6548 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006549 return DoesNotDominateBlock;
6550}
6551
6552bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6553 return getBlockDisposition(S, BB) >= DominatesBlock;
6554}
6555
6556bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6557 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006558}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006559
6560bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6561 switch (S->getSCEVType()) {
6562 case scConstant:
6563 return false;
6564 case scTruncate:
6565 case scZeroExtend:
6566 case scSignExtend: {
6567 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6568 const SCEV *CastOp = Cast->getOperand();
6569 return Op == CastOp || hasOperand(CastOp, Op);
6570 }
6571 case scAddRecExpr:
6572 case scAddExpr:
6573 case scMulExpr:
6574 case scUMaxExpr:
6575 case scSMaxExpr: {
6576 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6577 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6578 I != E; ++I) {
6579 const SCEV *NAryOp = *I;
6580 if (NAryOp == Op || hasOperand(NAryOp, Op))
6581 return true;
6582 }
6583 return false;
6584 }
6585 case scUDivExpr: {
6586 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6587 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6588 return LHS == Op || hasOperand(LHS, Op) ||
6589 RHS == Op || hasOperand(RHS, Op);
6590 }
6591 case scUnknown:
6592 return false;
6593 case scCouldNotCompute:
6594 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6595 return false;
6596 default: break;
6597 }
6598 llvm_unreachable("Unknown SCEV kind!");
6599 return false;
6600}
Dan Gohman56a75682010-11-17 23:28:48 +00006601
6602void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6603 ValuesAtScopes.erase(S);
6604 LoopDispositions.erase(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006605 BlockDispositions.erase(S);
Dan Gohman56a75682010-11-17 23:28:48 +00006606 UnsignedRanges.erase(S);
6607 SignedRanges.erase(S);
6608}