blob: b015481b76cc38786fd343b878b8fcf0ffef176a [file] [log] [blame]
Nick Lewycky97756402014-09-01 05:17:15 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-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 Gohmanef2ae2c2009-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 Lattnerd934c702004-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 Brukman01808ca2005-04-21 21:13:18 +000030//
Chris Lattnerd934c702004-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 Lattnerd934c702004-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Analysis/ScalarEvolution.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000062#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
Hal Finkel60db0582014-09-07 18:57:58 +000066#include "llvm/Analysis/AssumptionTracker.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000068#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000072#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000073#include "llvm/IR/Constants.h"
74#include "llvm/IR/DataLayout.h"
75#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000076#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000077#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000078#include "llvm/IR/GlobalAlias.h"
79#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000080#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000081#include "llvm/IR/Instructions.h"
82#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000083#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000084#include "llvm/IR/Operator.h"
Chris Lattner996795b2006-06-28 23:17:24 +000085#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000086#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000087#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000088#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000089#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000090#include "llvm/Target/TargetLibraryInfo.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000091#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000092using namespace llvm;
93
Chandler Carruthf1221bd2014-04-22 02:48:03 +000094#define DEBUG_TYPE "scalar-evolution"
95
Chris Lattner57ef9422006-12-19 22:30:33 +000096STATISTIC(NumArrayLenItCounts,
97 "Number of trip counts computed with array length");
98STATISTIC(NumTripCountsComputed,
99 "Number of loops with predictable loop counts");
100STATISTIC(NumTripCountsNotComputed,
101 "Number of loops without predictable loop counts");
102STATISTIC(NumBruteForceTripCountsComputed,
103 "Number of loops with trip counts computed by force");
104
Dan Gohmand78c4002008-05-13 00:00:25 +0000105static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000106MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000108 "symbolically execute a constant "
109 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000110 cl::init(100));
111
Benjamin Kramer214935e2012-10-26 17:31:32 +0000112// FIXME: Enable this with XDEBUG when the test suite is clean.
113static cl::opt<bool>
114VerifySCEV("verify-scev",
115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
116
Owen Anderson8ac477f2010-10-12 19:48:12 +0000117INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
118 "Scalar Evolution Analysis", false, true)
Hal Finkel60db0582014-09-07 18:57:58 +0000119INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000120INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chandler Carruth73523022014-01-13 13:07:17 +0000121INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chad Rosierc24b86f2011-12-01 03:08:23 +0000122INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000123INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000124 "Scalar Evolution Analysis", false, true)
Devang Patel8c78a0b2007-05-03 01:11:54 +0000125char ScalarEvolution::ID = 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000126
127//===----------------------------------------------------------------------===//
128// SCEV class definitions
129//===----------------------------------------------------------------------===//
130
131//===----------------------------------------------------------------------===//
132// Implementation of the SCEV class.
133//
Dan Gohman3423e722009-06-30 20:13:32 +0000134
Manman Ren49d684e2012-09-12 05:06:18 +0000135#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chris Lattnerd934c702004-04-02 20:23:17 +0000136void SCEV::dump() const {
David Greenedf1c4972009-12-23 22:18:14 +0000137 print(dbgs());
138 dbgs() << '\n';
Dan Gohmane20f8242009-04-21 00:47:46 +0000139}
Manman Renc3366cc2012-09-06 19:55:56 +0000140#endif
Dan Gohmane20f8242009-04-21 00:47:46 +0000141
Dan Gohman534749b2010-11-17 22:27:42 +0000142void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000143 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000144 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000145 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000146 return;
147 case scTruncate: {
148 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
149 const SCEV *Op = Trunc->getOperand();
150 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
151 << *Trunc->getType() << ")";
152 return;
153 }
154 case scZeroExtend: {
155 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
156 const SCEV *Op = ZExt->getOperand();
157 OS << "(zext " << *Op->getType() << " " << *Op << " to "
158 << *ZExt->getType() << ")";
159 return;
160 }
161 case scSignExtend: {
162 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
163 const SCEV *Op = SExt->getOperand();
164 OS << "(sext " << *Op->getType() << " " << *Op << " to "
165 << *SExt->getType() << ")";
166 return;
167 }
168 case scAddRecExpr: {
169 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
170 OS << "{" << *AR->getOperand(0);
171 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
172 OS << ",+," << *AR->getOperand(i);
173 OS << "}<";
Andrew Trick8b55b732011-03-14 16:50:06 +0000174 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000175 OS << "nuw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000176 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000177 OS << "nsw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000178 if (AR->getNoWrapFlags(FlagNW) &&
179 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
180 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000181 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000182 OS << ">";
183 return;
184 }
185 case scAddExpr:
186 case scMulExpr:
187 case scUMaxExpr:
188 case scSMaxExpr: {
189 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000190 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000191 switch (NAry->getSCEVType()) {
192 case scAddExpr: OpStr = " + "; break;
193 case scMulExpr: OpStr = " * "; break;
194 case scUMaxExpr: OpStr = " umax "; break;
195 case scSMaxExpr: OpStr = " smax "; break;
196 }
197 OS << "(";
198 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
199 I != E; ++I) {
200 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000201 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000202 OS << OpStr;
203 }
204 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000205 switch (NAry->getSCEVType()) {
206 case scAddExpr:
207 case scMulExpr:
208 if (NAry->getNoWrapFlags(FlagNUW))
209 OS << "<nuw>";
210 if (NAry->getNoWrapFlags(FlagNSW))
211 OS << "<nsw>";
212 }
Dan Gohman534749b2010-11-17 22:27:42 +0000213 return;
214 }
215 case scUDivExpr: {
216 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
217 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
218 return;
219 }
220 case scUnknown: {
221 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000222 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000223 if (U->isSizeOf(AllocTy)) {
224 OS << "sizeof(" << *AllocTy << ")";
225 return;
226 }
227 if (U->isAlignOf(AllocTy)) {
228 OS << "alignof(" << *AllocTy << ")";
229 return;
230 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000231
Chris Lattner229907c2011-07-18 04:54:35 +0000232 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000233 Constant *FieldNo;
234 if (U->isOffsetOf(CTy, FieldNo)) {
235 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000236 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000237 OS << ")";
238 return;
239 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000240
Dan Gohman534749b2010-11-17 22:27:42 +0000241 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000242 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000243 return;
244 }
245 case scCouldNotCompute:
246 OS << "***COULDNOTCOMPUTE***";
247 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000248 }
249 llvm_unreachable("Unknown SCEV kind!");
250}
251
Chris Lattner229907c2011-07-18 04:54:35 +0000252Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000253 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000254 case scConstant:
255 return cast<SCEVConstant>(this)->getType();
256 case scTruncate:
257 case scZeroExtend:
258 case scSignExtend:
259 return cast<SCEVCastExpr>(this)->getType();
260 case scAddRecExpr:
261 case scMulExpr:
262 case scUMaxExpr:
263 case scSMaxExpr:
264 return cast<SCEVNAryExpr>(this)->getType();
265 case scAddExpr:
266 return cast<SCEVAddExpr>(this)->getType();
267 case scUDivExpr:
268 return cast<SCEVUDivExpr>(this)->getType();
269 case scUnknown:
270 return cast<SCEVUnknown>(this)->getType();
271 case scCouldNotCompute:
272 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000273 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000274 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000275}
276
Dan Gohmanbe928e32008-06-18 16:23:07 +0000277bool SCEV::isZero() const {
278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
279 return SC->getValue()->isZero();
280 return false;
281}
282
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000283bool SCEV::isOne() const {
284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
285 return SC->getValue()->isOne();
286 return false;
287}
Chris Lattnerd934c702004-04-02 20:23:17 +0000288
Dan Gohman18a96bb2009-06-24 00:30:26 +0000289bool SCEV::isAllOnesValue() const {
290 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
291 return SC->getValue()->isAllOnesValue();
292 return false;
293}
294
Andrew Trick881a7762012-01-07 00:27:31 +0000295/// isNonConstantNegative - Return true if the specified scev is negated, but
296/// not a constant.
297bool SCEV::isNonConstantNegative() const {
298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
299 if (!Mul) return false;
300
301 // If there is a constant factor, it will be first.
302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
303 if (!SC) return false;
304
305 // Return true if the value is negative, this matches things like (-42 * V).
306 return SC->getValue()->getValue().isNegative();
307}
308
Owen Anderson04052ec2009-06-22 21:57:23 +0000309SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000311
Chris Lattnerd934c702004-04-02 20:23:17 +0000312bool SCEVCouldNotCompute::classof(const SCEV *S) {
313 return S->getSCEVType() == scCouldNotCompute;
314}
315
Dan Gohmanaf752342009-07-07 17:06:11 +0000316const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000317 FoldingSetNodeID ID;
318 ID.AddInteger(scConstant);
319 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000320 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000323 UniqueSCEVs.InsertNode(S, IP);
324 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000325}
Chris Lattnerd934c702004-04-02 20:23:17 +0000326
Nick Lewycky31eaca52014-01-27 10:04:03 +0000327const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000328 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000329}
330
Dan Gohmanaf752342009-07-07 17:06:11 +0000331const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000332ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000334 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000335}
336
Dan Gohman24ceda82010-06-18 19:54:20 +0000337SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000338 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000340
Dan Gohman24ceda82010-06-18 19:54:20 +0000341SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000342 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000343 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000346 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000347}
Chris Lattnerd934c702004-04-02 20:23:17 +0000348
Dan Gohman24ceda82010-06-18 19:54:20 +0000349SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000350 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000351 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
353 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000354 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000355}
356
Dan Gohman24ceda82010-06-18 19:54:20 +0000357SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000358 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000359 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
361 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000362 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000363}
364
Dan Gohman7cac9572010-08-02 23:49:30 +0000365void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000366 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000367 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000368
369 // Remove this SCEVUnknown from the uniquing map.
370 SE->UniqueSCEVs.RemoveNode(this);
371
372 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000373 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374}
375
376void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000377 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000378 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000379
380 // Remove this SCEVUnknown from the uniquing map.
381 SE->UniqueSCEVs.RemoveNode(this);
382
383 // Update this SCEVUnknown to point to the new value. This is needed
384 // because there may still be outstanding SCEVs which still point to
385 // this SCEVUnknown.
386 setValPtr(New);
387}
388
Chris Lattner229907c2011-07-18 04:54:35 +0000389bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000393 if (CE->getOpcode() == Instruction::GetElementPtr &&
394 CE->getOperand(0)->isNullValue() &&
395 CE->getNumOperands() == 2)
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
397 if (CI->isOne()) {
398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
399 ->getElementType();
400 return true;
401 }
Dan Gohmancf913832010-01-28 02:15:55 +0000402
403 return false;
404}
405
Chris Lattner229907c2011-07-18 04:54:35 +0000406bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000408 if (VCE->getOpcode() == Instruction::PtrToInt)
409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (CE->getOpcode() == Instruction::GetElementPtr &&
411 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000412 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000414 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000415 if (!STy->isPacked() &&
416 CE->getNumOperands() == 3 &&
417 CE->getOperand(1)->isNullValue()) {
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
419 if (CI->isOne() &&
420 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000421 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000422 AllocTy = STy->getElementType(1);
423 return true;
424 }
425 }
426 }
Dan Gohmancf913832010-01-28 02:15:55 +0000427
428 return false;
429}
430
Chris Lattner229907c2011-07-18 04:54:35 +0000431bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getNumOperands() == 3 &&
437 CE->getOperand(0)->isNullValue() &&
438 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000439 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
441 // Ignore vector types here so that ScalarEvolutionExpander doesn't
442 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000443 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000444 CTy = Ty;
445 FieldNo = CE->getOperand(2);
446 return true;
447 }
448 }
449
450 return false;
451}
452
Chris Lattnereb3e8402004-06-20 06:23:15 +0000453//===----------------------------------------------------------------------===//
454// SCEV Utilities
455//===----------------------------------------------------------------------===//
456
457namespace {
458 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
459 /// than the complexity of the RHS. This comparator is used to canonicalize
460 /// expressions.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000461 class SCEVComplexityCompare {
Dan Gohman3324b9e2010-08-13 20:17:27 +0000462 const LoopInfo *const LI;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000463 public:
Dan Gohman992db002010-07-23 21:18:55 +0000464 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000465
Dan Gohman27065672010-08-27 15:26:01 +0000466 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohman5e6ce7b2008-04-14 18:23:56 +0000467 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman27065672010-08-27 15:26:01 +0000468 return compare(LHS, RHS) < 0;
469 }
470
471 // Return negative, zero, or positive, if LHS is less than, equal to, or
472 // greater than RHS, respectively. A three-way result allows recursive
473 // comparisons to be more efficient.
474 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000475 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
476 if (LHS == RHS)
Dan Gohman27065672010-08-27 15:26:01 +0000477 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000478
Dan Gohman9ba542c2009-05-07 14:39:04 +0000479 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman5ae31022010-07-23 21:20:52 +0000480 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
481 if (LType != RType)
Dan Gohman27065672010-08-27 15:26:01 +0000482 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000483
Dan Gohman24ceda82010-06-18 19:54:20 +0000484 // Aside from the getSCEVType() ordering, the particular ordering
485 // isn't very important except that it's beneficial to be consistent,
486 // so that (a + b) and (b + a) don't end up as different expressions.
Benjamin Kramer987b8502014-02-11 19:02:55 +0000487 switch (static_cast<SCEVTypes>(LType)) {
Dan Gohman27065672010-08-27 15:26:01 +0000488 case scUnknown: {
489 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000490 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000491
492 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
493 // not as complete as it could be.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000494 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000495
496 // Order pointer values after integer values. This helps SCEVExpander
497 // form GEPs.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000498 bool LIsPointer = LV->getType()->isPointerTy(),
499 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman5ae31022010-07-23 21:20:52 +0000500 if (LIsPointer != RIsPointer)
Dan Gohman27065672010-08-27 15:26:01 +0000501 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000502
503 // Compare getValueID values.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000504 unsigned LID = LV->getValueID(),
505 RID = RV->getValueID();
Dan Gohman5ae31022010-07-23 21:20:52 +0000506 if (LID != RID)
Dan Gohman27065672010-08-27 15:26:01 +0000507 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000508
509 // Sort arguments by their position.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000510 if (const Argument *LA = dyn_cast<Argument>(LV)) {
511 const Argument *RA = cast<Argument>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000514 }
515
Dan Gohman27065672010-08-27 15:26:01 +0000516 // For instructions, compare their loop depth, and their operand
517 // count. This is pretty loose.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000518 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
519 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman24ceda82010-06-18 19:54:20 +0000520
521 // Compare loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 const BasicBlock *LParent = LInst->getParent(),
523 *RParent = RInst->getParent();
524 if (LParent != RParent) {
525 unsigned LDepth = LI->getLoopDepth(LParent),
526 RDepth = LI->getLoopDepth(RParent);
527 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000528 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000529 }
Dan Gohman24ceda82010-06-18 19:54:20 +0000530
531 // Compare the number of operands.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000532 unsigned LNumOps = LInst->getNumOperands(),
533 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000534 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000535 }
536
Dan Gohman27065672010-08-27 15:26:01 +0000537 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000538 }
539
Dan Gohman27065672010-08-27 15:26:01 +0000540 case scConstant: {
541 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000542 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000543
544 // Compare constant values.
Dan Gohmanf2961822010-08-16 16:25:35 +0000545 const APInt &LA = LC->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman5ae31022010-07-23 21:20:52 +0000548 if (LBitWidth != RBitWidth)
Dan Gohman27065672010-08-27 15:26:01 +0000549 return (int)LBitWidth - (int)RBitWidth;
550 return LA.ult(RA) ? -1 : 1;
Dan Gohman24ceda82010-06-18 19:54:20 +0000551 }
552
Dan Gohman27065672010-08-27 15:26:01 +0000553 case scAddRecExpr: {
554 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000555 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000556
557 // Compare addrec loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000558 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
559 if (LLoop != RLoop) {
560 unsigned LDepth = LLoop->getLoopDepth(),
561 RDepth = RLoop->getLoopDepth();
562 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000563 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000564 }
Dan Gohman27065672010-08-27 15:26:01 +0000565
566 // Addrec complexity grows with operand count.
567 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
568 if (LNumOps != RNumOps)
569 return (int)LNumOps - (int)RNumOps;
570
571 // Lexicographically compare.
572 for (unsigned i = 0; i != LNumOps; ++i) {
573 long X = compare(LA->getOperand(i), RA->getOperand(i));
574 if (X != 0)
575 return X;
576 }
577
578 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000579 }
580
Dan Gohman27065672010-08-27 15:26:01 +0000581 case scAddExpr:
582 case scMulExpr:
583 case scSMaxExpr:
584 case scUMaxExpr: {
585 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000586 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000587
588 // Lexicographically compare n-ary expressions.
Dan Gohman5ae31022010-07-23 21:20:52 +0000589 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
Andrew Trickc3bc8b82013-07-31 02:43:40 +0000590 if (LNumOps != RNumOps)
591 return (int)LNumOps - (int)RNumOps;
592
Dan Gohman5ae31022010-07-23 21:20:52 +0000593 for (unsigned i = 0; i != LNumOps; ++i) {
594 if (i >= RNumOps)
Dan Gohman27065672010-08-27 15:26:01 +0000595 return 1;
596 long X = compare(LC->getOperand(i), RC->getOperand(i));
597 if (X != 0)
598 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000599 }
Dan Gohman27065672010-08-27 15:26:01 +0000600 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000601 }
602
Dan Gohman27065672010-08-27 15:26:01 +0000603 case scUDivExpr: {
604 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000605 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000606
607 // Lexicographically compare udiv expressions.
608 long X = compare(LC->getLHS(), RC->getLHS());
609 if (X != 0)
610 return X;
611 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman24ceda82010-06-18 19:54:20 +0000612 }
613
Dan Gohman27065672010-08-27 15:26:01 +0000614 case scTruncate:
615 case scZeroExtend:
616 case scSignExtend: {
617 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000618 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000619
620 // Compare cast expressions by operand.
621 return compare(LC->getOperand(), RC->getOperand());
622 }
623
Benjamin Kramer987b8502014-02-11 19:02:55 +0000624 case scCouldNotCompute:
625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman24ceda82010-06-18 19:54:20 +0000626 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000627 llvm_unreachable("Unknown SCEV kind!");
Chris Lattnereb3e8402004-06-20 06:23:15 +0000628 }
629 };
630}
631
632/// GroupByComplexity - Given a list of SCEV objects, order them by their
633/// complexity, and group objects of the same complexity together by value.
634/// When this routine is finished, we know that any duplicates in the vector are
635/// consecutive and that complexity is monotonically increasing.
636///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000637/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000638/// results from this routine. In other words, we don't want the results of
639/// this to depend on where the addresses of various SCEV objects happened to
640/// land in memory.
641///
Dan Gohmanaf752342009-07-07 17:06:11 +0000642static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000643 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000644 if (Ops.size() < 2) return; // Noop
645 if (Ops.size() == 2) {
646 // This is the common case, which also happens to be trivially simple.
647 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000648 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
649 if (SCEVComplexityCompare(LI)(RHS, LHS))
650 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000651 return;
652 }
653
Dan Gohman24ceda82010-06-18 19:54:20 +0000654 // Do the rough sort by complexity.
655 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
656
657 // Now that we are sorted by complexity, group elements of the same
658 // complexity. Note that this is, at worst, N^2, but the vector is likely to
659 // be extremely short in practice. Note that we take this approach because we
660 // do not want to depend on the addresses of the objects we are grouping.
661 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
662 const SCEV *S = Ops[i];
663 unsigned Complexity = S->getSCEVType();
664
665 // If there are any objects of the same complexity and same value as this
666 // one, group them.
667 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
668 if (Ops[j] == S) { // Found a duplicate.
669 // Move it to immediately after i'th element.
670 std::swap(Ops[i+1], Ops[j]);
671 ++i; // no need to rescan it.
672 if (i == e-2) return; // Done!
673 }
674 }
675 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000676}
677
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000678static const APInt srem(const SCEVConstant *C1, const SCEVConstant *C2) {
679 APInt A = C1->getValue()->getValue();
680 APInt B = C2->getValue()->getValue();
681 uint32_t ABW = A.getBitWidth();
682 uint32_t BBW = B.getBitWidth();
683
684 if (ABW > BBW)
685 B = B.sext(ABW);
686 else if (ABW < BBW)
687 A = A.sext(BBW);
688
689 return APIntOps::srem(A, B);
690}
691
692static const APInt sdiv(const SCEVConstant *C1, const SCEVConstant *C2) {
693 APInt A = C1->getValue()->getValue();
694 APInt B = C2->getValue()->getValue();
695 uint32_t ABW = A.getBitWidth();
696 uint32_t BBW = B.getBitWidth();
697
698 if (ABW > BBW)
699 B = B.sext(ABW);
700 else if (ABW < BBW)
701 A = A.sext(BBW);
702
703 return APIntOps::sdiv(A, B);
704}
705
706namespace {
707struct FindSCEVSize {
708 int Size;
709 FindSCEVSize() : Size(0) {}
710
711 bool follow(const SCEV *S) {
712 ++Size;
713 // Keep looking at all operands of S.
714 return true;
715 }
716 bool isDone() const {
717 return false;
718 }
719};
720}
721
722// Returns the size of the SCEV S.
723static inline int sizeOfSCEV(const SCEV *S) {
724 FindSCEVSize F;
725 SCEVTraversal<FindSCEVSize> ST(F);
726 ST.visitAll(S);
727 return F.Size;
728}
729
730namespace {
731
732struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
733public:
734 // Computes the Quotient and Remainder of the division of Numerator by
735 // Denominator.
736 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
737 const SCEV *Denominator, const SCEV **Quotient,
738 const SCEV **Remainder) {
739 assert(Numerator && Denominator && "Uninitialized SCEV");
740
741 SCEVDivision D(SE, Numerator, Denominator);
742
743 // Check for the trivial case here to avoid having to check for it in the
744 // rest of the code.
745 if (Numerator == Denominator) {
746 *Quotient = D.One;
747 *Remainder = D.Zero;
748 return;
749 }
750
751 if (Numerator->isZero()) {
752 *Quotient = D.Zero;
753 *Remainder = D.Zero;
754 return;
755 }
756
757 // Split the Denominator when it is a product.
758 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
759 const SCEV *Q, *R;
760 *Quotient = Numerator;
761 for (const SCEV *Op : T->operands()) {
762 divide(SE, *Quotient, Op, &Q, &R);
763 *Quotient = Q;
764
765 // Bail out when the Numerator is not divisible by one of the terms of
766 // the Denominator.
767 if (!R->isZero()) {
768 *Quotient = D.Zero;
769 *Remainder = Numerator;
770 return;
771 }
772 }
773 *Remainder = D.Zero;
774 return;
775 }
776
777 D.visit(Numerator);
778 *Quotient = D.Quotient;
779 *Remainder = D.Remainder;
780 }
781
782 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, const SCEV *Denominator)
783 : SE(S), Denominator(Denominator) {
784 Zero = SE.getConstant(Denominator->getType(), 0);
785 One = SE.getConstant(Denominator->getType(), 1);
786
787 // By default, we don't know how to divide Expr by Denominator.
788 // Providing the default here simplifies the rest of the code.
789 Quotient = Zero;
790 Remainder = Numerator;
791 }
792
793 // Except in the trivial case described above, we do not know how to divide
794 // Expr by Denominator for the following functions with empty implementation.
795 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
796 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
797 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
798 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
799 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
800 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
801 void visitUnknown(const SCEVUnknown *Numerator) {}
802 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
803
804 void visitConstant(const SCEVConstant *Numerator) {
805 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
806 Quotient = SE.getConstant(sdiv(Numerator, D));
807 Remainder = SE.getConstant(srem(Numerator, D));
808 return;
809 }
810 }
811
812 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
813 const SCEV *StartQ, *StartR, *StepQ, *StepR;
814 assert(Numerator->isAffine() && "Numerator should be affine");
815 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
816 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
817 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
818 Numerator->getNoWrapFlags());
819 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
820 Numerator->getNoWrapFlags());
821 }
822
823 void visitAddExpr(const SCEVAddExpr *Numerator) {
824 SmallVector<const SCEV *, 2> Qs, Rs;
825 Type *Ty = Denominator->getType();
826
827 for (const SCEV *Op : Numerator->operands()) {
828 const SCEV *Q, *R;
829 divide(SE, Op, Denominator, &Q, &R);
830
831 // Bail out if types do not match.
832 if (Ty != Q->getType() || Ty != R->getType()) {
833 Quotient = Zero;
834 Remainder = Numerator;
835 return;
836 }
837
838 Qs.push_back(Q);
839 Rs.push_back(R);
840 }
841
842 if (Qs.size() == 1) {
843 Quotient = Qs[0];
844 Remainder = Rs[0];
845 return;
846 }
847
848 Quotient = SE.getAddExpr(Qs);
849 Remainder = SE.getAddExpr(Rs);
850 }
851
852 void visitMulExpr(const SCEVMulExpr *Numerator) {
853 SmallVector<const SCEV *, 2> Qs;
854 Type *Ty = Denominator->getType();
855
856 bool FoundDenominatorTerm = false;
857 for (const SCEV *Op : Numerator->operands()) {
858 // Bail out if types do not match.
859 if (Ty != Op->getType()) {
860 Quotient = Zero;
861 Remainder = Numerator;
862 return;
863 }
864
865 if (FoundDenominatorTerm) {
866 Qs.push_back(Op);
867 continue;
868 }
869
870 // Check whether Denominator divides one of the product operands.
871 const SCEV *Q, *R;
872 divide(SE, Op, Denominator, &Q, &R);
873 if (!R->isZero()) {
874 Qs.push_back(Op);
875 continue;
876 }
877
878 // Bail out if types do not match.
879 if (Ty != Q->getType()) {
880 Quotient = Zero;
881 Remainder = Numerator;
882 return;
883 }
884
885 FoundDenominatorTerm = true;
886 Qs.push_back(Q);
887 }
888
889 if (FoundDenominatorTerm) {
890 Remainder = Zero;
891 if (Qs.size() == 1)
892 Quotient = Qs[0];
893 else
894 Quotient = SE.getMulExpr(Qs);
895 return;
896 }
897
898 if (!isa<SCEVUnknown>(Denominator)) {
899 Quotient = Zero;
900 Remainder = Numerator;
901 return;
902 }
903
904 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
905 ValueToValueMap RewriteMap;
906 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
907 cast<SCEVConstant>(Zero)->getValue();
908 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
909
910 if (Remainder->isZero()) {
911 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
912 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
913 cast<SCEVConstant>(One)->getValue();
914 Quotient =
915 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
916 return;
917 }
918
919 // Quotient is (Numerator - Remainder) divided by Denominator.
920 const SCEV *Q, *R;
921 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
922 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
923 // This SCEV does not seem to simplify: fail the division here.
924 Quotient = Zero;
925 Remainder = Numerator;
926 return;
927 }
928 divide(SE, Diff, Denominator, &Q, &R);
929 assert(R == Zero &&
930 "(Numerator - Remainder) should evenly divide Denominator");
931 Quotient = Q;
932 }
933
934private:
935 ScalarEvolution &SE;
936 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
937};
938}
939
Chris Lattnerd934c702004-04-02 20:23:17 +0000940
Chris Lattnerd934c702004-04-02 20:23:17 +0000941
942//===----------------------------------------------------------------------===//
943// Simple SCEV method implementations
944//===----------------------------------------------------------------------===//
945
Eli Friedman61f67622008-08-04 23:49:06 +0000946/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000947/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000948static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000949 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000950 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000951 // Handle the simplest case efficiently.
952 if (K == 1)
953 return SE.getTruncateOrZeroExtend(It, ResultTy);
954
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000955 // We are using the following formula for BC(It, K):
956 //
957 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
958 //
Eli Friedman61f67622008-08-04 23:49:06 +0000959 // Suppose, W is the bitwidth of the return value. We must be prepared for
960 // overflow. Hence, we must assure that the result of our computation is
961 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
962 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000963 //
Eli Friedman61f67622008-08-04 23:49:06 +0000964 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000965 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000966 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
967 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000968 //
Eli Friedman61f67622008-08-04 23:49:06 +0000969 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000970 //
Eli Friedman61f67622008-08-04 23:49:06 +0000971 // This formula is trivially equivalent to the previous formula. However,
972 // this formula can be implemented much more efficiently. The trick is that
973 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
974 // arithmetic. To do exact division in modular arithmetic, all we have
975 // to do is multiply by the inverse. Therefore, this step can be done at
976 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000977 //
Eli Friedman61f67622008-08-04 23:49:06 +0000978 // The next issue is how to safely do the division by 2^T. The way this
979 // is done is by doing the multiplication step at a width of at least W + T
980 // bits. This way, the bottom W+T bits of the product are accurate. Then,
981 // when we perform the division by 2^T (which is equivalent to a right shift
982 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
983 // truncated out after the division by 2^T.
984 //
985 // In comparison to just directly using the first formula, this technique
986 // is much more efficient; using the first formula requires W * K bits,
987 // but this formula less than W + K bits. Also, the first formula requires
988 // a division step, whereas this formula only requires multiplies and shifts.
989 //
990 // It doesn't matter whether the subtraction step is done in the calculation
991 // width or the input iteration count's width; if the subtraction overflows,
992 // the result must be zero anyway. We prefer here to do it in the width of
993 // the induction variable because it helps a lot for certain cases; CodeGen
994 // isn't smart enough to ignore the overflow, which leads to much less
995 // efficient code if the width of the subtraction is wider than the native
996 // register width.
997 //
998 // (It's possible to not widen at all by pulling out factors of 2 before
999 // the multiplication; for example, K=2 can be calculated as
1000 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1001 // extra arithmetic, so it's not an obvious win, and it gets
1002 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001003
Eli Friedman61f67622008-08-04 23:49:06 +00001004 // Protection from insane SCEVs; this bound is conservative,
1005 // but it probably doesn't matter.
1006 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001007 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001008
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001009 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001010
Eli Friedman61f67622008-08-04 23:49:06 +00001011 // Calculate K! / 2^T and T; we divide out the factors of two before
1012 // multiplying for calculating K! / 2^T to avoid overflow.
1013 // Other overflow doesn't matter because we only care about the bottom
1014 // W bits of the result.
1015 APInt OddFactorial(W, 1);
1016 unsigned T = 1;
1017 for (unsigned i = 3; i <= K; ++i) {
1018 APInt Mult(W, i);
1019 unsigned TwoFactors = Mult.countTrailingZeros();
1020 T += TwoFactors;
1021 Mult = Mult.lshr(TwoFactors);
1022 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001023 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001024
Eli Friedman61f67622008-08-04 23:49:06 +00001025 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001026 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001027
Dan Gohman8b0a4192010-03-01 17:49:51 +00001028 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001029 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001030
1031 // Calculate the multiplicative inverse of K! / 2^T;
1032 // this multiplication factor will perform the exact division by
1033 // K! / 2^T.
1034 APInt Mod = APInt::getSignedMinValue(W+1);
1035 APInt MultiplyFactor = OddFactorial.zext(W+1);
1036 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1037 MultiplyFactor = MultiplyFactor.trunc(W);
1038
1039 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001040 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001041 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001042 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001043 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001044 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001045 Dividend = SE.getMulExpr(Dividend,
1046 SE.getTruncateOrZeroExtend(S, CalculationTy));
1047 }
1048
1049 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001050 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001051
1052 // Truncate the result, and divide by K! / 2^T.
1053
1054 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1055 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001056}
1057
Chris Lattnerd934c702004-04-02 20:23:17 +00001058/// evaluateAtIteration - Return the value of this chain of recurrences at
1059/// the specified iteration number. We can evaluate this recurrence by
1060/// multiplying each element in the chain by the binomial coefficient
1061/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1062///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001063/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001064///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001065/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001066///
Dan Gohmanaf752342009-07-07 17:06:11 +00001067const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001068 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001069 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001070 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001071 // The computation is correct in the face of overflow provided that the
1072 // multiplication is performed _after_ the evaluation of the binomial
1073 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001074 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001075 if (isa<SCEVCouldNotCompute>(Coeff))
1076 return Coeff;
1077
1078 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001079 }
1080 return Result;
1081}
1082
Chris Lattnerd934c702004-04-02 20:23:17 +00001083//===----------------------------------------------------------------------===//
1084// SCEV Expression folder implementations
1085//===----------------------------------------------------------------------===//
1086
Dan Gohmanaf752342009-07-07 17:06:11 +00001087const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001088 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001089 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001090 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001091 assert(isSCEVable(Ty) &&
1092 "This is not a conversion to a SCEVable type!");
1093 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001094
Dan Gohman3a302cb2009-07-13 20:50:19 +00001095 FoldingSetNodeID ID;
1096 ID.AddInteger(scTruncate);
1097 ID.AddPointer(Op);
1098 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001099 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001100 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1101
Dan Gohman3423e722009-06-30 20:13:32 +00001102 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001103 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001104 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001105 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001106
Dan Gohman79af8542009-04-22 16:20:48 +00001107 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001108 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001109 return getTruncateExpr(ST->getOperand(), Ty);
1110
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001111 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001112 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001113 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1114
1115 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001116 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001117 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1118
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001119 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1120 // eliminate all the truncates.
1121 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1122 SmallVector<const SCEV *, 4> Operands;
1123 bool hasTrunc = false;
1124 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1125 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
1127 Operands.push_back(S);
1128 }
1129 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001130 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001132 }
1133
Nick Lewycky5c901f32011-01-19 18:56:00 +00001134 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1135 // eliminate all the truncates.
1136 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1137 SmallVector<const SCEV *, 4> Operands;
1138 bool hasTrunc = false;
1139 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1140 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1141 hasTrunc = isa<SCEVTruncateExpr>(S);
1142 Operands.push_back(S);
1143 }
1144 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001145 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001146 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001147 }
1148
Dan Gohman5a728c92009-06-18 16:24:47 +00001149 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001150 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001151 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00001152 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman2e55cc52009-05-08 21:03:19 +00001153 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001154 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001155 }
1156
Dan Gohman89dd42a2010-06-25 18:47:08 +00001157 // The cast wasn't folded; create an explicit cast node. We can reuse
1158 // the existing insert position since if we get here, we won't have
1159 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001160 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1161 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001162 UniqueSCEVs.InsertNode(S, IP);
1163 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001164}
1165
Dan Gohmanaf752342009-07-07 17:06:11 +00001166const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001167 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001168 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001169 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001170 assert(isSCEVable(Ty) &&
1171 "This is not a conversion to a SCEVable type!");
1172 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001173
Dan Gohman3423e722009-06-30 20:13:32 +00001174 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001175 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1176 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001177 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001178
Dan Gohman79af8542009-04-22 16:20:48 +00001179 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001180 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001181 return getZeroExtendExpr(SZ->getOperand(), Ty);
1182
Dan Gohman74a0ba12009-07-13 20:55:53 +00001183 // Before doing any expensive analysis, check to see if we've already
1184 // computed a SCEV for this Op and Ty.
1185 FoldingSetNodeID ID;
1186 ID.AddInteger(scZeroExtend);
1187 ID.AddPointer(Op);
1188 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001189 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1191
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001192 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1193 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1194 // It's possible the bits taken off by the truncate were all zero bits. If
1195 // so, we should be able to simplify this further.
1196 const SCEV *X = ST->getOperand();
1197 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001198 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1199 unsigned NewBits = getTypeSizeInBits(Ty);
1200 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001201 CR.zextOrTrunc(NewBits)))
1202 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001203 }
1204
Dan Gohman76466372009-04-27 20:16:15 +00001205 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001206 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001207 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001208 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001209 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001210 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001211 const SCEV *Start = AR->getStart();
1212 const SCEV *Step = AR->getStepRecurrence(*this);
1213 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1214 const Loop *L = AR->getLoop();
1215
Dan Gohman62ef6a72009-07-25 01:22:26 +00001216 // If we have special knowledge that this addrec won't overflow,
1217 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001218 if (AR->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman62ef6a72009-07-25 01:22:26 +00001219 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1220 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001221 L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001222
Dan Gohman76466372009-04-27 20:16:15 +00001223 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1224 // Note that this serves two purposes: It filters out loops that are
1225 // simply not analyzable, and it covers the case where this code is
1226 // being called from within backedge-taken count analysis, such that
1227 // attempting to ask for the backedge-taken count would likely result
1228 // in infinite recursion. In the later case, the analysis code will
1229 // cope with a conservative value, and it will take care to purge
1230 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001231 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001232 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001233 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001234 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001235
1236 // Check whether the backedge-taken count can be losslessly casted to
1237 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001238 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001239 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001240 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001241 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1242 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001243 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001244 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001245 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001246 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1247 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1248 const SCEV *WideMaxBECount =
1249 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001250 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001251 getAddExpr(WideStart,
1252 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001253 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001254 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001255 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1256 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001257 // Return the expression with the addrec on the outside.
1258 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1259 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001260 L, AR->getNoWrapFlags());
1261 }
Dan Gohman76466372009-04-27 20:16:15 +00001262 // Similar to above, only this time treat the step value as signed.
1263 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001264 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001265 getAddExpr(WideStart,
1266 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001267 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001268 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001269 // Cache knowledge of AR NW, which is propagated to this AddRec.
1270 // Negative step causes unsigned wrap, but it still can't self-wrap.
1271 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001272 // Return the expression with the addrec on the outside.
1273 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1274 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001275 L, AR->getNoWrapFlags());
1276 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001277 }
1278
1279 // If the backedge is guarded by a comparison with the pre-inc value
1280 // the addrec is safe. Also, if the entry is guarded by a comparison
1281 // with the start value and the backedge is guarded by a comparison
1282 // with the post-inc value, the addrec is safe.
1283 if (isKnownPositive(Step)) {
1284 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1285 getUnsignedRange(Step).getUnsignedMax());
1286 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001287 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001288 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001289 AR->getPostIncExpr(*this), N))) {
1290 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1291 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001292 // Return the expression with the addrec on the outside.
1293 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1294 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001295 L, AR->getNoWrapFlags());
1296 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001297 } else if (isKnownNegative(Step)) {
1298 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1299 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001300 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1301 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001302 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001303 AR->getPostIncExpr(*this), N))) {
1304 // Cache knowledge of AR NW, which is propagated to this AddRec.
1305 // Negative step causes unsigned wrap, but it still can't self-wrap.
1306 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1307 // Return the expression with the addrec on the outside.
Dan Gohmane65c9172009-07-13 21:35:55 +00001308 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1309 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001310 L, AR->getNoWrapFlags());
1311 }
Dan Gohman76466372009-04-27 20:16:15 +00001312 }
1313 }
1314 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001315
Dan Gohman74a0ba12009-07-13 20:55:53 +00001316 // The cast wasn't folded; create an explicit cast node.
1317 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001318 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001319 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1320 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001321 UniqueSCEVs.InsertNode(S, IP);
1322 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001323}
1324
Andrew Trick812276e2011-05-31 21:17:47 +00001325// Get the limit of a recurrence such that incrementing by Step cannot cause
1326// signed overflow as long as the value of the recurrence within the loop does
1327// not exceed this limit before incrementing.
1328static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1329 ICmpInst::Predicate *Pred,
1330 ScalarEvolution *SE) {
1331 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1332 if (SE->isKnownPositive(Step)) {
1333 *Pred = ICmpInst::ICMP_SLT;
1334 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1335 SE->getSignedRange(Step).getSignedMax());
1336 }
1337 if (SE->isKnownNegative(Step)) {
1338 *Pred = ICmpInst::ICMP_SGT;
1339 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1340 SE->getSignedRange(Step).getSignedMin());
1341 }
Craig Topper9f008862014-04-15 04:59:12 +00001342 return nullptr;
Andrew Trick812276e2011-05-31 21:17:47 +00001343}
1344
1345// The recurrence AR has been shown to have no signed wrap. Typically, if we can
1346// prove NSW for AR, then we can just as easily prove NSW for its preincrement
1347// or postincrement sibling. This allows normalizing a sign extended AddRec as
1348// such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1349// result, the expression "Step + sext(PreIncAR)" is congruent with
1350// "sext(PostIncAR)"
1351static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
Chris Lattner229907c2011-07-18 04:54:35 +00001352 Type *Ty,
Andrew Trick812276e2011-05-31 21:17:47 +00001353 ScalarEvolution *SE) {
1354 const Loop *L = AR->getLoop();
1355 const SCEV *Start = AR->getStart();
1356 const SCEV *Step = AR->getStepRecurrence(*SE);
1357
1358 // Check for a simple looking step prior to loop entry.
1359 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001360 if (!SA)
Craig Topper9f008862014-04-15 04:59:12 +00001361 return nullptr;
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001362
1363 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1364 // subtraction is expensive. For this purpose, perform a quick and dirty
1365 // difference, by checking for Step in the operand list.
1366 SmallVector<const SCEV *, 4> DiffOps;
Tobias Grosser924221c2014-05-07 06:07:47 +00001367 for (const SCEV *Op : SA->operands())
1368 if (Op != Step)
1369 DiffOps.push_back(Op);
1370
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001371 if (DiffOps.size() == SA->getNumOperands())
Craig Topper9f008862014-04-15 04:59:12 +00001372 return nullptr;
Andrew Trick812276e2011-05-31 21:17:47 +00001373
1374 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1375 // same three conditions that getSignExtendedExpr checks.
1376
1377 // 1. NSW flags on the step increment.
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001378 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
Andrew Trick812276e2011-05-31 21:17:47 +00001379 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1380 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1381
Andrew Trick8ef3ad02011-06-01 19:14:56 +00001382 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trick812276e2011-05-31 21:17:47 +00001383 return PreStart;
Andrew Trick812276e2011-05-31 21:17:47 +00001384
1385 // 2. Direct overflow check on the step operation's expression.
1386 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
Chris Lattner229907c2011-07-18 04:54:35 +00001387 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
Andrew Trick812276e2011-05-31 21:17:47 +00001388 const SCEV *OperandExtendedStart =
1389 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1390 SE->getSignExtendExpr(Step, WideTy));
1391 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1392 // Cache knowledge of PreAR NSW.
1393 if (PreAR)
1394 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1395 // FIXME: this optimization needs a unit test
1396 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1397 return PreStart;
1398 }
1399
1400 // 3. Loop precondition.
1401 ICmpInst::Predicate Pred;
1402 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1403
Andrew Trick8ef3ad02011-06-01 19:14:56 +00001404 if (OverflowLimit &&
1405 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
Andrew Trick812276e2011-05-31 21:17:47 +00001406 return PreStart;
1407 }
Craig Topper9f008862014-04-15 04:59:12 +00001408 return nullptr;
Andrew Trick812276e2011-05-31 21:17:47 +00001409}
1410
1411// Get the normalized sign-extended expression for this AddRec's Start.
1412static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
Chris Lattner229907c2011-07-18 04:54:35 +00001413 Type *Ty,
Andrew Trick812276e2011-05-31 21:17:47 +00001414 ScalarEvolution *SE) {
1415 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1416 if (!PreStart)
1417 return SE->getSignExtendExpr(AR->getStart(), Ty);
1418
1419 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1420 SE->getSignExtendExpr(PreStart, Ty));
1421}
1422
Dan Gohmanaf752342009-07-07 17:06:11 +00001423const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001424 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001425 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001426 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001427 assert(isSCEVable(Ty) &&
1428 "This is not a conversion to a SCEVable type!");
1429 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001430
Dan Gohman3423e722009-06-30 20:13:32 +00001431 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001432 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1433 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001434 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001435
Dan Gohman79af8542009-04-22 16:20:48 +00001436 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001437 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001438 return getSignExtendExpr(SS->getOperand(), Ty);
1439
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001440 // sext(zext(x)) --> zext(x)
1441 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1442 return getZeroExtendExpr(SZ->getOperand(), Ty);
1443
Dan Gohman74a0ba12009-07-13 20:55:53 +00001444 // Before doing any expensive analysis, check to see if we've already
1445 // computed a SCEV for this Op and Ty.
1446 FoldingSetNodeID ID;
1447 ID.AddInteger(scSignExtend);
1448 ID.AddPointer(Op);
1449 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001450 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1452
Nick Lewyckyb32c8942011-01-22 22:06:21 +00001453 // If the input value is provably positive, build a zext instead.
1454 if (isKnownNonNegative(Op))
1455 return getZeroExtendExpr(Op, Ty);
1456
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001457 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1458 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1459 // It's possible the bits taken off by the truncate were all sign bits. If
1460 // so, we should be able to simplify this further.
1461 const SCEV *X = ST->getOperand();
1462 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001463 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1464 unsigned NewBits = getTypeSizeInBits(Ty);
1465 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001466 CR.sextOrTrunc(NewBits)))
1467 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001468 }
1469
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001470 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1471 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1472 if (SA->getNumOperands() == 2) {
1473 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1474 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1475 if (SMul && SC1) {
1476 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001477 const APInt &C1 = SC1->getValue()->getValue();
1478 const APInt &C2 = SC2->getValue()->getValue();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001479 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001480 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001481 return getAddExpr(getSignExtendExpr(SC1, Ty),
1482 getSignExtendExpr(SMul, Ty));
1483 }
1484 }
1485 }
1486 }
Dan Gohman76466372009-04-27 20:16:15 +00001487 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001488 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001489 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001490 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001491 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001492 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001493 const SCEV *Start = AR->getStart();
1494 const SCEV *Step = AR->getStepRecurrence(*this);
1495 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1496 const Loop *L = AR->getLoop();
1497
Dan Gohman62ef6a72009-07-25 01:22:26 +00001498 // If we have special knowledge that this addrec won't overflow,
1499 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001500 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trick812276e2011-05-31 21:17:47 +00001501 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman62ef6a72009-07-25 01:22:26 +00001502 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001503 L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001504
Dan Gohman76466372009-04-27 20:16:15 +00001505 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1506 // Note that this serves two purposes: It filters out loops that are
1507 // simply not analyzable, and it covers the case where this code is
1508 // being called from within backedge-taken count analysis, such that
1509 // attempting to ask for the backedge-taken count would likely result
1510 // in infinite recursion. In the later case, the analysis code will
1511 // cope with a conservative value, and it will take care to purge
1512 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001513 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001514 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001515 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001516 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001517
1518 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001519 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001520 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001521 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001522 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001523 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1524 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001525 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001526 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001527 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001528 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1529 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1530 const SCEV *WideMaxBECount =
1531 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001532 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001533 getAddExpr(WideStart,
1534 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001535 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001536 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001537 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1538 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001539 // Return the expression with the addrec on the outside.
Andrew Trick812276e2011-05-31 21:17:47 +00001540 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman494dac32009-04-29 22:28:28 +00001541 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001542 L, AR->getNoWrapFlags());
1543 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001544 // Similar to above, only this time treat the step value as unsigned.
1545 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001546 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001547 getAddExpr(WideStart,
1548 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001549 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001550 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001551 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1552 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman8c129d72009-07-16 17:34:36 +00001553 // Return the expression with the addrec on the outside.
Andrew Trick812276e2011-05-31 21:17:47 +00001554 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman8c129d72009-07-16 17:34:36 +00001555 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001556 L, AR->getNoWrapFlags());
1557 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001558 }
1559
1560 // If the backedge is guarded by a comparison with the pre-inc value
1561 // the addrec is safe. Also, if the entry is guarded by a comparison
1562 // with the start value and the backedge is guarded by a comparison
1563 // with the post-inc value, the addrec is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001564 ICmpInst::Predicate Pred;
1565 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1566 if (OverflowLimit &&
1567 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1568 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1569 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1570 OverflowLimit)))) {
1571 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1572 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1573 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1574 getSignExtendExpr(Step, Ty),
1575 L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001576 }
1577 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001578 // If Start and Step are constants, check if we can apply this
1579 // transformation:
1580 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1581 auto SC1 = dyn_cast<SCEVConstant>(Start);
1582 auto SC2 = dyn_cast<SCEVConstant>(Step);
1583 if (SC1 && SC2) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001584 const APInt &C1 = SC1->getValue()->getValue();
1585 const APInt &C2 = SC2->getValue()->getValue();
1586 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1587 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001588 Start = getSignExtendExpr(Start, Ty);
1589 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1590 L, AR->getNoWrapFlags());
1591 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1592 }
1593 }
Dan Gohman76466372009-04-27 20:16:15 +00001594 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001595
Dan Gohman74a0ba12009-07-13 20:55:53 +00001596 // The cast wasn't folded; create an explicit cast node.
1597 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001599 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1600 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001601 UniqueSCEVs.InsertNode(S, IP);
1602 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001603}
1604
Dan Gohman8db2edc2009-06-13 15:56:47 +00001605/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1606/// unspecified bits out to the given type.
1607///
Dan Gohmanaf752342009-07-07 17:06:11 +00001608const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001609 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001610 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1611 "This is not an extending conversion!");
1612 assert(isSCEVable(Ty) &&
1613 "This is not a conversion to a SCEVable type!");
1614 Ty = getEffectiveSCEVType(Ty);
1615
1616 // Sign-extend negative constants.
1617 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1618 if (SC->getValue()->getValue().isNegative())
1619 return getSignExtendExpr(Op, Ty);
1620
1621 // Peel off a truncate cast.
1622 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001623 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001624 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1625 return getAnyExtendExpr(NewOp, Ty);
1626 return getTruncateOrNoop(NewOp, Ty);
1627 }
1628
1629 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001630 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001631 if (!isa<SCEVZeroExtendExpr>(ZExt))
1632 return ZExt;
1633
1634 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001635 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001636 if (!isa<SCEVSignExtendExpr>(SExt))
1637 return SExt;
1638
Dan Gohman51ad99d2010-01-21 02:09:26 +00001639 // Force the cast to be folded into the operands of an addrec.
1640 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1641 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001642 for (const SCEV *Op : AR->operands())
1643 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001644 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001645 }
1646
Dan Gohman8db2edc2009-06-13 15:56:47 +00001647 // If the expression is obviously signed, use the sext cast value.
1648 if (isa<SCEVSMaxExpr>(Op))
1649 return SExt;
1650
1651 // Absent any other information, use the zext cast value.
1652 return ZExt;
1653}
1654
Dan Gohman038d02e2009-06-14 22:58:51 +00001655/// CollectAddOperandsWithScales - Process the given Ops list, which is
1656/// a list of operands to be added under the given scale, update the given
1657/// map. This is a helper function for getAddRecExpr. As an example of
1658/// what it does, given a sequence of operands that would form an add
1659/// expression like this:
1660///
Tobias Grosserba49e422014-03-05 10:37:17 +00001661/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001662///
1663/// where A and B are constants, update the map with these values:
1664///
1665/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1666///
1667/// and add 13 + A*B*29 to AccumulatedConstant.
1668/// This will allow getAddRecExpr to produce this:
1669///
1670/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1671///
1672/// This form often exposes folding opportunities that are hidden in
1673/// the original operand list.
1674///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001675/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001676/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1677/// the common case where no interesting opportunities are present, and
1678/// is also used as a check to avoid infinite recursion.
1679///
1680static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001681CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001682 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001683 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001684 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001685 const APInt &Scale,
1686 ScalarEvolution &SE) {
1687 bool Interesting = false;
1688
Dan Gohman45073042010-06-18 19:12:32 +00001689 // Iterate over the add operands. They are sorted, with constants first.
1690 unsigned i = 0;
1691 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1692 ++i;
1693 // Pull a buried constant out to the outside.
1694 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1695 Interesting = true;
1696 AccumulatedConstant += Scale * C->getValue()->getValue();
1697 }
1698
1699 // Next comes everything else. We're especially interested in multiplies
1700 // here, but they're in the middle, so just visit the rest with one loop.
1701 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001702 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1703 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1704 APInt NewScale =
1705 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1706 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1707 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001708 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001709 Interesting |=
1710 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001711 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001712 NewScale, SE);
1713 } else {
1714 // A multiplication of a constant with some other value. Update
1715 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001716 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1717 const SCEV *Key = SE.getMulExpr(MulOps);
1718 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001719 M.insert(std::make_pair(Key, NewScale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001720 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001721 NewOps.push_back(Pair.first->first);
1722 } else {
1723 Pair.first->second += NewScale;
1724 // The map already had an entry for this value, which may indicate
1725 // a folding opportunity.
1726 Interesting = true;
1727 }
1728 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001729 } else {
1730 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001731 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001732 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001733 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001734 NewOps.push_back(Pair.first->first);
1735 } else {
1736 Pair.first->second += Scale;
1737 // The map already had an entry for this value, which may indicate
1738 // a folding opportunity.
1739 Interesting = true;
1740 }
1741 }
1742 }
1743
1744 return Interesting;
1745}
1746
1747namespace {
1748 struct APIntCompare {
1749 bool operator()(const APInt &LHS, const APInt &RHS) const {
1750 return LHS.ult(RHS);
1751 }
1752 };
1753}
1754
Dan Gohman4d5435d2009-05-24 23:45:28 +00001755/// getAddExpr - Get a canonical add expression, or something simpler if
1756/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00001757const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00001758 SCEV::NoWrapFlags Flags) {
1759 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1760 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00001761 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00001762 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00001763#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00001764 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00001765 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00001766 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00001767 "SCEVAddExpr operand types don't match!");
1768#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00001769
Andrew Trick8b55b732011-03-14 16:50:06 +00001770 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001771 // And vice-versa.
1772 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1773 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1774 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001775 bool All = true;
Dan Gohman74c61502010-08-16 16:27:53 +00001776 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1777 E = Ops.end(); I != E; ++I)
1778 if (!isKnownNonNegative(*I)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001779 All = false;
1780 break;
1781 }
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001782 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001783 }
1784
Chris Lattnerd934c702004-04-02 20:23:17 +00001785 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00001786 GroupByComplexity(Ops, LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00001787
1788 // If there are any constants, fold them together.
1789 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00001790 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001791 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00001792 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00001793 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001794 // We found two constants, fold them together!
Dan Gohman0652fd52009-06-14 22:47:23 +00001795 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1796 RHSC->getValue()->getValue());
Dan Gohman011cf682009-06-14 22:53:57 +00001797 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001798 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001799 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001800 }
1801
1802 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00001803 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001804 Ops.erase(Ops.begin());
1805 --Idx;
1806 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001807
Dan Gohmanebbd05f2010-04-12 23:08:18 +00001808 if (Ops.size() == 1) return Ops[0];
1809 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001810
Dan Gohman15871f22010-08-27 21:39:59 +00001811 // Okay, check to see if the same value occurs in the operand list more than
1812 // once. If so, merge them together into an multiply expression. Since we
1813 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00001814 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00001815 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00001816 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00001817 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00001818 // Scan ahead to count how many equal operands there are.
1819 unsigned Count = 2;
1820 while (i+Count != e && Ops[i+Count] == Ops[i])
1821 ++Count;
1822 // Merge the values into a multiply.
1823 const SCEV *Scale = getConstant(Ty, Count);
1824 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1825 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00001826 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00001827 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00001828 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00001829 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00001830 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00001831 }
Dan Gohmane67b2872010-08-12 14:46:54 +00001832 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00001833 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00001834
Dan Gohman2e55cc52009-05-08 21:03:19 +00001835 // Check for truncates. If all the operands are truncated from the same
1836 // type, see if factoring out the truncate would permit the result to be
1837 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1838 // if the contents of the resulting outer trunc fold to something simple.
1839 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1840 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00001841 Type *DstType = Trunc->getType();
1842 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00001843 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00001844 bool Ok = true;
1845 // Check all the operands to see if they can be represented in the
1846 // source type of the truncate.
1847 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1848 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1849 if (T->getOperand()->getType() != SrcType) {
1850 Ok = false;
1851 break;
1852 }
1853 LargeOps.push_back(T->getOperand());
1854 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00001855 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00001856 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001857 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00001858 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1859 if (const SCEVTruncateExpr *T =
1860 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1861 if (T->getOperand()->getType() != SrcType) {
1862 Ok = false;
1863 break;
1864 }
1865 LargeMulOps.push_back(T->getOperand());
1866 } else if (const SCEVConstant *C =
1867 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00001868 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00001869 } else {
1870 Ok = false;
1871 break;
1872 }
1873 }
1874 if (Ok)
1875 LargeOps.push_back(getMulExpr(LargeMulOps));
1876 } else {
1877 Ok = false;
1878 break;
1879 }
1880 }
1881 if (Ok) {
1882 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00001883 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00001884 // If it folds to something simple, use it. Otherwise, don't.
1885 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1886 return getTruncateExpr(Fold, DstType);
1887 }
1888 }
1889
1890 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00001891 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1892 ++Idx;
1893
1894 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00001895 if (Idx < Ops.size()) {
1896 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00001897 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001898 // If we have an add, expand the add operands onto the end of the operands
1899 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00001900 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00001901 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00001902 DeletedAdd = true;
1903 }
1904
1905 // If we deleted at least one add, we added operands to the end of the list,
1906 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00001907 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00001908 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00001909 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001910 }
1911
1912 // Skip over the add expression until we get to a multiply.
1913 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1914 ++Idx;
1915
Dan Gohman038d02e2009-06-14 22:58:51 +00001916 // Check to see if there are any folding opportunities present with
1917 // operands multiplied by constant values.
1918 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1919 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00001920 DenseMap<const SCEV *, APInt> M;
1921 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00001922 APInt AccumulatedConstant(BitWidth, 0);
1923 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001924 Ops.data(), Ops.size(),
1925 APInt(BitWidth, 1), *this)) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001926 // Some interesting folding opportunity is present, so its worthwhile to
1927 // re-generate the operands list. Group the operands by constant scale,
1928 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00001929 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Craig Topper31ee5862013-07-03 15:07:05 +00001930 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001931 E = NewOps.end(); I != E; ++I)
1932 MulOpLists[M.find(*I)->second].push_back(*I);
1933 // Re-generate the operands list.
1934 Ops.clear();
1935 if (AccumulatedConstant != 0)
1936 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohmance973df2009-06-24 04:48:43 +00001937 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1938 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman038d02e2009-06-14 22:58:51 +00001939 if (I->first != 0)
Dan Gohmance973df2009-06-24 04:48:43 +00001940 Ops.push_back(getMulExpr(getConstant(I->first),
1941 getAddExpr(I->second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00001942 if (Ops.empty())
Dan Gohman1d2ded72010-05-03 22:09:21 +00001943 return getConstant(Ty, 0);
Dan Gohman038d02e2009-06-14 22:58:51 +00001944 if (Ops.size() == 1)
1945 return Ops[0];
1946 return getAddExpr(Ops);
1947 }
1948 }
1949
Chris Lattnerd934c702004-04-02 20:23:17 +00001950 // If we are adding something to a multiply expression, make sure the
1951 // something is not already an operand of the multiply. If so, merge it into
1952 // the multiply.
1953 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00001954 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001955 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00001956 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00001957 if (isa<SCEVConstant>(MulOpSCEV))
1958 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00001959 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00001960 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001961 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00001962 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00001963 if (Mul->getNumOperands() != 2) {
1964 // If the multiply has more than two operands, we must get the
1965 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00001966 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1967 Mul->op_begin()+MulOp);
1968 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00001969 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00001970 }
Dan Gohman1d2ded72010-05-03 22:09:21 +00001971 const SCEV *One = getConstant(Ty, 1);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00001972 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00001973 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00001974 if (Ops.size() == 2) return OuterMul;
1975 if (AddOp < Idx) {
1976 Ops.erase(Ops.begin()+AddOp);
1977 Ops.erase(Ops.begin()+Idx-1);
1978 } else {
1979 Ops.erase(Ops.begin()+Idx);
1980 Ops.erase(Ops.begin()+AddOp-1);
1981 }
1982 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00001983 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001984 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001985
Chris Lattnerd934c702004-04-02 20:23:17 +00001986 // Check this multiply against other multiplies being added together.
1987 for (unsigned OtherMulIdx = Idx+1;
1988 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1989 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00001990 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001991 // If MulOp occurs in OtherMul, we can fold the two multiplies
1992 // together.
1993 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1994 OMulOp != e; ++OMulOp)
1995 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1996 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00001997 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00001998 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00001999 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002000 Mul->op_begin()+MulOp);
2001 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002002 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002003 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002004 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002005 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002006 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002007 OtherMul->op_begin()+OMulOp);
2008 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002009 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002010 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002011 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2012 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002013 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002014 Ops.erase(Ops.begin()+Idx);
2015 Ops.erase(Ops.begin()+OtherMulIdx-1);
2016 Ops.push_back(OuterMul);
2017 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002018 }
2019 }
2020 }
2021 }
2022
2023 // If there are any add recurrences in the operands list, see if any other
2024 // added values are loop invariant. If so, we can fold them into the
2025 // recurrence.
2026 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2027 ++Idx;
2028
2029 // Scan over all recurrences, trying to fold loop invariants into them.
2030 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2031 // Scan all of the other operands to this add and add them to the vector if
2032 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002033 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002034 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002035 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002036 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002037 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002038 LIOps.push_back(Ops[i]);
2039 Ops.erase(Ops.begin()+i);
2040 --i; --e;
2041 }
2042
2043 // If we found some loop invariants, fold them into the recurrence.
2044 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002045 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002046 LIOps.push_back(AddRec->getStart());
2047
Dan Gohmanaf752342009-07-07 17:06:11 +00002048 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002049 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002050 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002051
Dan Gohman16206132010-06-30 07:16:37 +00002052 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002053 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002054 // Always propagate NW.
2055 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002056 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002057
Chris Lattnerd934c702004-04-02 20:23:17 +00002058 // If all of the other operands were loop invariant, we are done.
2059 if (Ops.size() == 1) return NewRec;
2060
Nick Lewyckydb66b822011-09-06 05:08:09 +00002061 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002062 for (unsigned i = 0;; ++i)
2063 if (Ops[i] == AddRec) {
2064 Ops[i] = NewRec;
2065 break;
2066 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002067 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002068 }
2069
2070 // Okay, if there weren't any loop invariants to be folded, check to see if
2071 // there are multiple AddRec's with the same loop induction variable being
2072 // added together. If so, we can fold them.
2073 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002074 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2075 ++OtherIdx)
2076 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2077 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2078 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2079 AddRec->op_end());
2080 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2081 ++OtherIdx)
Dan Gohman028c1812010-08-29 14:53:34 +00002082 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohmanc866bf42010-08-27 20:45:56 +00002083 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002084 if (OtherAddRec->getLoop() == AddRecLoop) {
2085 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2086 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002087 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002088 AddRecOps.append(OtherAddRec->op_begin()+i,
2089 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002090 break;
2091 }
Dan Gohman028c1812010-08-29 14:53:34 +00002092 AddRecOps[i] = getAddExpr(AddRecOps[i],
2093 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002094 }
2095 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002096 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002097 // Step size has changed, so we cannot guarantee no self-wraparound.
2098 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002099 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002100 }
2101
2102 // Otherwise couldn't fold anything into this recurrence. Move onto the
2103 // next one.
2104 }
2105
2106 // Okay, it looks like we really DO need an add expr. Check to see if we
2107 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002108 FoldingSetNodeID ID;
2109 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002110 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2111 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002112 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002113 SCEVAddExpr *S =
2114 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2115 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002116 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2117 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002118 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2119 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002120 UniqueSCEVs.InsertNode(S, IP);
2121 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002122 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002123 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002124}
2125
Nick Lewycky287682e2011-10-04 06:51:26 +00002126static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2127 uint64_t k = i*j;
2128 if (j > 1 && k / j != i) Overflow = true;
2129 return k;
2130}
2131
2132/// Compute the result of "n choose k", the binomial coefficient. If an
2133/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002134/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002135static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2136 // We use the multiplicative formula:
2137 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2138 // At each iteration, we take the n-th term of the numeral and divide by the
2139 // (k-n)th term of the denominator. This division will always produce an
2140 // integral result, and helps reduce the chance of overflow in the
2141 // intermediate computations. However, we can still overflow even when the
2142 // final result would fit.
2143
2144 if (n == 0 || n == k) return 1;
2145 if (k > n) return 0;
2146
2147 if (k > n/2)
2148 k = n-k;
2149
2150 uint64_t r = 1;
2151 for (uint64_t i = 1; i <= k; ++i) {
2152 r = umul_ov(r, n-(i-1), Overflow);
2153 r /= i;
2154 }
2155 return r;
2156}
2157
Dan Gohman4d5435d2009-05-24 23:45:28 +00002158/// getMulExpr - Get a canonical multiply expression, or something simpler if
2159/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002160const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002161 SCEV::NoWrapFlags Flags) {
2162 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2163 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002164 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002165 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002166#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002167 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002168 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002169 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002170 "SCEVMulExpr operand types don't match!");
2171#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002172
Andrew Trick8b55b732011-03-14 16:50:06 +00002173 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002174 // And vice-versa.
2175 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2176 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2177 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002178 bool All = true;
Dan Gohman74c61502010-08-16 16:27:53 +00002179 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
2180 E = Ops.end(); I != E; ++I)
2181 if (!isKnownNonNegative(*I)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002182 All = false;
2183 break;
2184 }
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002185 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002186 }
2187
Chris Lattnerd934c702004-04-02 20:23:17 +00002188 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002189 GroupByComplexity(Ops, LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002190
2191 // If there are any constants, fold them together.
2192 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002193 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002194
2195 // C1*(C2+V) -> C1*C2 + C1*V
2196 if (Ops.size() == 2)
Dan Gohmana30370b2009-05-04 22:02:23 +00002197 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattnerd934c702004-04-02 20:23:17 +00002198 if (Add->getNumOperands() == 2 &&
2199 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohmana37eaf22007-10-22 18:31:58 +00002200 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2201 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002202
Chris Lattnerd934c702004-04-02 20:23:17 +00002203 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002204 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002205 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002206 ConstantInt *Fold = ConstantInt::get(getContext(),
2207 LHSC->getValue()->getValue() *
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002208 RHSC->getValue()->getValue());
2209 Ops[0] = getConstant(Fold);
2210 Ops.erase(Ops.begin()+1); // Erase the folded element
2211 if (Ops.size() == 1) return Ops[0];
2212 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002213 }
2214
2215 // If we are left with a constant one being multiplied, strip it off.
2216 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2217 Ops.erase(Ops.begin());
2218 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002219 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002220 // If we have a multiply of zero, it will always be zero.
2221 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002222 } else if (Ops[0]->isAllOnesValue()) {
2223 // If we have a mul by -1 of an add, try distributing the -1 among the
2224 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002225 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002226 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2227 SmallVector<const SCEV *, 4> NewOps;
2228 bool AnyFolded = false;
Andrew Trick8b55b732011-03-14 16:50:06 +00002229 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2230 E = Add->op_end(); I != E; ++I) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002231 const SCEV *Mul = getMulExpr(Ops[0], *I);
2232 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2233 NewOps.push_back(Mul);
2234 }
2235 if (AnyFolded)
2236 return getAddExpr(NewOps);
2237 }
Andrew Tricke92dcce2011-03-14 17:38:54 +00002238 else if (const SCEVAddRecExpr *
2239 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2240 // Negation preserves a recurrence's no self-wrap property.
2241 SmallVector<const SCEV *, 4> Operands;
2242 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2243 E = AddRec->op_end(); I != E; ++I) {
2244 Operands.push_back(getMulExpr(Ops[0], *I));
2245 }
2246 return getAddRecExpr(Operands, AddRec->getLoop(),
2247 AddRec->getNoWrapFlags(SCEV::FlagNW));
2248 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002249 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002250 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002251
2252 if (Ops.size() == 1)
2253 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002254 }
2255
2256 // Skip over the add expression until we get to a multiply.
2257 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2258 ++Idx;
2259
Chris Lattnerd934c702004-04-02 20:23:17 +00002260 // If there are mul operands inline them all into this expression.
2261 if (Idx < Ops.size()) {
2262 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002263 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002264 // If we have an mul, expand the mul operands onto the end of the operands
2265 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002266 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002267 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002268 DeletedMul = true;
2269 }
2270
2271 // If we deleted at least one mul, we added operands to the end of the list,
2272 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002273 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002274 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002275 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002276 }
2277
2278 // If there are any add recurrences in the operands list, see if any other
2279 // added values are loop invariant. If so, we can fold them into the
2280 // recurrence.
2281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2282 ++Idx;
2283
2284 // Scan over all recurrences, trying to fold loop invariants into them.
2285 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2286 // Scan all of the other operands to this mul and add them to the vector if
2287 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002288 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002289 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002290 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002291 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002292 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002293 LIOps.push_back(Ops[i]);
2294 Ops.erase(Ops.begin()+i);
2295 --i; --e;
2296 }
2297
2298 // If we found some loop invariants, fold them into the recurrence.
2299 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002300 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002301 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002302 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002303 const SCEV *Scale = getMulExpr(LIOps);
2304 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2305 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002306
Dan Gohman16206132010-06-30 07:16:37 +00002307 // Build the new addrec. Propagate the NUW and NSW flags if both the
2308 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002309 //
2310 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002311 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002312 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2313 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002314
2315 // If all of the other operands were loop invariant, we are done.
2316 if (Ops.size() == 1) return NewRec;
2317
Nick Lewyckydb66b822011-09-06 05:08:09 +00002318 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002319 for (unsigned i = 0;; ++i)
2320 if (Ops[i] == AddRec) {
2321 Ops[i] = NewRec;
2322 break;
2323 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002324 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002325 }
2326
2327 // Okay, if there weren't any loop invariants to be folded, check to see if
2328 // there are multiple AddRec's with the same loop induction variable being
2329 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002330
2331 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2332 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2333 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2334 // ]]],+,...up to x=2n}.
2335 // Note that the arguments to choose() are always integers with values
2336 // known at compile time, never SCEV objects.
2337 //
2338 // The implementation avoids pointless extra computations when the two
2339 // addrec's are of different length (mathematically, it's equivalent to
2340 // an infinite stream of zeros on the right).
2341 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002342 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002343 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002344 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002345 const SCEVAddRecExpr *OtherAddRec =
2346 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2347 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002348 continue;
2349
Nick Lewycky97756402014-09-01 05:17:15 +00002350 bool Overflow = false;
2351 Type *Ty = AddRec->getType();
2352 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2353 SmallVector<const SCEV*, 7> AddRecOps;
2354 for (int x = 0, xe = AddRec->getNumOperands() +
2355 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2356 const SCEV *Term = getConstant(Ty, 0);
2357 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2358 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2359 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2360 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2361 z < ze && !Overflow; ++z) {
2362 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2363 uint64_t Coeff;
2364 if (LargerThan64Bits)
2365 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2366 else
2367 Coeff = Coeff1*Coeff2;
2368 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2369 const SCEV *Term1 = AddRec->getOperand(y-z);
2370 const SCEV *Term2 = OtherAddRec->getOperand(z);
2371 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002372 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002373 }
Nick Lewycky97756402014-09-01 05:17:15 +00002374 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002375 }
Nick Lewycky97756402014-09-01 05:17:15 +00002376 if (!Overflow) {
2377 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2378 SCEV::FlagAnyWrap);
2379 if (Ops.size() == 2) return NewAddRec;
2380 Ops[Idx] = NewAddRec;
2381 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2382 OpsModified = true;
2383 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2384 if (!AddRec)
2385 break;
2386 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002387 }
Nick Lewycky97756402014-09-01 05:17:15 +00002388 if (OpsModified)
2389 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002390
2391 // Otherwise couldn't fold anything into this recurrence. Move onto the
2392 // next one.
2393 }
2394
2395 // Okay, it looks like we really DO need an mul expr. Check to see if we
2396 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002397 FoldingSetNodeID ID;
2398 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002399 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2400 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002401 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002402 SCEVMulExpr *S =
2403 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2404 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002405 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2406 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002407 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2408 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002409 UniqueSCEVs.InsertNode(S, IP);
2410 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002411 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002412 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002413}
2414
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002415/// getUDivExpr - Get a canonical unsigned division expression, or something
2416/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002417const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2418 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002419 assert(getEffectiveSCEVType(LHS->getType()) ==
2420 getEffectiveSCEVType(RHS->getType()) &&
2421 "SCEVUDivExpr operand types don't match!");
2422
Dan Gohmana30370b2009-05-04 22:02:23 +00002423 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002424 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002425 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002426 // If the denominator is zero, the result of the udiv is undefined. Don't
2427 // try to analyze it, because the resolution chosen here may differ from
2428 // the resolution chosen in other parts of the compiler.
2429 if (!RHSC->getValue()->isZero()) {
2430 // Determine if the division can be folded into the operands of
2431 // its operands.
2432 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002433 Type *Ty = LHS->getType();
Dan Gohmanacd700a2010-04-22 01:35:11 +00002434 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002435 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002436 // For non-power-of-two values, effectively round the value up to the
2437 // nearest power of two.
2438 if (!RHSC->getValue()->getValue().isPowerOf2())
2439 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002440 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002441 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002442 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2443 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002444 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2445 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2446 const APInt &StepInt = Step->getValue()->getValue();
2447 const APInt &DivInt = RHSC->getValue()->getValue();
2448 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002449 getZeroExtendExpr(AR, ExtTy) ==
2450 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2451 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002452 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002453 SmallVector<const SCEV *, 4> Operands;
2454 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2455 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick8b55b732011-03-14 16:50:06 +00002456 return getAddRecExpr(Operands, AR->getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002457 SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002458 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002459 /// Get a canonical UDivExpr for a recurrence.
2460 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2461 // We can currently only fold X%N if X is constant.
2462 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2463 if (StartC && !DivInt.urem(StepInt) &&
2464 getZeroExtendExpr(AR, ExtTy) ==
2465 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2466 getZeroExtendExpr(Step, ExtTy),
2467 AR->getLoop(), SCEV::FlagAnyWrap)) {
2468 const APInt &StartInt = StartC->getValue()->getValue();
2469 const APInt &StartRem = StartInt.urem(StepInt);
2470 if (StartRem != 0)
2471 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2472 AR->getLoop(), SCEV::FlagNW);
2473 }
2474 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002475 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2476 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2477 SmallVector<const SCEV *, 4> Operands;
2478 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2479 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2480 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2481 // Find an operand that's safely divisible.
2482 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2483 const SCEV *Op = M->getOperand(i);
2484 const SCEV *Div = getUDivExpr(Op, RHSC);
2485 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2486 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2487 M->op_end());
2488 Operands[i] = Div;
2489 return getMulExpr(Operands);
2490 }
2491 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002492 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002493 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Andrew Trick7d1eea82011-04-27 18:17:36 +00002494 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002495 SmallVector<const SCEV *, 4> Operands;
2496 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2497 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2498 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2499 Operands.clear();
2500 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2501 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2502 if (isa<SCEVUDivExpr>(Op) ||
2503 getMulExpr(Op, RHS) != A->getOperand(i))
2504 break;
2505 Operands.push_back(Op);
2506 }
2507 if (Operands.size() == A->getNumOperands())
2508 return getAddExpr(Operands);
2509 }
2510 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002511
Dan Gohmanacd700a2010-04-22 01:35:11 +00002512 // Fold if both operands are constant.
2513 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2514 Constant *LHSCV = LHSC->getValue();
2515 Constant *RHSCV = RHSC->getValue();
2516 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2517 RHSCV)));
2518 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002519 }
2520 }
2521
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002522 FoldingSetNodeID ID;
2523 ID.AddInteger(scUDivExpr);
2524 ID.AddPointer(LHS);
2525 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002526 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002527 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002528 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2529 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002530 UniqueSCEVs.InsertNode(S, IP);
2531 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002532}
2533
Nick Lewycky31eaca52014-01-27 10:04:03 +00002534static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2535 APInt A = C1->getValue()->getValue().abs();
2536 APInt B = C2->getValue()->getValue().abs();
2537 uint32_t ABW = A.getBitWidth();
2538 uint32_t BBW = B.getBitWidth();
2539
2540 if (ABW > BBW)
2541 B = B.zext(ABW);
2542 else if (ABW < BBW)
2543 A = A.zext(BBW);
2544
2545 return APIntOps::GreatestCommonDivisor(A, B);
2546}
2547
2548/// getUDivExactExpr - Get a canonical unsigned division expression, or
2549/// something simpler if possible. There is no representation for an exact udiv
2550/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2551/// We can't do this when it's not exact because the udiv may be clearing bits.
2552const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2553 const SCEV *RHS) {
2554 // TODO: we could try to find factors in all sorts of things, but for now we
2555 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2556 // end of this file for inspiration.
2557
2558 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2559 if (!Mul)
2560 return getUDivExpr(LHS, RHS);
2561
2562 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2563 // If the mulexpr multiplies by a constant, then that constant must be the
2564 // first element of the mulexpr.
2565 if (const SCEVConstant *LHSCst =
2566 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2567 if (LHSCst == RHSCst) {
2568 SmallVector<const SCEV *, 2> Operands;
2569 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2570 return getMulExpr(Operands);
2571 }
2572
2573 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2574 // that there's a factor provided by one of the other terms. We need to
2575 // check.
2576 APInt Factor = gcd(LHSCst, RHSCst);
2577 if (!Factor.isIntN(1)) {
2578 LHSCst = cast<SCEVConstant>(
2579 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2580 RHSCst = cast<SCEVConstant>(
2581 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2582 SmallVector<const SCEV *, 2> Operands;
2583 Operands.push_back(LHSCst);
2584 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2585 LHS = getMulExpr(Operands);
2586 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002587 Mul = dyn_cast<SCEVMulExpr>(LHS);
2588 if (!Mul)
2589 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002590 }
2591 }
2592 }
2593
2594 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2595 if (Mul->getOperand(i) == RHS) {
2596 SmallVector<const SCEV *, 2> Operands;
2597 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2598 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2599 return getMulExpr(Operands);
2600 }
2601 }
2602
2603 return getUDivExpr(LHS, RHS);
2604}
Chris Lattnerd934c702004-04-02 20:23:17 +00002605
Dan Gohman4d5435d2009-05-24 23:45:28 +00002606/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2607/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002608const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2609 const Loop *L,
2610 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002611 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002612 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002613 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002614 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002615 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002616 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002617 }
2618
2619 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002620 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002621}
2622
Dan Gohman4d5435d2009-05-24 23:45:28 +00002623/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2624/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002625const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002626ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002627 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002628 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002629#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002630 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002631 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002632 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002633 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002634 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002635 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002636 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002637#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002638
Dan Gohmanbe928e32008-06-18 16:23:07 +00002639 if (Operands.back()->isZero()) {
2640 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002641 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002642 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002643
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002644 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2645 // use that information to infer NUW and NSW flags. However, computing a
2646 // BE count requires calling getAddRecExpr, so we may not yet have a
2647 // meaningful BE count at this point (and if we don't, we'd be stuck
2648 // with a SCEVCouldNotCompute as the cached BE count).
2649
Andrew Trick8b55b732011-03-14 16:50:06 +00002650 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002651 // And vice-versa.
2652 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2653 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2654 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002655 bool All = true;
Dan Gohman74c61502010-08-16 16:27:53 +00002656 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2657 E = Operands.end(); I != E; ++I)
2658 if (!isKnownNonNegative(*I)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002659 All = false;
2660 break;
2661 }
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002662 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002663 }
2664
Dan Gohman223a5d22008-08-08 18:33:12 +00002665 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002666 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002667 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman63c020a2010-08-13 20:23:25 +00002668 if (L->contains(NestedLoop) ?
Dan Gohman51ad99d2010-01-21 02:09:26 +00002669 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman63c020a2010-08-13 20:23:25 +00002670 (!NestedLoop->contains(L) &&
Dan Gohman51ad99d2010-01-21 02:09:26 +00002671 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002672 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002673 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002674 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002675 // AddRecs require their operands be loop-invariant with respect to their
2676 // loops. Don't perform this transformation if it would break this
2677 // requirement.
2678 bool AllInvariant = true;
2679 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002680 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002681 AllInvariant = false;
2682 break;
2683 }
2684 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002685 // Create a recurrence for the outer loop with the same step size.
2686 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002687 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2688 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002689 SCEV::NoWrapFlags OuterFlags =
2690 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002691
2692 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohmancc030b72009-06-26 22:36:20 +00002693 AllInvariant = true;
2694 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002695 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002696 AllInvariant = false;
2697 break;
2698 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002699 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002700 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002701 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002702 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2703 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002704 SCEV::NoWrapFlags InnerFlags =
2705 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002706 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2707 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002708 }
2709 // Reset Operands to its original state.
2710 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002711 }
2712 }
2713
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002714 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2715 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002716 FoldingSetNodeID ID;
2717 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002718 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2719 ID.AddPointer(Operands[i]);
2720 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002721 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002722 SCEVAddRecExpr *S =
2723 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2724 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002725 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2726 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002727 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2728 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002729 UniqueSCEVs.InsertNode(S, IP);
2730 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002731 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002732 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002733}
2734
Dan Gohmanabd17092009-06-24 14:49:00 +00002735const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2736 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002737 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002738 Ops.push_back(LHS);
2739 Ops.push_back(RHS);
2740 return getSMaxExpr(Ops);
2741}
2742
Dan Gohmanaf752342009-07-07 17:06:11 +00002743const SCEV *
2744ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002745 assert(!Ops.empty() && "Cannot get empty smax!");
2746 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002747#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002748 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002749 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002750 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002751 "SCEVSMaxExpr operand types don't match!");
2752#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002753
2754 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002755 GroupByComplexity(Ops, LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002756
2757 // If there are any constants, fold them together.
2758 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002759 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002760 ++Idx;
2761 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002762 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002763 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002764 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002765 APIntOps::smax(LHSC->getValue()->getValue(),
2766 RHSC->getValue()->getValue()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002767 Ops[0] = getConstant(Fold);
2768 Ops.erase(Ops.begin()+1); // Erase the folded element
2769 if (Ops.size() == 1) return Ops[0];
2770 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002771 }
2772
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002773 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002774 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2775 Ops.erase(Ops.begin());
2776 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002777 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2778 // If we have an smax with a constant maximum-int, it will always be
2779 // maximum-int.
2780 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002781 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002782
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002783 if (Ops.size() == 1) return Ops[0];
2784 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002785
2786 // Find the first SMax
2787 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2788 ++Idx;
2789
2790 // Check to see if one of the operands is an SMax. If so, expand its operands
2791 // onto our operand list, and recurse to simplify.
2792 if (Idx < Ops.size()) {
2793 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002794 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002795 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002796 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002797 DeletedSMax = true;
2798 }
2799
2800 if (DeletedSMax)
2801 return getSMaxExpr(Ops);
2802 }
2803
2804 // Okay, check to see if the same value occurs in the operand list twice. If
2805 // so, delete one. Since we sorted the list, these values are required to
2806 // be adjacent.
2807 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00002808 // X smax Y smax Y --> X smax Y
2809 // X smax Y --> X, if X is always greater than Y
2810 if (Ops[i] == Ops[i+1] ||
2811 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2812 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2813 --i; --e;
2814 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002815 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2816 --i; --e;
2817 }
2818
2819 if (Ops.size() == 1) return Ops[0];
2820
2821 assert(!Ops.empty() && "Reduced smax down to nothing!");
2822
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002823 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002824 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002825 FoldingSetNodeID ID;
2826 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002827 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2828 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002829 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002830 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00002831 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2832 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002833 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2834 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002835 UniqueSCEVs.InsertNode(S, IP);
2836 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002837}
2838
Dan Gohmanabd17092009-06-24 14:49:00 +00002839const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2840 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002841 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002842 Ops.push_back(LHS);
2843 Ops.push_back(RHS);
2844 return getUMaxExpr(Ops);
2845}
2846
Dan Gohmanaf752342009-07-07 17:06:11 +00002847const SCEV *
2848ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002849 assert(!Ops.empty() && "Cannot get empty umax!");
2850 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002851#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002852 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002853 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002854 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002855 "SCEVUMaxExpr operand types don't match!");
2856#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002857
2858 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002859 GroupByComplexity(Ops, LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002860
2861 // If there are any constants, fold them together.
2862 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002863 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002864 ++Idx;
2865 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002866 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002867 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002868 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002869 APIntOps::umax(LHSC->getValue()->getValue(),
2870 RHSC->getValue()->getValue()));
2871 Ops[0] = getConstant(Fold);
2872 Ops.erase(Ops.begin()+1); // Erase the folded element
2873 if (Ops.size() == 1) return Ops[0];
2874 LHSC = cast<SCEVConstant>(Ops[0]);
2875 }
2876
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002877 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002878 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2879 Ops.erase(Ops.begin());
2880 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002881 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2882 // If we have an umax with a constant maximum-int, it will always be
2883 // maximum-int.
2884 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002885 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002886
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002887 if (Ops.size() == 1) return Ops[0];
2888 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002889
2890 // Find the first UMax
2891 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2892 ++Idx;
2893
2894 // Check to see if one of the operands is a UMax. If so, expand its operands
2895 // onto our operand list, and recurse to simplify.
2896 if (Idx < Ops.size()) {
2897 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002898 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002899 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002900 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002901 DeletedUMax = true;
2902 }
2903
2904 if (DeletedUMax)
2905 return getUMaxExpr(Ops);
2906 }
2907
2908 // Okay, check to see if the same value occurs in the operand list twice. If
2909 // so, delete one. Since we sorted the list, these values are required to
2910 // be adjacent.
2911 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00002912 // X umax Y umax Y --> X umax Y
2913 // X umax Y --> X, if X is always greater than Y
2914 if (Ops[i] == Ops[i+1] ||
2915 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2916 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2917 --i; --e;
2918 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002919 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2920 --i; --e;
2921 }
2922
2923 if (Ops.size() == 1) return Ops[0];
2924
2925 assert(!Ops.empty() && "Reduced umax down to nothing!");
2926
2927 // Okay, it looks like we really DO need a umax expr. Check to see if we
2928 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002929 FoldingSetNodeID ID;
2930 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002931 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2932 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002933 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002934 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00002935 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2936 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002937 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2938 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002939 UniqueSCEVs.InsertNode(S, IP);
2940 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002941}
2942
Dan Gohmanabd17092009-06-24 14:49:00 +00002943const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2944 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00002945 // ~smax(~x, ~y) == smin(x, y).
2946 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2947}
2948
Dan Gohmanabd17092009-06-24 14:49:00 +00002949const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2950 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00002951 // ~umax(~x, ~y) == umin(x, y)
2952 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2953}
2954
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002955const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002956 // If we have DataLayout, we can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00002957 // constant expression and then folding it back into a ConstantInt.
2958 // This is just a compile-time optimization.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002959 if (DL)
2960 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
Dan Gohman11862a62010-04-12 23:03:26 +00002961
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002962 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002964 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmana3b6c4b2010-05-28 16:12:08 +00002965 C = Folded;
Chris Lattner229907c2011-07-18 04:54:35 +00002966 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002967 assert(Ty == IntTy && "Effective SCEV type doesn't match");
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002968 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2969}
2970
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002971const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
2972 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002973 unsigned FieldNo) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002974 // If we have DataLayout, we can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00002975 // constant expression and then folding it back into a ConstantInt.
2976 // This is just a compile-time optimization.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002977 if (DL) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002978 return getConstant(IntTy,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002979 DL->getStructLayout(STy)->getElementOffset(FieldNo));
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002980 }
Dan Gohman11862a62010-04-12 23:03:26 +00002981
Dan Gohmancf913832010-01-28 02:15:55 +00002982 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2983 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002984 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmana3b6c4b2010-05-28 16:12:08 +00002985 C = Folded;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00002986
Matt Arsenault4ed49b52013-10-21 18:08:09 +00002987 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohmancf913832010-01-28 02:15:55 +00002988 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00002989}
2990
Dan Gohmanaf752342009-07-07 17:06:11 +00002991const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00002992 // Don't attempt to do anything other than create a SCEVUnknown object
2993 // here. createSCEV only calls getUnknown after checking for all other
2994 // interesting possibilities, and any other code that calls getUnknown
2995 // is doing so in order to hide a value from SCEV canonicalization.
2996
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002997 FoldingSetNodeID ID;
2998 ID.AddInteger(scUnknown);
2999 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003000 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003001 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3002 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3003 "Stale SCEVUnknown in uniquing map!");
3004 return S;
3005 }
3006 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3007 FirstUnknown);
3008 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003009 UniqueSCEVs.InsertNode(S, IP);
3010 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003011}
3012
Chris Lattnerd934c702004-04-02 20:23:17 +00003013//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003014// Basic SCEV Analysis and PHI Idiom Recognition Code
3015//
3016
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003017/// isSCEVable - Test if values of the given type are analyzable within
3018/// the SCEV framework. This primarily includes integer types, and it
3019/// can optionally include pointer types if the ScalarEvolution class
3020/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003021bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003022 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003023 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003024}
3025
3026/// getTypeSizeInBits - Return the size in bits of the specified type,
3027/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003028uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003029 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3030
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003031 // If we have a DataLayout, use it!
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003032 if (DL)
3033 return DL->getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003034
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003035 // Integer types have fixed sizes.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003036 if (Ty->isIntegerTy())
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003037 return Ty->getPrimitiveSizeInBits();
3038
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003039 // The only other support type is pointer. Without DataLayout, conservatively
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003040 // assume pointers are 64-bit.
Duncan Sands19d0b472010-02-16 11:11:14 +00003041 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003042 return 64;
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003043}
3044
3045/// getEffectiveSCEVType - Return a type with the same bitwidth as
3046/// the given type and which represents how SCEV will treat the given
3047/// type, for which isSCEVable must return true. For pointer types,
3048/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003049Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003050 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3051
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003052 if (Ty->isIntegerTy()) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003053 return Ty;
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003054 }
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003055
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003056 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003057 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003058
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003059 if (DL)
3060 return DL->getIntPtrType(Ty);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003061
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003062 // Without DataLayout, conservatively assume pointers are 64-bit.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003063 return Type::getInt64Ty(getContext());
Dan Gohman0a40ad92009-04-16 03:18:22 +00003064}
Chris Lattnerd934c702004-04-02 20:23:17 +00003065
Dan Gohmanaf752342009-07-07 17:06:11 +00003066const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003067 return &CouldNotCompute;
Dan Gohman31efa302009-04-18 17:58:19 +00003068}
3069
Shuxin Yangefc4c012013-07-08 17:33:13 +00003070namespace {
3071 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3072 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3073 // is set iff if find such SCEVUnknown.
3074 //
3075 struct FindInvalidSCEVUnknown {
3076 bool FindOne;
3077 FindInvalidSCEVUnknown() { FindOne = false; }
3078 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003079 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003080 case scConstant:
3081 return false;
3082 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003083 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003084 FindOne = true;
3085 return false;
3086 default:
3087 return true;
3088 }
3089 }
3090 bool isDone() const { return FindOne; }
3091 };
3092}
3093
3094bool ScalarEvolution::checkValidity(const SCEV *S) const {
3095 FindInvalidSCEVUnknown F;
3096 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3097 ST.visitAll(S);
3098
3099 return !F.FindOne;
3100}
3101
Chris Lattnerd934c702004-04-02 20:23:17 +00003102/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3103/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003104const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003105 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003106
Shuxin Yangefc4c012013-07-08 17:33:13 +00003107 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3108 if (I != ValueExprMap.end()) {
3109 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003110 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003111 return S;
3112 else
3113 ValueExprMap.erase(I);
3114 }
Dan Gohmanaf752342009-07-07 17:06:11 +00003115 const SCEV *S = createSCEV(V);
Dan Gohmanc29eeae2010-08-16 16:31:39 +00003116
3117 // The process of creating a SCEV for V may have caused other SCEVs
3118 // to have been created, so it's necessary to insert the new entry
3119 // from scratch, rather than trying to remember the insert position
3120 // above.
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003121 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattnerd934c702004-04-02 20:23:17 +00003122 return S;
3123}
3124
Dan Gohman0a40ad92009-04-16 03:18:22 +00003125/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3126///
Dan Gohmanaf752342009-07-07 17:06:11 +00003127const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003128 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003129 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003130 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003131
Chris Lattner229907c2011-07-18 04:54:35 +00003132 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003133 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003134 return getMulExpr(V,
Owen Anderson5a1acd92009-07-31 20:28:14 +00003135 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003136}
3137
3138/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003139const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003140 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003141 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003142 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003143
Chris Lattner229907c2011-07-18 04:54:35 +00003144 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003145 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003146 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003147 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003148 return getMinusSCEV(AllOnes, V);
3149}
3150
Andrew Trick8b55b732011-03-14 16:50:06 +00003151/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003152const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003153 SCEV::NoWrapFlags Flags) {
Andrew Tricka34f1b12011-03-15 01:16:14 +00003154 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
3155
Dan Gohman46f00a22010-07-20 16:53:00 +00003156 // Fast path: X - X --> 0.
3157 if (LHS == RHS)
3158 return getConstant(LHS->getType(), 0);
3159
Dan Gohman0a40ad92009-04-16 03:18:22 +00003160 // X - Y --> X + -Y
Andrew Trick8b55b732011-03-14 16:50:06 +00003161 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003162}
3163
3164/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3165/// input value to the specified type. If the type must be extended, it is zero
3166/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003167const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003168ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3169 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003170 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3171 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003172 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003173 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003174 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003175 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003176 return getTruncateExpr(V, Ty);
3177 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003178}
3179
3180/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3181/// input value to the specified type. If the type must be extended, it is sign
3182/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003183const SCEV *
3184ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003185 Type *Ty) {
3186 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003187 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3188 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003189 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003190 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003191 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003192 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003193 return getTruncateExpr(V, Ty);
3194 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003195}
3196
Dan Gohmane712a2f2009-05-13 03:46:30 +00003197/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3198/// input value to the specified type. If the type must be extended, it is zero
3199/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003200const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003201ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3202 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003203 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3204 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003205 "Cannot noop or zero extend with non-integer arguments!");
3206 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3207 "getNoopOrZeroExtend cannot truncate!");
3208 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3209 return V; // No conversion
3210 return getZeroExtendExpr(V, Ty);
3211}
3212
3213/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3214/// input value to the specified type. If the type must be extended, it is sign
3215/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003216const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003217ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3218 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003219 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3220 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003221 "Cannot noop or sign extend with non-integer arguments!");
3222 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3223 "getNoopOrSignExtend cannot truncate!");
3224 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3225 return V; // No conversion
3226 return getSignExtendExpr(V, Ty);
3227}
3228
Dan Gohman8db2edc2009-06-13 15:56:47 +00003229/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3230/// the input value to the specified type. If the type must be extended,
3231/// it is extended with unspecified bits. The conversion must not be
3232/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003233const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003234ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3235 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003236 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3237 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003238 "Cannot noop or any extend with non-integer arguments!");
3239 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3240 "getNoopOrAnyExtend cannot truncate!");
3241 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3242 return V; // No conversion
3243 return getAnyExtendExpr(V, Ty);
3244}
3245
Dan Gohmane712a2f2009-05-13 03:46:30 +00003246/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3247/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003248const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003249ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3250 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003251 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3252 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003253 "Cannot truncate or noop with non-integer arguments!");
3254 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3255 "getTruncateOrNoop cannot extend!");
3256 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3257 return V; // No conversion
3258 return getTruncateExpr(V, Ty);
3259}
3260
Dan Gohman96212b62009-06-22 00:31:57 +00003261/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3262/// the types using zero-extension, and then perform a umax operation
3263/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003264const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3265 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003266 const SCEV *PromotedLHS = LHS;
3267 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003268
3269 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3270 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3271 else
3272 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3273
3274 return getUMaxExpr(PromotedLHS, PromotedRHS);
3275}
3276
Dan Gohman2bc22302009-06-22 15:03:27 +00003277/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3278/// the types using zero-extension, and then perform a umin operation
3279/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003280const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3281 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003282 const SCEV *PromotedLHS = LHS;
3283 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003284
3285 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3286 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3287 else
3288 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3289
3290 return getUMinExpr(PromotedLHS, PromotedRHS);
3291}
3292
Andrew Trick87716c92011-03-17 23:51:11 +00003293/// getPointerBase - Transitively follow the chain of pointer-type operands
3294/// until reaching a SCEV that does not have a single pointer operand. This
3295/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3296/// but corner cases do exist.
3297const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3298 // A pointer operand may evaluate to a nonpointer expression, such as null.
3299 if (!V->getType()->isPointerTy())
3300 return V;
3301
3302 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3303 return getPointerBase(Cast->getOperand());
3304 }
3305 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003306 const SCEV *PtrOp = nullptr;
Andrew Trick87716c92011-03-17 23:51:11 +00003307 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3308 I != E; ++I) {
3309 if ((*I)->getType()->isPointerTy()) {
3310 // Cannot find the base of an expression with multiple pointer operands.
3311 if (PtrOp)
3312 return V;
3313 PtrOp = *I;
3314 }
3315 }
3316 if (!PtrOp)
3317 return V;
3318 return getPointerBase(PtrOp);
3319 }
3320 return V;
3321}
3322
Dan Gohman0b89dff2009-07-25 01:13:03 +00003323/// PushDefUseChildren - Push users of the given Instruction
3324/// onto the given Worklist.
3325static void
3326PushDefUseChildren(Instruction *I,
3327 SmallVectorImpl<Instruction *> &Worklist) {
3328 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003329 for (User *U : I->users())
3330 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003331}
3332
3333/// ForgetSymbolicValue - This looks up computed SCEV values for all
3334/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003335/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003336/// resolution.
Dan Gohmance973df2009-06-24 04:48:43 +00003337void
Dan Gohmana9c205c2010-02-25 06:57:05 +00003338ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003339 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003340 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003341
Dan Gohman0b89dff2009-07-25 01:13:03 +00003342 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003343 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003344 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003345 Instruction *I = Worklist.pop_back_val();
Dan Gohman0b89dff2009-07-25 01:13:03 +00003346 if (!Visited.insert(I)) continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003347
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003348 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00003349 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003350 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003351 const SCEV *Old = It->second;
3352
Dan Gohman0b89dff2009-07-25 01:13:03 +00003353 // Short-circuit the def-use traversal if the symbolic name
3354 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003355 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003356 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003357
Dan Gohman0b89dff2009-07-25 01:13:03 +00003358 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003359 // structure, it's a PHI that's in the progress of being computed
3360 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3361 // additional loop trip count information isn't going to change anything.
3362 // In the second case, createNodeForPHI will perform the necessary
3363 // updates on its own when it gets to that point. In the third, we do
3364 // want to forget the SCEVUnknown.
3365 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003366 !isa<SCEVUnknown>(Old) ||
3367 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003368 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003369 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003370 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003371 }
3372
3373 PushDefUseChildren(I, Worklist);
3374 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003375}
Chris Lattnerd934c702004-04-02 20:23:17 +00003376
3377/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3378/// a loop header, making it a potential recurrence, or it doesn't.
3379///
Dan Gohmanaf752342009-07-07 17:06:11 +00003380const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman6635bb22010-04-12 07:49:36 +00003381 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3382 if (L->getHeader() == PN->getParent()) {
3383 // The loop may have multiple entrances or multiple exits; we can analyze
3384 // this phi as an addrec if it has a unique entry value and a unique
3385 // backedge value.
Craig Topper9f008862014-04-15 04:59:12 +00003386 Value *BEValueV = nullptr, *StartValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003387 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3388 Value *V = PN->getIncomingValue(i);
3389 if (L->contains(PN->getIncomingBlock(i))) {
3390 if (!BEValueV) {
3391 BEValueV = V;
3392 } else if (BEValueV != V) {
Craig Topper9f008862014-04-15 04:59:12 +00003393 BEValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003394 break;
3395 }
3396 } else if (!StartValueV) {
3397 StartValueV = V;
3398 } else if (StartValueV != V) {
Craig Topper9f008862014-04-15 04:59:12 +00003399 StartValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003400 break;
3401 }
3402 }
3403 if (BEValueV && StartValueV) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003404 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanaf752342009-07-07 17:06:11 +00003405 const SCEV *SymbolicName = getUnknown(PN);
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00003406 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
Chris Lattnerd934c702004-04-02 20:23:17 +00003407 "PHI node already processed?");
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003408 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattnerd934c702004-04-02 20:23:17 +00003409
3410 // Using this symbolic name for the PHI, analyze the value coming around
3411 // the back-edge.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003412 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattnerd934c702004-04-02 20:23:17 +00003413
3414 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3415 // has a special value for the first iteration of the loop.
3416
3417 // If the value coming around the backedge is an add with the symbolic
3418 // value we just inserted, then we found a simple induction variable!
Dan Gohmana30370b2009-05-04 22:02:23 +00003419 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003420 // If there is a single occurrence of the symbolic value, replace it
3421 // with a recurrence.
3422 unsigned FoundIndex = Add->getNumOperands();
3423 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3424 if (Add->getOperand(i) == SymbolicName)
3425 if (FoundIndex == e) {
3426 FoundIndex = i;
3427 break;
3428 }
3429
3430 if (FoundIndex != Add->getNumOperands()) {
3431 // Create an add with everything but the specified operand.
Dan Gohmanaf752342009-07-07 17:06:11 +00003432 SmallVector<const SCEV *, 8> Ops;
Chris Lattnerd934c702004-04-02 20:23:17 +00003433 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3434 if (i != FoundIndex)
3435 Ops.push_back(Add->getOperand(i));
Dan Gohmanaf752342009-07-07 17:06:11 +00003436 const SCEV *Accum = getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00003437
3438 // This is not a valid addrec if the step amount is varying each
3439 // loop iteration, but is not itself an addrec in this loop.
Dan Gohmanafd6db92010-11-17 21:23:15 +00003440 if (isLoopInvariant(Accum, L) ||
Chris Lattnerd934c702004-04-02 20:23:17 +00003441 (isa<SCEVAddRecExpr>(Accum) &&
3442 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003443 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003444
3445 // If the increment doesn't overflow, then neither the addrec nor
3446 // the post-increment will overflow.
3447 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3448 if (OBO->hasNoUnsignedWrap())
Andrew Trick8b55b732011-03-14 16:50:06 +00003449 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003450 if (OBO->hasNoSignedWrap())
Andrew Trick8b55b732011-03-14 16:50:06 +00003451 Flags = setFlags(Flags, SCEV::FlagNSW);
Benjamin Kramer6094f302013-10-28 07:30:06 +00003452 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003453 // If the increment is an inbounds GEP, then we know the address
3454 // space cannot be wrapped around. We cannot make any guarantee
3455 // about signed or unsigned overflow because pointers are
3456 // unsigned but we may have a negative index from the base
Benjamin Kramer6094f302013-10-28 07:30:06 +00003457 // pointer. We can guarantee that no unsigned wrap occurs if the
3458 // indices form a positive value.
3459 if (GEP->isInBounds()) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003460 Flags = setFlags(Flags, SCEV::FlagNW);
Benjamin Kramer6094f302013-10-28 07:30:06 +00003461
3462 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3463 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3464 Flags = setFlags(Flags, SCEV::FlagNUW);
3465 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00003466 } else if (const SubOperator *OBO =
3467 dyn_cast<SubOperator>(BEValueV)) {
3468 if (OBO->hasNoUnsignedWrap())
3469 Flags = setFlags(Flags, SCEV::FlagNUW);
3470 if (OBO->hasNoSignedWrap())
3471 Flags = setFlags(Flags, SCEV::FlagNSW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003472 }
3473
Dan Gohman6635bb22010-04-12 07:49:36 +00003474 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick8b55b732011-03-14 16:50:06 +00003475 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohman62ef6a72009-07-25 01:22:26 +00003476
Dan Gohman51ad99d2010-01-21 02:09:26 +00003477 // Since the no-wrap flags are on the increment, they apply to the
3478 // post-incremented value as well.
Dan Gohmanafd6db92010-11-17 21:23:15 +00003479 if (isLoopInvariant(Accum, L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00003480 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick8b55b732011-03-14 16:50:06 +00003481 Accum, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00003482
3483 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003484 // to be symbolic. We now need to go back and purge all of the
3485 // entries for the scalars that use the symbolic expression.
3486 ForgetSymbolicName(PN, SymbolicName);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003487 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattnerd934c702004-04-02 20:23:17 +00003488 return PHISCEV;
3489 }
3490 }
Dan Gohmana30370b2009-05-04 22:02:23 +00003491 } else if (const SCEVAddRecExpr *AddRec =
3492 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003493 // Otherwise, this could be a loop like this:
3494 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3495 // In this case, j = {1,+,1} and BEValue is j.
3496 // Because the other in-value of i (0) fits the evolution of BEValue
3497 // i really is an addrec evolution.
3498 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman6635bb22010-04-12 07:49:36 +00003499 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003500
3501 // If StartVal = j.start - j.stride, we can use StartVal as the
3502 // initial step of the addrec evolution.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003503 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman068b7932010-04-11 23:44:58 +00003504 AddRec->getOperand(1))) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003505 // FIXME: For constant StartVal, we should be able to infer
3506 // no-wrap flags.
Dan Gohmanaf752342009-07-07 17:06:11 +00003507 const SCEV *PHISCEV =
Andrew Trick8b55b732011-03-14 16:50:06 +00003508 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3509 SCEV::FlagAnyWrap);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003510
3511 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003512 // to be symbolic. We now need to go back and purge all of the
3513 // entries for the scalars that use the symbolic expression.
3514 ForgetSymbolicName(PN, SymbolicName);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003515 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003516 return PHISCEV;
3517 }
3518 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003519 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003520 }
Dan Gohman6635bb22010-04-12 07:49:36 +00003521 }
Misha Brukman01808ca2005-04-21 21:13:18 +00003522
Dan Gohmana9c205c2010-02-25 06:57:05 +00003523 // If the PHI has a single incoming value, follow that value, unless the
3524 // PHI's incoming blocks are in a different loop, in which case doing so
3525 // risks breaking LCSSA form. Instcombine would normally zap these, but
3526 // it doesn't have DominatorTree information, so it may miss cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003527 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AT))
Duncan Sandsaef146b2010-11-18 19:59:41 +00003528 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00003529 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00003530
Chris Lattnerd934c702004-04-02 20:23:17 +00003531 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003532 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00003533}
3534
Dan Gohmanee750d12009-05-08 20:26:55 +00003535/// createNodeForGEP - Expand GEP instructions into add and multiply
3536/// operations. This allows them to be analyzed by regular SCEV code.
3537///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00003538const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Chris Lattner229907c2011-07-18 04:54:35 +00003539 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohman2173bd32009-05-08 20:36:47 +00003540 Value *Base = GEP->getOperand(0);
Dan Gohman30f24fe2009-05-09 00:14:52 +00003541 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenault404c60a2013-10-21 19:43:56 +00003542 if (!Base->getType()->getPointerElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00003543 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00003544
3545 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3546 // Add expression, because the Instruction may be guarded by control flow
3547 // and the no-overflow bits may not be valid for the expression in any
3548 // context.
3549 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3550
Dan Gohman1d2ded72010-05-03 22:09:21 +00003551 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohman2173bd32009-05-08 20:36:47 +00003552 gep_type_iterator GTI = gep_type_begin(GEP);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003553 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
Dan Gohman2173bd32009-05-08 20:36:47 +00003554 E = GEP->op_end();
Dan Gohmanee750d12009-05-08 20:26:55 +00003555 I != E; ++I) {
3556 Value *Index = *I;
3557 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +00003558 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Dan Gohmanee750d12009-05-08 20:26:55 +00003559 // For a struct, add the member offset.
Dan Gohmanee750d12009-05-08 20:26:55 +00003560 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003561 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
Dan Gohman16206132010-06-30 07:16:37 +00003562
Dan Gohman16206132010-06-30 07:16:37 +00003563 // Add the field offset to the running total offset.
Dan Gohmanc0cca7f2010-06-30 17:27:11 +00003564 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohmanee750d12009-05-08 20:26:55 +00003565 } else {
3566 // For an array, add the element offset, explicitly scaled.
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003567 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
Dan Gohman16206132010-06-30 07:16:37 +00003568 const SCEV *IndexS = getSCEV(Index);
Dan Gohman8b0a4192010-03-01 17:49:51 +00003569 // Getelementptr indices are signed.
Dan Gohman16206132010-06-30 07:16:37 +00003570 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3571
Dan Gohman16206132010-06-30 07:16:37 +00003572 // Multiply the index by the element size to compute the element offset.
Matt Arsenault4c265902013-09-27 22:38:23 +00003573 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
Dan Gohman16206132010-06-30 07:16:37 +00003574
3575 // Add the element offset to the running total offset.
Dan Gohmanc0cca7f2010-06-30 17:27:11 +00003576 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohmanee750d12009-05-08 20:26:55 +00003577 }
3578 }
Dan Gohman16206132010-06-30 07:16:37 +00003579
3580 // Get the SCEV for the GEP base.
3581 const SCEV *BaseS = getSCEV(Base);
3582
Dan Gohman16206132010-06-30 07:16:37 +00003583 // Add the total offset from all the GEP indices to the base.
Matt Arsenault4c265902013-09-27 22:38:23 +00003584 return getAddExpr(BaseS, TotalOffset, Wrap);
Dan Gohmanee750d12009-05-08 20:26:55 +00003585}
3586
Nick Lewycky3783b462007-11-22 07:59:40 +00003587/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3588/// guaranteed to end in (at every loop iteration). It is, at the same time,
3589/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3590/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003591uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00003592ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003593 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner69ec1ec2007-11-23 22:36:49 +00003594 return C->getValue()->getValue().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00003595
Dan Gohmana30370b2009-05-04 22:02:23 +00003596 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00003597 return std::min(GetMinTrailingZeros(T->getOperand()),
3598 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00003599
Dan Gohmana30370b2009-05-04 22:02:23 +00003600 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00003601 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3602 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3603 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00003604 }
3605
Dan Gohmana30370b2009-05-04 22:02:23 +00003606 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00003607 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3608 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3609 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00003610 }
3611
Dan Gohmana30370b2009-05-04 22:02:23 +00003612 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003613 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003614 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00003615 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003616 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00003617 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003618 }
3619
Dan Gohmana30370b2009-05-04 22:02:23 +00003620 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003621 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003622 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3623 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00003624 for (unsigned i = 1, e = M->getNumOperands();
3625 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003626 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00003627 BitWidth);
3628 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003629 }
Nick Lewycky3783b462007-11-22 07:59:40 +00003630
Dan Gohmana30370b2009-05-04 22:02:23 +00003631 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003632 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003633 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00003634 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003635 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00003636 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003637 }
Nick Lewycky3783b462007-11-22 07:59:40 +00003638
Dan Gohmana30370b2009-05-04 22:02:23 +00003639 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003640 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003641 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003642 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003643 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003644 return MinOpRes;
3645 }
3646
Dan Gohmana30370b2009-05-04 22:02:23 +00003647 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003648 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003649 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003650 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003651 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003652 return MinOpRes;
3653 }
3654
Dan Gohmanc702fc02009-06-19 23:29:04 +00003655 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3656 // For a SCEVUnknown, ask ValueTracking.
3657 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00003658 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003659 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003660 return Zeros.countTrailingOnes();
3661 }
3662
3663 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00003664 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00003665}
Chris Lattnerd934c702004-04-02 20:23:17 +00003666
Sanjoy Das1f05c512014-10-10 21:22:34 +00003667/// GetRangeFromMetadata - Helper method to assign a range to V from
3668/// metadata present in the IR.
3669static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
3670 if (Instruction *I = dyn_cast<Instruction>(V)) {
3671 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
3672 ConstantRange TotalRange(
3673 cast<IntegerType>(I->getType())->getBitWidth(), false);
3674
3675 unsigned NumRanges = MD->getNumOperands() / 2;
3676 assert(NumRanges >= 1);
3677
3678 for (unsigned i = 0; i < NumRanges; ++i) {
3679 ConstantInt *Lower = cast<ConstantInt>(MD->getOperand(2*i + 0));
3680 ConstantInt *Upper = cast<ConstantInt>(MD->getOperand(2*i + 1));
3681 ConstantRange Range(Lower->getValue(), Upper->getValue());
3682 TotalRange = TotalRange.unionWith(Range);
3683 }
3684
3685 return TotalRange;
3686 }
3687 }
3688
3689 return None;
3690}
3691
Dan Gohmane65c9172009-07-13 21:35:55 +00003692/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3693///
3694ConstantRange
3695ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman761065e2010-11-17 02:44:44 +00003696 // See if we've computed this range already.
3697 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3698 if (I != UnsignedRanges.end())
3699 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00003700
3701 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohmaned756312010-11-17 20:23:08 +00003702 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003703
Dan Gohman85be4332010-01-26 19:19:05 +00003704 unsigned BitWidth = getTypeSizeInBits(S->getType());
3705 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3706
3707 // If the value has known zeros, the maximum unsigned value will have those
3708 // known zeros as well.
3709 uint32_t TZ = GetMinTrailingZeros(S);
3710 if (TZ != 0)
3711 ConservativeResult =
3712 ConstantRange(APInt::getMinValue(BitWidth),
3713 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3714
Dan Gohmane65c9172009-07-13 21:35:55 +00003715 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3716 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3717 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3718 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003719 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003720 }
3721
3722 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3723 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3724 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3725 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003726 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003727 }
3728
3729 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3730 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3731 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3732 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003733 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003734 }
3735
3736 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3737 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3738 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3739 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003740 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003741 }
3742
3743 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3744 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3745 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmaned756312010-11-17 20:23:08 +00003746 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003747 }
3748
3749 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3750 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003751 return setUnsignedRange(ZExt,
3752 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003753 }
3754
3755 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3756 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003757 return setUnsignedRange(SExt,
3758 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003759 }
3760
3761 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3762 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003763 return setUnsignedRange(Trunc,
3764 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003765 }
3766
Dan Gohmane65c9172009-07-13 21:35:55 +00003767 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003768 // If there's no unsigned wrap, the value will never be less than its
3769 // initial value.
Andrew Trick8b55b732011-03-14 16:50:06 +00003770 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman51ad99d2010-01-21 02:09:26 +00003771 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00003772 if (!C->getValue()->isZero())
Dan Gohmanae4a4142010-04-11 22:12:18 +00003773 ConservativeResult =
Dan Gohman9396b422010-06-30 06:58:35 +00003774 ConservativeResult.intersectWith(
3775 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003776
3777 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00003778 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003779 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00003780 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00003781 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3782 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohmane65c9172009-07-13 21:35:55 +00003783 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3784
3785 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00003786 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmane65c9172009-07-13 21:35:55 +00003787
3788 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003789 ConstantRange StepRange = getSignedRange(Step);
3790 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3791 ConstantRange EndRange =
3792 StartRange.add(MaxBECountRange.multiply(StepRange));
3793
3794 // Check for overflow. This must be done with ConstantRange arithmetic
3795 // because we could be called from within the ScalarEvolution overflow
3796 // checking code.
3797 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3798 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3799 ConstantRange ExtMaxBECountRange =
3800 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3801 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3802 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3803 ExtEndRange)
Dan Gohmaned756312010-11-17 20:23:08 +00003804 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003805
Dan Gohmane65c9172009-07-13 21:35:55 +00003806 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3807 EndRange.getUnsignedMin());
3808 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3809 EndRange.getUnsignedMax());
3810 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmaned756312010-11-17 20:23:08 +00003811 return setUnsignedRange(AddRec, ConservativeResult);
3812 return setUnsignedRange(AddRec,
3813 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003814 }
3815 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003816
Dan Gohmaned756312010-11-17 20:23:08 +00003817 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003818 }
3819
3820 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00003821 // Check if the IR explicitly contains !range metadata.
3822 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3823 if (MDRange.hasValue())
3824 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3825
Dan Gohmanc702fc02009-06-19 23:29:04 +00003826 // For a SCEVUnknown, ask ValueTracking.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003827 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003828 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
Dan Gohman1a7ab942009-07-20 22:34:18 +00003829 if (Ones == ~Zeros + 1)
Dan Gohmaned756312010-11-17 20:23:08 +00003830 return setUnsignedRange(U, ConservativeResult);
3831 return setUnsignedRange(U,
3832 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003833 }
3834
Dan Gohmaned756312010-11-17 20:23:08 +00003835 return setUnsignedRange(S, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003836}
3837
Dan Gohmane65c9172009-07-13 21:35:55 +00003838/// getSignedRange - Determine the signed range for a particular SCEV.
3839///
3840ConstantRange
3841ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman3ac8cd62011-01-24 17:54:18 +00003842 // See if we've computed this range already.
Dan Gohman761065e2010-11-17 02:44:44 +00003843 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3844 if (I != SignedRanges.end())
3845 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00003846
Dan Gohmane65c9172009-07-13 21:35:55 +00003847 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohmaned756312010-11-17 20:23:08 +00003848 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohmane65c9172009-07-13 21:35:55 +00003849
Dan Gohman51aaf022010-01-26 04:40:18 +00003850 unsigned BitWidth = getTypeSizeInBits(S->getType());
3851 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3852
3853 // If the value has known zeros, the maximum signed value will have those
3854 // known zeros as well.
3855 uint32_t TZ = GetMinTrailingZeros(S);
3856 if (TZ != 0)
3857 ConservativeResult =
3858 ConstantRange(APInt::getSignedMinValue(BitWidth),
3859 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3860
Dan Gohmane65c9172009-07-13 21:35:55 +00003861 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3862 ConstantRange X = getSignedRange(Add->getOperand(0));
3863 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3864 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003865 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003866 }
3867
Dan Gohmane65c9172009-07-13 21:35:55 +00003868 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3869 ConstantRange X = getSignedRange(Mul->getOperand(0));
3870 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3871 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003872 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003873 }
3874
Dan Gohmane65c9172009-07-13 21:35:55 +00003875 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3876 ConstantRange X = getSignedRange(SMax->getOperand(0));
3877 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3878 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003879 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003880 }
Dan Gohmand261d272009-06-24 01:05:09 +00003881
Dan Gohmane65c9172009-07-13 21:35:55 +00003882 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3883 ConstantRange X = getSignedRange(UMax->getOperand(0));
3884 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3885 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003886 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003887 }
Dan Gohmand261d272009-06-24 01:05:09 +00003888
Dan Gohmane65c9172009-07-13 21:35:55 +00003889 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3890 ConstantRange X = getSignedRange(UDiv->getLHS());
3891 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohmaned756312010-11-17 20:23:08 +00003892 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003893 }
Dan Gohmand261d272009-06-24 01:05:09 +00003894
Dan Gohmane65c9172009-07-13 21:35:55 +00003895 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3896 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003897 return setSignedRange(ZExt,
3898 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003899 }
3900
3901 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3902 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003903 return setSignedRange(SExt,
3904 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003905 }
3906
3907 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3908 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003909 return setSignedRange(Trunc,
3910 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003911 }
3912
Dan Gohmane65c9172009-07-13 21:35:55 +00003913 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003914 // If there's no signed wrap, and all the operands have the same sign or
3915 // zero, the value won't ever change sign.
Andrew Trick8b55b732011-03-14 16:50:06 +00003916 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003917 bool AllNonNeg = true;
3918 bool AllNonPos = true;
3919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3920 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3921 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3922 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003923 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00003924 ConservativeResult = ConservativeResult.intersectWith(
3925 ConstantRange(APInt(BitWidth, 0),
3926 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00003927 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00003928 ConservativeResult = ConservativeResult.intersectWith(
3929 ConstantRange(APInt::getSignedMinValue(BitWidth),
3930 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00003931 }
Dan Gohmane65c9172009-07-13 21:35:55 +00003932
3933 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00003934 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003935 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00003936 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00003937 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3938 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohmane65c9172009-07-13 21:35:55 +00003939 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3940
3941 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00003942 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmane65c9172009-07-13 21:35:55 +00003943
3944 ConstantRange StartRange = getSignedRange(Start);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003945 ConstantRange StepRange = getSignedRange(Step);
3946 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3947 ConstantRange EndRange =
3948 StartRange.add(MaxBECountRange.multiply(StepRange));
3949
3950 // Check for overflow. This must be done with ConstantRange arithmetic
3951 // because we could be called from within the ScalarEvolution overflow
3952 // checking code.
3953 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3954 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3955 ConstantRange ExtMaxBECountRange =
3956 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3957 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3958 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3959 ExtEndRange)
Dan Gohmaned756312010-11-17 20:23:08 +00003960 return setSignedRange(AddRec, ConservativeResult);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003961
Dan Gohmane65c9172009-07-13 21:35:55 +00003962 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3963 EndRange.getSignedMin());
3964 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3965 EndRange.getSignedMax());
3966 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmaned756312010-11-17 20:23:08 +00003967 return setSignedRange(AddRec, ConservativeResult);
3968 return setSignedRange(AddRec,
3969 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohmand261d272009-06-24 01:05:09 +00003970 }
Dan Gohmand261d272009-06-24 01:05:09 +00003971 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003972
Dan Gohmaned756312010-11-17 20:23:08 +00003973 return setSignedRange(AddRec, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00003974 }
3975
Dan Gohmanc702fc02009-06-19 23:29:04 +00003976 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00003977 // Check if the IR explicitly contains !range metadata.
3978 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3979 if (MDRange.hasValue())
3980 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3981
Dan Gohmanc702fc02009-06-19 23:29:04 +00003982 // For a SCEVUnknown, ask ValueTracking.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003983 if (!U->getValue()->getType()->isIntegerTy() && !DL)
Dan Gohmaned756312010-11-17 20:23:08 +00003984 return setSignedRange(U, ConservativeResult);
Hal Finkel60db0582014-09-07 18:57:58 +00003985 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AT, nullptr, DT);
Hal Finkelff666bd2013-07-09 18:16:16 +00003986 if (NS <= 1)
Dan Gohmaned756312010-11-17 20:23:08 +00003987 return setSignedRange(U, ConservativeResult);
3988 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohmane65c9172009-07-13 21:35:55 +00003989 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohmaned756312010-11-17 20:23:08 +00003990 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003991 }
3992
Dan Gohmaned756312010-11-17 20:23:08 +00003993 return setSignedRange(S, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003994}
3995
Chris Lattnerd934c702004-04-02 20:23:17 +00003996/// createSCEV - We know that there is no SCEV for the specified value.
3997/// Analyze the expression.
3998///
Dan Gohmanaf752342009-07-07 17:06:11 +00003999const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004000 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004001 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004002
Dan Gohman05e89732008-06-22 19:56:46 +00004003 unsigned Opcode = Instruction::UserOp1;
Dan Gohman69451a02010-03-09 23:46:50 +00004004 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman05e89732008-06-22 19:56:46 +00004005 Opcode = I->getOpcode();
Dan Gohman69451a02010-03-09 23:46:50 +00004006
4007 // Don't attempt to analyze instructions in blocks that aren't
4008 // reachable. Such instructions don't matter, and they aren't required
4009 // to obey basic rules for definitions dominating uses which this
4010 // analysis depends on.
4011 if (!DT->isReachableFromEntry(I->getParent()))
4012 return getUnknown(V);
4013 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman05e89732008-06-22 19:56:46 +00004014 Opcode = CE->getOpcode();
Dan Gohmanf436bac2009-06-24 00:54:57 +00004015 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4016 return getConstant(CI);
4017 else if (isa<ConstantPointerNull>(V))
Dan Gohman1d2ded72010-05-03 22:09:21 +00004018 return getConstant(V->getType(), 0);
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004019 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4020 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman05e89732008-06-22 19:56:46 +00004021 else
Dan Gohmanc8e23622009-04-21 23:15:49 +00004022 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004023
Dan Gohman80ca01c2009-07-17 20:47:02 +00004024 Operator *U = cast<Operator>(V);
Dan Gohman05e89732008-06-22 19:56:46 +00004025 switch (Opcode) {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004026 case Instruction::Add: {
4027 // The simple thing to do would be to just call getSCEV on both operands
4028 // and call getAddExpr with the result. However if we're looking at a
4029 // bunch of things all added together, this can be quite inefficient,
4030 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4031 // Instead, gather up all the operands and make a single getAddExpr call.
4032 // LLVM IR canonical form means we need only traverse the left operands.
Andrew Trickd25089f2011-11-29 02:16:38 +00004033 //
4034 // Don't apply this instruction's NSW or NUW flags to the new
4035 // expression. The instruction may be guarded by control flow that the
4036 // no-wrap behavior depends on. Non-control-equivalent instructions can be
4037 // mapped to the same SCEV expression, and it would be incorrect to transfer
4038 // NSW/NUW semantics to those operations.
Dan Gohmane5fb1032010-08-16 16:03:49 +00004039 SmallVector<const SCEV *, 4> AddOps;
4040 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman47308d52010-08-31 22:53:17 +00004041 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
4042 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
4043 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
4044 break;
Dan Gohmane5fb1032010-08-16 16:03:49 +00004045 U = cast<Operator>(Op);
Dan Gohman47308d52010-08-31 22:53:17 +00004046 const SCEV *Op1 = getSCEV(U->getOperand(1));
4047 if (Opcode == Instruction::Sub)
4048 AddOps.push_back(getNegativeSCEV(Op1));
4049 else
4050 AddOps.push_back(Op1);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004051 }
4052 AddOps.push_back(getSCEV(U->getOperand(0)));
Andrew Trickd25089f2011-11-29 02:16:38 +00004053 return getAddExpr(AddOps);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004054 }
4055 case Instruction::Mul: {
Andrew Trickd25089f2011-11-29 02:16:38 +00004056 // Don't transfer NSW/NUW for the same reason as AddExpr.
Dan Gohmane5fb1032010-08-16 16:03:49 +00004057 SmallVector<const SCEV *, 4> MulOps;
4058 MulOps.push_back(getSCEV(U->getOperand(1)));
4059 for (Value *Op = U->getOperand(0);
Andrew Trick2a3b7162011-03-09 17:23:39 +00004060 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmane5fb1032010-08-16 16:03:49 +00004061 Op = U->getOperand(0)) {
4062 U = cast<Operator>(Op);
4063 MulOps.push_back(getSCEV(U->getOperand(1)));
4064 }
4065 MulOps.push_back(getSCEV(U->getOperand(0)));
4066 return getMulExpr(MulOps);
4067 }
Dan Gohman05e89732008-06-22 19:56:46 +00004068 case Instruction::UDiv:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004069 return getUDivExpr(getSCEV(U->getOperand(0)),
4070 getSCEV(U->getOperand(1)));
Dan Gohman05e89732008-06-22 19:56:46 +00004071 case Instruction::Sub:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004072 return getMinusSCEV(getSCEV(U->getOperand(0)),
4073 getSCEV(U->getOperand(1)));
Dan Gohman0ec05372009-04-21 02:26:00 +00004074 case Instruction::And:
4075 // For an expression like x&255 that merely masks off the high bits,
4076 // use zext(trunc(x)) as the SCEV expression.
4077 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmandf199482009-04-25 17:05:40 +00004078 if (CI->isNullValue())
4079 return getSCEV(U->getOperand(1));
Dan Gohman05c1d372009-04-27 01:41:10 +00004080 if (CI->isAllOnesValue())
4081 return getSCEV(U->getOperand(0));
Dan Gohman0ec05372009-04-21 02:26:00 +00004082 const APInt &A = CI->getValue();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004083
4084 // Instcombine's ShrinkDemandedConstant may strip bits out of
4085 // constants, obscuring what would otherwise be a low-bits mask.
Jay Foada0653a32014-05-14 21:14:37 +00004086 // Use computeKnownBits to compute what ShrinkDemandedConstant
Dan Gohman1ee696d2009-06-16 19:52:01 +00004087 // knew about to reconstruct a low-bits mask value.
4088 unsigned LZ = A.countLeadingZeros();
Nick Lewycky31eaca52014-01-27 10:04:03 +00004089 unsigned TZ = A.countTrailingZeros();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004090 unsigned BitWidth = A.getBitWidth();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004091 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00004092 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL,
4093 0, AT, nullptr, DT);
Dan Gohman1ee696d2009-06-16 19:52:01 +00004094
Nick Lewycky31eaca52014-01-27 10:04:03 +00004095 APInt EffectiveMask =
4096 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4097 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4098 const SCEV *MulCount = getConstant(
4099 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4100 return getMulExpr(
4101 getZeroExtendExpr(
4102 getTruncateExpr(
4103 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4104 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4105 U->getType()),
4106 MulCount);
4107 }
Dan Gohman0ec05372009-04-21 02:26:00 +00004108 }
4109 break;
Dan Gohman1ee696d2009-06-16 19:52:01 +00004110
Dan Gohman05e89732008-06-22 19:56:46 +00004111 case Instruction::Or:
4112 // If the RHS of the Or is a constant, we may have something like:
4113 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4114 // optimizations will transparently handle this case.
4115 //
4116 // In order for this transformation to be safe, the LHS must be of the
4117 // form X*(2^n) and the Or constant must be less than 2^n.
4118 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00004119 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman05e89732008-06-22 19:56:46 +00004120 const APInt &CIVal = CI->getValue();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004121 if (GetMinTrailingZeros(LHS) >=
Dan Gohman36bad002009-09-17 18:05:20 +00004122 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4123 // Build a plain add SCEV.
4124 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4125 // If the LHS of the add was an addrec and it has no-wrap flags,
4126 // transfer the no-wrap flags, since an or won't introduce a wrap.
4127 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4128 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick8b55b732011-03-14 16:50:06 +00004129 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4130 OldAR->getNoWrapFlags());
Dan Gohman36bad002009-09-17 18:05:20 +00004131 }
4132 return S;
4133 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004134 }
Dan Gohman05e89732008-06-22 19:56:46 +00004135 break;
4136 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00004137 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004138 // If the RHS of the xor is a signbit, then this is just an add.
4139 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00004140 if (CI->getValue().isSignBit())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004141 return getAddExpr(getSCEV(U->getOperand(0)),
4142 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004143
4144 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmand277a1e2009-05-18 16:17:44 +00004145 if (CI->isAllOnesValue())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004146 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6350296e2009-05-18 16:29:04 +00004147
4148 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4149 // This is a variant of the check for xor with -1, and it handles
4150 // the case where instcombine has trimmed non-demanded bits out
4151 // of an xor with -1.
4152 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4153 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4154 if (BO->getOpcode() == Instruction::And &&
4155 LCI->getValue() == CI->getValue())
4156 if (const SCEVZeroExtendExpr *Z =
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004157 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattner229907c2011-07-18 04:54:35 +00004158 Type *UTy = U->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00004159 const SCEV *Z0 = Z->getOperand();
Chris Lattner229907c2011-07-18 04:54:35 +00004160 Type *Z0Ty = Z0->getType();
Dan Gohmaneddf7712009-06-18 00:00:20 +00004161 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4162
Dan Gohman8b0a4192010-03-01 17:49:51 +00004163 // If C is a low-bits mask, the zero extend is serving to
Dan Gohmaneddf7712009-06-18 00:00:20 +00004164 // mask off the high bits. Complement the operand and
4165 // re-apply the zext.
4166 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4167 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4168
4169 // If C is a single bit, it may be in the sign-bit position
4170 // before the zero-extend. In this case, represent the xor
4171 // using an add, which is equivalent, and re-apply the zext.
Jay Foad583abbc2010-12-07 08:25:19 +00004172 APInt Trunc = CI->getValue().trunc(Z0TySize);
4173 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohmaneddf7712009-06-18 00:00:20 +00004174 Trunc.isSignBit())
4175 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4176 UTy);
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004177 }
Dan Gohman05e89732008-06-22 19:56:46 +00004178 }
4179 break;
4180
4181 case Instruction::Shl:
4182 // Turn shift left of a constant amount into a multiply.
4183 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004184 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004185
4186 // If the shift count is not less than the bitwidth, the result of
4187 // the shift is undefined. Don't try to analyze it, because the
4188 // resolution chosen here may differ from the resolution chosen in
4189 // other parts of the compiler.
4190 if (SA->getValue().uge(BitWidth))
4191 break;
4192
Owen Andersonedb4a702009-07-24 23:12:02 +00004193 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004194 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004195 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman05e89732008-06-22 19:56:46 +00004196 }
4197 break;
4198
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004199 case Instruction::LShr:
Nick Lewycky52348302009-01-13 09:18:58 +00004200 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004201 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004202 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004203
4204 // If the shift count is not less than the bitwidth, the result of
4205 // the shift is undefined. Don't try to analyze it, because the
4206 // resolution chosen here may differ from the resolution chosen in
4207 // other parts of the compiler.
4208 if (SA->getValue().uge(BitWidth))
4209 break;
4210
Owen Andersonedb4a702009-07-24 23:12:02 +00004211 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004212 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004213 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004214 }
4215 break;
4216
Dan Gohman0ec05372009-04-21 02:26:00 +00004217 case Instruction::AShr:
4218 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4219 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanacd700a2010-04-22 01:35:11 +00004220 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman0ec05372009-04-21 02:26:00 +00004221 if (L->getOpcode() == Instruction::Shl &&
4222 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00004223 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4224
4225 // If the shift count is not less than the bitwidth, the result of
4226 // the shift is undefined. Don't try to analyze it, because the
4227 // resolution chosen here may differ from the resolution chosen in
4228 // other parts of the compiler.
4229 if (CI->getValue().uge(BitWidth))
4230 break;
4231
Dan Gohmandf199482009-04-25 17:05:40 +00004232 uint64_t Amt = BitWidth - CI->getZExtValue();
4233 if (Amt == BitWidth)
4234 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman0ec05372009-04-21 02:26:00 +00004235 return
Dan Gohmanc8e23622009-04-21 23:15:49 +00004236 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanacd700a2010-04-22 01:35:11 +00004237 IntegerType::get(getContext(),
4238 Amt)),
4239 U->getType());
Dan Gohman0ec05372009-04-21 02:26:00 +00004240 }
4241 break;
4242
Dan Gohman05e89732008-06-22 19:56:46 +00004243 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004244 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004245
4246 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004247 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004248
4249 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004250 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004251
4252 case Instruction::BitCast:
4253 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004254 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00004255 return getSCEV(U->getOperand(0));
4256 break;
4257
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004258 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4259 // lead to pointer expressions which cannot safely be expanded to GEPs,
4260 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4261 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00004262
Dan Gohmanee750d12009-05-08 20:26:55 +00004263 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004264 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00004265
Dan Gohman05e89732008-06-22 19:56:46 +00004266 case Instruction::PHI:
4267 return createNodeForPHI(cast<PHINode>(U));
4268
4269 case Instruction::Select:
4270 // This could be a smax or umax that was lowered earlier.
4271 // Try to recover it.
4272 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
4273 Value *LHS = ICI->getOperand(0);
4274 Value *RHS = ICI->getOperand(1);
4275 switch (ICI->getPredicate()) {
4276 case ICmpInst::ICMP_SLT:
4277 case ICmpInst::ICMP_SLE:
4278 std::swap(LHS, RHS);
4279 // fall through
4280 case ICmpInst::ICMP_SGT:
4281 case ICmpInst::ICMP_SGE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004282 // a >s b ? a+x : b+x -> smax(a, b)+x
4283 // a >s b ? b+x : a+x -> smin(a, b)+x
4284 if (LHS->getType() == U->getType()) {
4285 const SCEV *LS = getSCEV(LHS);
4286 const SCEV *RS = getSCEV(RHS);
4287 const SCEV *LA = getSCEV(U->getOperand(1));
4288 const SCEV *RA = getSCEV(U->getOperand(2));
4289 const SCEV *LDiff = getMinusSCEV(LA, LS);
4290 const SCEV *RDiff = getMinusSCEV(RA, RS);
4291 if (LDiff == RDiff)
4292 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4293 LDiff = getMinusSCEV(LA, RS);
4294 RDiff = getMinusSCEV(RA, LS);
4295 if (LDiff == RDiff)
4296 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4297 }
Dan Gohman05e89732008-06-22 19:56:46 +00004298 break;
4299 case ICmpInst::ICMP_ULT:
4300 case ICmpInst::ICMP_ULE:
4301 std::swap(LHS, RHS);
4302 // fall through
4303 case ICmpInst::ICMP_UGT:
4304 case ICmpInst::ICMP_UGE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004305 // a >u b ? a+x : b+x -> umax(a, b)+x
4306 // a >u b ? b+x : a+x -> umin(a, b)+x
4307 if (LHS->getType() == U->getType()) {
4308 const SCEV *LS = getSCEV(LHS);
4309 const SCEV *RS = getSCEV(RHS);
4310 const SCEV *LA = getSCEV(U->getOperand(1));
4311 const SCEV *RA = getSCEV(U->getOperand(2));
4312 const SCEV *LDiff = getMinusSCEV(LA, LS);
4313 const SCEV *RDiff = getMinusSCEV(RA, RS);
4314 if (LDiff == RDiff)
4315 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4316 LDiff = getMinusSCEV(LA, RS);
4317 RDiff = getMinusSCEV(RA, LS);
4318 if (LDiff == RDiff)
4319 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4320 }
Dan Gohman05e89732008-06-22 19:56:46 +00004321 break;
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004322 case ICmpInst::ICMP_NE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004323 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4324 if (LHS->getType() == U->getType() &&
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004325 isa<ConstantInt>(RHS) &&
Dan Gohmanf33bac32010-04-24 03:09:42 +00004326 cast<ConstantInt>(RHS)->isZero()) {
4327 const SCEV *One = getConstant(LHS->getType(), 1);
4328 const SCEV *LS = getSCEV(LHS);
4329 const SCEV *LA = getSCEV(U->getOperand(1));
4330 const SCEV *RA = getSCEV(U->getOperand(2));
4331 const SCEV *LDiff = getMinusSCEV(LA, LS);
4332 const SCEV *RDiff = getMinusSCEV(RA, One);
4333 if (LDiff == RDiff)
Dan Gohmancf32f2b2010-08-13 20:17:14 +00004334 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohmanf33bac32010-04-24 03:09:42 +00004335 }
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004336 break;
4337 case ICmpInst::ICMP_EQ:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004338 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4339 if (LHS->getType() == U->getType() &&
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004340 isa<ConstantInt>(RHS) &&
Dan Gohmanf33bac32010-04-24 03:09:42 +00004341 cast<ConstantInt>(RHS)->isZero()) {
4342 const SCEV *One = getConstant(LHS->getType(), 1);
4343 const SCEV *LS = getSCEV(LHS);
4344 const SCEV *LA = getSCEV(U->getOperand(1));
4345 const SCEV *RA = getSCEV(U->getOperand(2));
4346 const SCEV *LDiff = getMinusSCEV(LA, One);
4347 const SCEV *RDiff = getMinusSCEV(RA, LS);
4348 if (LDiff == RDiff)
Dan Gohmancf32f2b2010-08-13 20:17:14 +00004349 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohmanf33bac32010-04-24 03:09:42 +00004350 }
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004351 break;
Dan Gohman05e89732008-06-22 19:56:46 +00004352 default:
4353 break;
4354 }
4355 }
4356
4357 default: // We cannot analyze this expression.
4358 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00004359 }
4360
Dan Gohmanc8e23622009-04-21 23:15:49 +00004361 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00004362}
4363
4364
4365
4366//===----------------------------------------------------------------------===//
4367// Iteration Count Computation Code
4368//
4369
Chandler Carruth6666c272014-10-11 00:12:11 +00004370unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4371 if (BasicBlock *ExitingBB = L->getExitingBlock())
4372 return getSmallConstantTripCount(L, ExitingBB);
4373
4374 // No trip count information for multiple exits.
4375 return 0;
4376}
4377
Andrew Trick2b6860f2011-08-11 23:36:16 +00004378/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00004379/// normal unsigned value. Returns 0 if the trip count is unknown or not
4380/// constant. Will also return 0 if the maximum trip count is very large (>=
4381/// 2^32).
4382///
4383/// This "trip count" assumes that control exits via ExitingBlock. More
4384/// precisely, it is the number of times that control may reach ExitingBlock
4385/// before taking the branch. For loops with multiple exits, it may not be the
4386/// number times that the loop header executes because the loop may exit
4387/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004388unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4389 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004390 assert(ExitingBlock && "Must pass a non-null exiting block!");
4391 assert(L->isLoopExiting(ExitingBlock) &&
4392 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00004393 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004394 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004395 if (!ExitCount)
4396 return 0;
4397
4398 ConstantInt *ExitConst = ExitCount->getValue();
4399
4400 // Guard against huge trip counts.
4401 if (ExitConst->getValue().getActiveBits() > 32)
4402 return 0;
4403
4404 // In case of integer overflow, this returns 0, which is correct.
4405 return ((unsigned)ExitConst->getZExtValue()) + 1;
4406}
4407
Chandler Carruth6666c272014-10-11 00:12:11 +00004408unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4409 if (BasicBlock *ExitingBB = L->getExitingBlock())
4410 return getSmallConstantTripMultiple(L, ExitingBB);
4411
4412 // No trip multiple information for multiple exits.
4413 return 0;
4414}
4415
Andrew Trick2b6860f2011-08-11 23:36:16 +00004416/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4417/// trip count of this loop as a normal unsigned value, if possible. This
4418/// means that the actual trip count is always a multiple of the returned
4419/// value (don't forget the trip count could very well be zero as well!).
4420///
4421/// Returns 1 if the trip count is unknown or not guaranteed to be the
4422/// multiple of a constant (which is also the case if the trip count is simply
4423/// constant, use getSmallConstantTripCount for that case), Will also return 1
4424/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00004425///
4426/// As explained in the comments for getSmallConstantTripCount, this assumes
4427/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004428unsigned
4429ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4430 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004431 assert(ExitingBlock && "Must pass a non-null exiting block!");
4432 assert(L->isLoopExiting(ExitingBlock) &&
4433 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004434 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00004435 if (ExitCount == getCouldNotCompute())
4436 return 1;
4437
4438 // Get the trip count from the BE count by adding 1.
4439 const SCEV *TCMul = getAddExpr(ExitCount,
4440 getConstant(ExitCount->getType(), 1));
4441 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4442 // to factor simple cases.
4443 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4444 TCMul = Mul->getOperand(0);
4445
4446 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4447 if (!MulC)
4448 return 1;
4449
4450 ConstantInt *Result = MulC->getValue();
4451
Hal Finkel30bd9342012-10-24 19:46:44 +00004452 // Guard against huge trip counts (this requires checking
4453 // for zero to handle the case where the trip count == -1 and the
4454 // addition wraps).
4455 if (!Result || Result->getValue().getActiveBits() > 32 ||
4456 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00004457 return 1;
4458
4459 return (unsigned)Result->getZExtValue();
4460}
4461
Andrew Trick3ca3f982011-07-26 17:19:55 +00004462// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00004463// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00004464// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00004465const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4466 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004467}
4468
Dan Gohman0bddac12009-02-24 18:55:53 +00004469/// getBackedgeTakenCount - If the specified loop has a predictable
4470/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4471/// object. The backedge-taken count is the number of times the loop header
4472/// will be branched to from within the loop. This is one less than the
4473/// trip count of the loop, since it doesn't count the first iteration,
4474/// when the header is branched to from outside the loop.
4475///
4476/// Note that it is not valid to call this method on a loop without a
4477/// loop-invariant backedge-taken count (see
4478/// hasLoopInvariantBackedgeTakenCount).
4479///
Dan Gohmanaf752342009-07-07 17:06:11 +00004480const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004481 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004482}
4483
4484/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4485/// return the least SCEV value that is known never to be less than the
4486/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00004487const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004488 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004489}
4490
Dan Gohmandc191042009-07-08 19:23:34 +00004491/// PushLoopPHIs - Push PHI nodes in the header of the given loop
4492/// onto the given Worklist.
4493static void
4494PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4495 BasicBlock *Header = L->getHeader();
4496
4497 // Push all Loop-header PHIs onto the Worklist stack.
4498 for (BasicBlock::iterator I = Header->begin();
4499 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4500 Worklist.push_back(PN);
4501}
4502
Dan Gohman2b8da352009-04-30 20:47:05 +00004503const ScalarEvolution::BackedgeTakenInfo &
4504ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004505 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00004506 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00004507 // update the value. The temporary CouldNotCompute value tells SCEV
4508 // code elsewhere that it shouldn't attempt to request a new
4509 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00004510 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick3ca3f982011-07-26 17:19:55 +00004511 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004512 if (!Pair.second)
4513 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00004514
Andrew Trick3ca3f982011-07-26 17:19:55 +00004515 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4516 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4517 // must be cleared in this scope.
4518 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4519
4520 if (Result.getExact(this) != getCouldNotCompute()) {
4521 assert(isLoopInvariant(Result.getExact(this), L) &&
4522 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00004523 "Computed backedge-taken count isn't loop invariant for loop!");
4524 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004525 }
4526 else if (Result.getMax(this) == getCouldNotCompute() &&
4527 isa<PHINode>(L->getHeader()->begin())) {
4528 // Only count loops that have phi nodes as not being computable.
4529 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00004530 }
Dan Gohman2b8da352009-04-30 20:47:05 +00004531
Chris Lattnera337f5e2011-01-09 02:16:18 +00004532 // Now that we know more about the trip count for this loop, forget any
4533 // existing SCEV values for PHI nodes in this loop since they are only
4534 // conservative estimates made without the benefit of trip count
4535 // information. This is similar to the code in forgetLoop, except that
4536 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004537 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00004538 SmallVector<Instruction *, 16> Worklist;
4539 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004540
Chris Lattnera337f5e2011-01-09 02:16:18 +00004541 SmallPtrSet<Instruction *, 8> Visited;
4542 while (!Worklist.empty()) {
4543 Instruction *I = Worklist.pop_back_val();
4544 if (!Visited.insert(I)) continue;
Dan Gohmandc191042009-07-08 19:23:34 +00004545
Chris Lattnera337f5e2011-01-09 02:16:18 +00004546 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004547 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004548 if (It != ValueExprMap.end()) {
4549 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00004550
Chris Lattnera337f5e2011-01-09 02:16:18 +00004551 // SCEVUnknown for a PHI either means that it has an unrecognized
4552 // structure, or it's a PHI that's in the progress of being computed
4553 // by createNodeForPHI. In the former case, additional loop trip
4554 // count information isn't going to change anything. In the later
4555 // case, createNodeForPHI will perform the necessary updates on its
4556 // own when it gets to that point.
4557 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4558 forgetMemoizedResults(Old);
4559 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004560 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004561 if (PHINode *PN = dyn_cast<PHINode>(I))
4562 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00004563 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004564
4565 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004566 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004567 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00004568
4569 // Re-lookup the insert position, since the call to
4570 // ComputeBackedgeTakenCount above could result in a
4571 // recusive call to getBackedgeTakenInfo (on a different
4572 // loop), which would invalidate the iterator computed
4573 // earlier.
4574 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00004575}
4576
Dan Gohman880c92a2009-10-31 15:04:55 +00004577/// forgetLoop - This method should be called by the client when it has
4578/// changed a loop in a way that may effect ScalarEvolution's ability to
4579/// compute a trip count, or if the loop is deleted.
4580void ScalarEvolution::forgetLoop(const Loop *L) {
4581 // Drop any stored trip count value.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004582 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4583 BackedgeTakenCounts.find(L);
4584 if (BTCPos != BackedgeTakenCounts.end()) {
4585 BTCPos->second.clear();
4586 BackedgeTakenCounts.erase(BTCPos);
4587 }
Dan Gohmanf1505722009-05-02 17:43:35 +00004588
Dan Gohman880c92a2009-10-31 15:04:55 +00004589 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00004590 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00004591 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004592
Dan Gohmandc191042009-07-08 19:23:34 +00004593 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00004594 while (!Worklist.empty()) {
4595 Instruction *I = Worklist.pop_back_val();
Dan Gohmandc191042009-07-08 19:23:34 +00004596 if (!Visited.insert(I)) continue;
4597
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004598 ValueExprMapType::iterator It =
4599 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004600 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00004601 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004602 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004603 if (PHINode *PN = dyn_cast<PHINode>(I))
4604 ConstantEvolutionLoopExitValue.erase(PN);
4605 }
4606
4607 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004608 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00004609
4610 // Forget all contained loops too, to avoid dangling entries in the
4611 // ValuesAtScopes map.
4612 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4613 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00004614}
4615
Eric Christopheref6d5932010-07-29 01:25:38 +00004616/// forgetValue - This method should be called by the client when it has
4617/// changed a value in a way that may effect its value, or which may
4618/// disconnect it from a def-use chain linking it to a loop.
4619void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004620 Instruction *I = dyn_cast<Instruction>(V);
4621 if (!I) return;
4622
4623 // Drop information about expressions based on loop-header PHIs.
4624 SmallVector<Instruction *, 16> Worklist;
4625 Worklist.push_back(I);
4626
4627 SmallPtrSet<Instruction *, 8> Visited;
4628 while (!Worklist.empty()) {
4629 I = Worklist.pop_back_val();
4630 if (!Visited.insert(I)) continue;
4631
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004632 ValueExprMapType::iterator It =
4633 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004634 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00004635 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004636 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004637 if (PHINode *PN = dyn_cast<PHINode>(I))
4638 ConstantEvolutionLoopExitValue.erase(PN);
4639 }
4640
4641 PushDefUseChildren(I, Worklist);
4642 }
4643}
4644
Andrew Trick3ca3f982011-07-26 17:19:55 +00004645/// getExact - Get the exact loop backedge taken count considering all loop
Andrew Trick90c7a102011-11-16 00:52:40 +00004646/// exits. A computable result can only be return for loops with a single exit.
4647/// Returning the minimum taken count among all exits is incorrect because one
4648/// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4649/// the limit of each loop test is never skipped. This is a valid assumption as
4650/// long as the loop exits via that test. For precise results, it is the
4651/// caller's responsibility to specify the relevant loop exit using
4652/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00004653const SCEV *
4654ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4655 // If any exits were not computable, the loop is not computable.
4656 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4657
Andrew Trick90c7a102011-11-16 00:52:40 +00004658 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00004659 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00004660 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4661
Craig Topper9f008862014-04-15 04:59:12 +00004662 const SCEV *BECount = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004663 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004664 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004665
4666 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4667
4668 if (!BECount)
4669 BECount = ENT->ExactNotTaken;
Andrew Trick90c7a102011-11-16 00:52:40 +00004670 else if (BECount != ENT->ExactNotTaken)
4671 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00004672 }
Andrew Trickbbb226a2011-09-02 21:20:46 +00004673 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004674 return BECount;
4675}
4676
4677/// getExact - Get the exact not taken count for this loop exit.
4678const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00004679ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00004680 ScalarEvolution *SE) const {
4681 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004682 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004683
Andrew Trick77c55422011-08-02 04:23:35 +00004684 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick3ca3f982011-07-26 17:19:55 +00004685 return ENT->ExactNotTaken;
4686 }
4687 return SE->getCouldNotCompute();
4688}
4689
4690/// getMax - Get the max backedge taken count for the loop.
4691const SCEV *
4692ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4693 return Max ? Max : SE->getCouldNotCompute();
4694}
4695
Andrew Trick9093e152013-03-26 03:14:53 +00004696bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4697 ScalarEvolution *SE) const {
4698 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4699 return true;
4700
4701 if (!ExitNotTaken.ExitingBlock)
4702 return false;
4703
4704 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004705 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick9093e152013-03-26 03:14:53 +00004706
4707 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4708 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4709 return true;
4710 }
4711 }
4712 return false;
4713}
4714
Andrew Trick3ca3f982011-07-26 17:19:55 +00004715/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4716/// computable exit into a persistent ExitNotTakenInfo array.
4717ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4718 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4719 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4720
4721 if (!Complete)
4722 ExitNotTaken.setIncomplete();
4723
4724 unsigned NumExits = ExitCounts.size();
4725 if (NumExits == 0) return;
4726
Andrew Trick77c55422011-08-02 04:23:35 +00004727 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004728 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4729 if (NumExits == 1) return;
4730
4731 // Handle the rare case of multiple computable exits.
4732 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4733
4734 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4735 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4736 PrevENT->setNextExit(ENT);
Andrew Trick77c55422011-08-02 04:23:35 +00004737 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004738 ENT->ExactNotTaken = ExitCounts[i].second;
4739 }
4740}
4741
4742/// clear - Invalidate this result and free the ExitNotTakenInfo array.
4743void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00004744 ExitNotTaken.ExitingBlock = nullptr;
4745 ExitNotTaken.ExactNotTaken = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004746 delete[] ExitNotTaken.getNextExit();
4747}
4748
Dan Gohman0bddac12009-02-24 18:55:53 +00004749/// ComputeBackedgeTakenCount - Compute the number of times the backedge
4750/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00004751ScalarEvolution::BackedgeTakenInfo
4752ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00004753 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00004754 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00004755
Andrew Trick839e30b2014-05-23 19:47:13 +00004756 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004757 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00004758 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00004759 const SCEV *MustExitMaxBECount = nullptr;
4760 const SCEV *MayExitMaxBECount = nullptr;
4761
4762 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4763 // and compute maxBECount.
Dan Gohman96212b62009-06-22 00:31:57 +00004764 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00004765 BasicBlock *ExitBB = ExitingBlocks[i];
4766 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4767
4768 // 1. For each exit that can be computed, add an entry to ExitCounts.
4769 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004770 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00004771 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00004772 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004773 CouldComputeBECount = false;
4774 else
Andrew Trick839e30b2014-05-23 19:47:13 +00004775 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
Andrew Trick3ca3f982011-07-26 17:19:55 +00004776
Andrew Trick839e30b2014-05-23 19:47:13 +00004777 // 2. Derive the loop's MaxBECount from each exit's max number of
4778 // non-exiting iterations. Partition the loop exits into two kinds:
4779 // LoopMustExits and LoopMayExits.
4780 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004781 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
4782 // is a LoopMayExit. If any computable LoopMustExit is found, then
4783 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
4784 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
4785 // considered greater than any computable EL.Max.
4786 if (EL.Max != getCouldNotCompute() && Latch &&
Andrew Trick839e30b2014-05-23 19:47:13 +00004787 DT->dominates(ExitBB, Latch)) {
4788 if (!MustExitMaxBECount)
4789 MustExitMaxBECount = EL.Max;
4790 else {
4791 MustExitMaxBECount =
4792 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00004793 }
Andrew Trick839e30b2014-05-23 19:47:13 +00004794 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4795 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4796 MayExitMaxBECount = EL.Max;
4797 else {
4798 MayExitMaxBECount =
4799 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4800 }
Andrew Trick90c7a102011-11-16 00:52:40 +00004801 }
Dan Gohman96212b62009-06-22 00:31:57 +00004802 }
Andrew Trick839e30b2014-05-23 19:47:13 +00004803 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4804 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00004805 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004806}
4807
Andrew Trick3ca3f982011-07-26 17:19:55 +00004808/// ComputeExitLimit - Compute the number of times the backedge of the specified
4809/// loop will execute if it exits via the specified block.
4810ScalarEvolution::ExitLimit
4811ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohman96212b62009-06-22 00:31:57 +00004812
4813 // Okay, we've chosen an exiting block. See what condition causes us to
Benjamin Kramer5a188542014-02-11 15:44:32 +00004814 // exit at this block and remember the exit block and whether all other targets
4815 // lead to the loop header.
4816 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00004817 BasicBlock *Exit = nullptr;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004818 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4819 SI != SE; ++SI)
4820 if (!L->contains(*SI)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00004821 if (Exit) // Multiple exit successors.
4822 return getCouldNotCompute();
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004823 Exit = *SI;
4824 } else if (*SI != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00004825 MustExecuteLoopHeader = false;
4826 }
Dan Gohmance973df2009-06-24 04:48:43 +00004827
Chris Lattner18954852007-01-07 02:24:26 +00004828 // At this point, we know we have a conditional branch that determines whether
4829 // the loop is exited. However, we don't know if the branch is executed each
4830 // time through the loop. If not, then the execution count of the branch will
4831 // not be equal to the trip count of the loop.
4832 //
4833 // Currently we check for this by checking to see if the Exit branch goes to
4834 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00004835 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00004836 // loop header. This is common for un-rotated loops.
4837 //
4838 // If both of those tests fail, walk up the unique predecessor chain to the
4839 // header, stopping if there is an edge that doesn't exit the loop. If the
4840 // header is reached, the execution count of the branch will be equal to the
4841 // trip count of the loop.
4842 //
4843 // More extensive analysis could be done to handle more cases here.
4844 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00004845 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00004846 // The simple checks failed, try climbing the unique predecessor chain
4847 // up to the header.
4848 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00004849 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00004850 BasicBlock *Pred = BB->getUniquePredecessor();
4851 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004852 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004853 TerminatorInst *PredTerm = Pred->getTerminator();
4854 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4855 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4856 if (PredSucc == BB)
4857 continue;
4858 // If the predecessor has a successor that isn't BB and isn't
4859 // outside the loop, assume the worst.
4860 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004861 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004862 }
4863 if (Pred == L->getHeader()) {
4864 Ok = true;
4865 break;
4866 }
4867 BB = Pred;
4868 }
4869 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004870 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004871 }
4872
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004873 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004874 TerminatorInst *Term = ExitingBlock->getTerminator();
4875 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4876 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4877 // Proceed to the next level to examine the exit condition expression.
4878 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4879 BI->getSuccessor(1),
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004880 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004881 }
4882
4883 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4884 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004885 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004886
4887 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004888}
4889
Andrew Trick3ca3f982011-07-26 17:19:55 +00004890/// ComputeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00004891/// backedge of the specified loop will execute if its exit condition
4892/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00004893///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004894/// @param ControlsExit is true if ExitCond directly controls the exit
4895/// branch. In this case, we can assume that the loop exits only if the
4896/// condition is true and can infer that failing to meet the condition prior to
4897/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004898ScalarEvolution::ExitLimit
4899ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4900 Value *ExitCond,
4901 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00004902 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004903 bool ControlsExit) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00004904 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00004905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4906 if (BO->getOpcode() == Instruction::And) {
4907 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00004908 bool EitherMayExit = L->contains(TBB);
4909 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004910 ControlsExit && !EitherMayExit);
Andrew Trick5b245a12013-05-31 06:43:25 +00004911 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004912 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00004913 const SCEV *BECount = getCouldNotCompute();
4914 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00004915 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00004916 // Both conditions must be true for the loop to continue executing.
4917 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004918 if (EL0.Exact == getCouldNotCompute() ||
4919 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004920 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00004921 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004922 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4923 if (EL0.Max == getCouldNotCompute())
4924 MaxBECount = EL1.Max;
4925 else if (EL1.Max == getCouldNotCompute())
4926 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00004927 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004928 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00004929 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00004930 // Both conditions must be true at the same time for the loop to exit.
4931 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00004932 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004933 if (EL0.Max == EL1.Max)
4934 MaxBECount = EL0.Max;
4935 if (EL0.Exact == EL1.Exact)
4936 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00004937 }
4938
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004939 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004940 }
4941 if (BO->getOpcode() == Instruction::Or) {
4942 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00004943 bool EitherMayExit = L->contains(FBB);
4944 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004945 ControlsExit && !EitherMayExit);
Andrew Trick5b245a12013-05-31 06:43:25 +00004946 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004947 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00004948 const SCEV *BECount = getCouldNotCompute();
4949 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00004950 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00004951 // Both conditions must be false for the loop to continue executing.
4952 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004953 if (EL0.Exact == getCouldNotCompute() ||
4954 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004955 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00004956 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004957 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4958 if (EL0.Max == getCouldNotCompute())
4959 MaxBECount = EL1.Max;
4960 else if (EL1.Max == getCouldNotCompute())
4961 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00004962 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004963 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00004964 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00004965 // Both conditions must be false at the same time for the loop to exit.
4966 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00004967 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004968 if (EL0.Max == EL1.Max)
4969 MaxBECount = EL0.Max;
4970 if (EL0.Exact == EL1.Exact)
4971 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00004972 }
4973
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004974 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004975 }
4976 }
4977
4978 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00004979 // Proceed to the next level to examine the icmp.
Dan Gohman96212b62009-06-22 00:31:57 +00004980 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004981 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
Reid Spencer266e42b2006-12-23 06:05:41 +00004982
Dan Gohman6b1e2a82010-02-19 18:12:07 +00004983 // Check for a constant condition. These are normally stripped out by
4984 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4985 // preserve the CFG and is temporarily leaving constant conditions
4986 // in place.
4987 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4988 if (L->contains(FBB) == !CI->getZExtValue())
4989 // The backedge is always taken.
4990 return getCouldNotCompute();
4991 else
4992 // The backedge is never taken.
Dan Gohman1d2ded72010-05-03 22:09:21 +00004993 return getConstant(CI->getType(), 0);
Dan Gohman6b1e2a82010-02-19 18:12:07 +00004994 }
4995
Eli Friedmanebf98b02009-05-09 12:32:42 +00004996 // If it's not an integer or pointer comparison then compute it the hard way.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004997 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00004998}
4999
Andrew Trick3ca3f982011-07-26 17:19:55 +00005000/// ComputeExitLimitFromICmp - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005001/// backedge of the specified loop will execute if its exit condition
5002/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005003ScalarEvolution::ExitLimit
5004ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
5005 ICmpInst *ExitCond,
5006 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005007 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005008 bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005009
Reid Spencer266e42b2006-12-23 06:05:41 +00005010 // If the condition was exit on true, convert the condition to exit on false
5011 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005012 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005013 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005014 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005015 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005016
5017 // Handle common loops like: for (X = "string"; *X; ++X)
5018 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5019 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005020 ExitLimit ItCnt =
5021 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005022 if (ItCnt.hasAnyInfo())
5023 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005024 }
5025
Dan Gohmanaf752342009-07-07 17:06:11 +00005026 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5027 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005028
5029 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005030 LHS = getSCEVAtScope(LHS, L);
5031 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005032
Dan Gohmance973df2009-06-24 04:48:43 +00005033 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005034 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005035 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005036 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005037 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005038 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005039 }
5040
Dan Gohman81585c12010-05-03 16:35:17 +00005041 // Simplify the operands before analyzing them.
5042 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5043
Chris Lattnerd934c702004-04-02 20:23:17 +00005044 // If we have a comparison of a chrec against a constant, try to use value
5045 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005046 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5047 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005048 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005049 // Form the constant range.
5050 ConstantRange CompRange(
5051 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005052
Dan Gohmanaf752342009-07-07 17:06:11 +00005053 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005054 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005055 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005056
Chris Lattnerd934c702004-04-02 20:23:17 +00005057 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005058 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005059 // Convert to: while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005060 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005061 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005062 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005063 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005064 case ICmpInst::ICMP_EQ: { // while (X == Y)
5065 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005066 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5067 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005068 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005069 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005070 case ICmpInst::ICMP_SLT:
5071 case ICmpInst::ICMP_ULT: { // while (X < Y)
5072 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005073 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005074 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005075 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005076 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005077 case ICmpInst::ICMP_SGT:
5078 case ICmpInst::ICMP_UGT: { // while (X > Y)
5079 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005080 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005081 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005082 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005083 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005084 default:
Chris Lattner09169212004-04-02 20:26:46 +00005085#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005086 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattnerd934c702004-04-02 20:23:17 +00005087 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greenedf1c4972009-12-23 22:18:14 +00005088 dbgs() << "[unsigned] ";
5089 dbgs() << *LHS << " "
Dan Gohmance973df2009-06-24 04:48:43 +00005090 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencer266e42b2006-12-23 06:05:41 +00005091 << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00005092#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00005093 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005094 }
Andrew Trick3ca3f982011-07-26 17:19:55 +00005095 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005096}
5097
Benjamin Kramer5a188542014-02-11 15:44:32 +00005098ScalarEvolution::ExitLimit
5099ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
5100 SwitchInst *Switch,
5101 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005102 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005103 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5104
5105 // Give up if the exit is the default dest of a switch.
5106 if (Switch->getDefaultDest() == ExitingBlock)
5107 return getCouldNotCompute();
5108
5109 assert(L->contains(Switch->getDefaultDest()) &&
5110 "Default case must not exit the loop!");
5111 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5112 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5113
5114 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005115 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005116 if (EL.hasAnyInfo())
5117 return EL;
5118
5119 return getCouldNotCompute();
5120}
5121
Chris Lattnerec901cc2004-10-12 01:49:27 +00005122static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00005123EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5124 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005125 const SCEV *InVal = SE.getConstant(C);
5126 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005127 assert(isa<SCEVConstant>(Val) &&
5128 "Evaluation of SCEV at constant didn't fold correctly?");
5129 return cast<SCEVConstant>(Val)->getValue();
5130}
5131
Andrew Trick3ca3f982011-07-26 17:19:55 +00005132/// ComputeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00005133/// 'icmp op load X, cst', try to see if we can compute the backedge
5134/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005135ScalarEvolution::ExitLimit
5136ScalarEvolution::ComputeLoadConstantCompareExitLimit(
5137 LoadInst *LI,
5138 Constant *RHS,
5139 const Loop *L,
5140 ICmpInst::Predicate predicate) {
5141
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005142 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005143
5144 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00005145 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005146 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005147 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005148
5149 // Make sure that it is really a constant global we are gepping, with an
5150 // initializer, and make sure the first IDX is really 0.
5151 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00005152 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005153 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5154 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005155 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005156
5157 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00005158 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00005159 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005160 unsigned VarIdxNum = 0;
5161 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5162 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5163 Indexes.push_back(CI);
5164 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005165 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005166 VarIdx = GEP->getOperand(i);
5167 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00005168 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005169 }
5170
Andrew Trick7004e4b2012-03-26 22:33:59 +00005171 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5172 if (!VarIdx)
5173 return getCouldNotCompute();
5174
Chris Lattnerec901cc2004-10-12 01:49:27 +00005175 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5176 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005177 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00005178 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005179
5180 // We can only recognize very limited forms of loop index expressions, in
5181 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00005182 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00005183 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005184 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5185 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005186 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005187
5188 unsigned MaxSteps = MaxBruteForceIterations;
5189 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005190 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00005191 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00005192 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005193
5194 // Form the GEP offset.
5195 Indexes[VarIdxNum] = Val;
5196
Chris Lattnere166a852012-01-24 05:49:24 +00005197 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5198 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00005199 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005200
5201 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00005202 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00005203 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00005204 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00005205#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005206 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmane20f8242009-04-21 00:47:46 +00005207 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5208 << "***\n";
Chris Lattnerec901cc2004-10-12 01:49:27 +00005209#endif
5210 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00005211 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005212 }
5213 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005214 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005215}
5216
5217
Chris Lattnerdd730472004-04-17 22:58:41 +00005218/// CanConstantFold - Return true if we can constant fold an instruction of the
5219/// specified type, assuming that all operands were constants.
5220static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00005221 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00005222 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5223 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00005224 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00005225
Chris Lattnerdd730472004-04-17 22:58:41 +00005226 if (const CallInst *CI = dyn_cast<CallInst>(I))
5227 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00005228 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00005229 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00005230}
5231
Andrew Trick3a86ba72011-10-05 03:25:31 +00005232/// Determine whether this instruction can constant evolve within this loop
5233/// assuming its operands can all constant evolve.
5234static bool canConstantEvolve(Instruction *I, const Loop *L) {
5235 // An instruction outside of the loop can't be derived from a loop PHI.
5236 if (!L->contains(I)) return false;
5237
5238 if (isa<PHINode>(I)) {
5239 if (L->getHeader() == I->getParent())
5240 return true;
5241 else
5242 // We don't currently keep track of the control flow needed to evaluate
5243 // PHIs, so we cannot handle PHIs inside of loops.
5244 return false;
5245 }
5246
5247 // If we won't be able to constant fold this expression even if the operands
5248 // are constants, bail early.
5249 return CanConstantFold(I);
5250}
5251
5252/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5253/// recursing through each instruction operand until reaching a loop header phi.
5254static PHINode *
5255getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00005256 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005257
5258 // Otherwise, we can evaluate this instruction if all of its operands are
5259 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00005260 PHINode *PHI = nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005261 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5262 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5263
5264 if (isa<Constant>(*OpI)) continue;
5265
5266 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
Craig Topper9f008862014-04-15 04:59:12 +00005267 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005268
5269 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00005270 if (!P)
5271 // If this operand is already visited, reuse the prior result.
5272 // We may have P != PHI if this is the deepest point at which the
5273 // inconsistent paths meet.
5274 P = PHIMap.lookup(OpInst);
5275 if (!P) {
5276 // Recurse and memoize the results, whether a phi is found or not.
5277 // This recursive call invalidates pointers into PHIMap.
5278 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5279 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00005280 }
Craig Topper9f008862014-04-15 04:59:12 +00005281 if (!P)
5282 return nullptr; // Not evolving from PHI
5283 if (PHI && PHI != P)
5284 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00005285 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005286 }
5287 // This is a expression evolving from a constant PHI!
5288 return PHI;
5289}
5290
Chris Lattnerdd730472004-04-17 22:58:41 +00005291/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5292/// in the loop that V is derived from. We allow arbitrary operations along the
5293/// way, but the operands of an operation must either be constants or a value
5294/// derived from a constant PHI. If this expression does not fit with these
5295/// constraints, return null.
5296static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005297 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005298 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005299
Anton Korobeynikov579f0712008-02-20 11:08:44 +00005300 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005301 return PN;
Anton Korobeynikov579f0712008-02-20 11:08:44 +00005302 }
Chris Lattnerdd730472004-04-17 22:58:41 +00005303
Andrew Trick3a86ba72011-10-05 03:25:31 +00005304 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00005305 DenseMap<Instruction *, PHINode *> PHIMap;
5306 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00005307}
5308
5309/// EvaluateExpression - Given an expression that passes the
5310/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5311/// in the loop has the value PHIVal. If we can't fold this expression for some
5312/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005313static Constant *EvaluateExpression(Value *V, const Loop *L,
5314 DenseMap<Instruction *, Constant *> &Vals,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005315 const DataLayout *DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005316 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005317 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00005318 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005319 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005320 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005321
Andrew Trick3a86ba72011-10-05 03:25:31 +00005322 if (Constant *C = Vals.lookup(I)) return C;
5323
Nick Lewyckya6674c72011-10-22 19:58:20 +00005324 // An instruction inside the loop depends on a value outside the loop that we
5325 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00005326 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005327
5328 // An unmapped PHI can be due to a branch or another loop inside this loop,
5329 // or due to this not being the initial iteration through a loop where we
5330 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00005331 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005332
Dan Gohmanf820bd32010-06-22 13:15:46 +00005333 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00005334
5335 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005336 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5337 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00005338 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005339 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005340 continue;
5341 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005342 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00005343 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00005344 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005345 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00005346 }
5347
Nick Lewyckya6674c72011-10-22 19:58:20 +00005348 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00005349 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005350 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005351 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5352 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005353 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005354 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005355 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005356 TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00005357}
5358
5359/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5360/// in the header of its containing loop, we know the loop executes a
5361/// constant number of times, and the PHI node is just a recurrence
5362/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00005363Constant *
5364ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00005365 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00005366 const Loop *L) {
Dan Gohman0daf6872011-05-09 18:44:09 +00005367 DenseMap<PHINode*, Constant*>::const_iterator I =
Chris Lattnerdd730472004-04-17 22:58:41 +00005368 ConstantEvolutionLoopExitValue.find(PN);
5369 if (I != ConstantEvolutionLoopExitValue.end())
5370 return I->second;
5371
Dan Gohman4ce1fb12010-04-08 23:03:40 +00005372 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00005373 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00005374
5375 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5376
Andrew Trick3a86ba72011-10-05 03:25:31 +00005377 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005378 BasicBlock *Header = L->getHeader();
5379 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00005380
Chris Lattnerdd730472004-04-17 22:58:41 +00005381 // Since the loop is canonicalized, the PHI node must have two entries. One
5382 // entry must be a constant (coming in from outside of the loop), and the
5383 // second must be derived from the same PHI.
5384 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Craig Topper9f008862014-04-15 04:59:12 +00005385 PHINode *PHI = nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005386 for (BasicBlock::iterator I = Header->begin();
5387 (PHI = dyn_cast<PHINode>(I)); ++I) {
5388 Constant *StartCST =
5389 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
Craig Topper9f008862014-04-15 04:59:12 +00005390 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005391 CurrentIterVals[PHI] = StartCST;
5392 }
5393 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00005394 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005395
5396 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Chris Lattnerdd730472004-04-17 22:58:41 +00005397
5398 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00005399 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00005400 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00005401
Dan Gohman0bddac12009-02-24 18:55:53 +00005402 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00005403 unsigned IterationNum = 0;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005404 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005405 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00005406 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00005407
Nick Lewyckya6674c72011-10-22 19:58:20 +00005408 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005409 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005410 DenseMap<Instruction *, Constant *> NextIterVals;
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005411 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005412 TLI);
Craig Topper9f008862014-04-15 04:59:12 +00005413 if (!NextPHI)
5414 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00005415 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005416
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005417 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5418
Nick Lewyckya6674c72011-10-22 19:58:20 +00005419 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5420 // cease to be able to evaluate one of them or if they stop evolving,
5421 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005422 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005423 for (DenseMap<Instruction *, Constant *>::const_iterator
5424 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5425 PHINode *PHI = dyn_cast<PHINode>(I->first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00005426 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005427 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5428 }
5429 // We use two distinct loops because EvaluateExpression may invalidate any
5430 // iterators into CurrentIterVals.
5431 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5432 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5433 PHINode *PHI = I->first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005434 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005435 if (!NextPHI) { // Not already computed.
5436 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005437 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005438 }
5439 if (NextPHI != I->second)
5440 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005441 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005442
5443 // If all entries in CurrentIterVals == NextIterVals then we can stop
5444 // iterating, the loop can't continue to change.
5445 if (StoppedEvolving)
5446 return RetVal = CurrentIterVals[PN];
5447
Andrew Trick3a86ba72011-10-05 03:25:31 +00005448 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00005449 }
5450}
5451
Andrew Trick3ca3f982011-07-26 17:19:55 +00005452/// ComputeExitCountExhaustively - If the loop is known to execute a
Chris Lattner4021d1a2004-04-17 18:36:24 +00005453/// constant number of times (the condition evolves only from constants),
5454/// try to evaluate a few iterations of the loop until we get the exit
5455/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005456/// evaluate the trip count of the loop, return getCouldNotCompute().
Nick Lewyckya6674c72011-10-22 19:58:20 +00005457const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5458 Value *Cond,
5459 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005460 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00005461 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005462
Dan Gohman866971e2010-06-19 14:17:24 +00005463 // If the loop is canonicalized, the PHI will have exactly two entries.
5464 // That's the only form we support here.
5465 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5466
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005467 DenseMap<Instruction *, Constant *> CurrentIterVals;
5468 BasicBlock *Header = L->getHeader();
5469 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5470
Dan Gohman866971e2010-06-19 14:17:24 +00005471 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner4021d1a2004-04-17 18:36:24 +00005472 // second must be derived from the same PHI.
5473 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Craig Topper9f008862014-04-15 04:59:12 +00005474 PHINode *PHI = nullptr;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005475 for (BasicBlock::iterator I = Header->begin();
5476 (PHI = dyn_cast<PHINode>(I)); ++I) {
5477 Constant *StartCST =
5478 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
Craig Topper9f008862014-04-15 04:59:12 +00005479 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005480 CurrentIterVals[PHI] = StartCST;
5481 }
5482 if (!CurrentIterVals.count(PN))
5483 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005484
5485 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5486 // the loop symbolically to determine when the condition gets a value of
5487 // "ExitWhen".
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005488
Andrew Trick90c7a102011-11-16 00:52:40 +00005489 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005490 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Zhou Sheng75b871f2007-01-11 12:24:14 +00005491 ConstantInt *CondVal =
Chad Rosiere6de63d2011-12-01 21:29:16 +00005492 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005493 DL, TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00005494
Zhou Sheng75b871f2007-01-11 12:24:14 +00005495 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005496 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00005497
Reid Spencer983e3b32007-03-01 07:25:48 +00005498 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005499 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00005500 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005501 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005502
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005503 // Update all the PHI nodes for the next iteration.
5504 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005505
5506 // Create a list of which PHIs we need to compute. We want to do this before
5507 // calling EvaluateExpression on them because that may invalidate iterators
5508 // into CurrentIterVals.
5509 SmallVector<PHINode *, 8> PHIsToCompute;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005510 for (DenseMap<Instruction *, Constant *>::const_iterator
5511 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5512 PHINode *PHI = dyn_cast<PHINode>(I->first);
5513 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005514 PHIsToCompute.push_back(PHI);
5515 }
5516 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5517 E = PHIsToCompute.end(); I != E; ++I) {
5518 PHINode *PHI = *I;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005519 Constant *&NextPHI = NextIterVals[PHI];
5520 if (NextPHI) continue; // Already computed!
5521
5522 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005523 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005524 }
5525 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005526 }
5527
5528 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005529 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005530}
5531
Dan Gohman237d9e52009-09-03 15:00:26 +00005532/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005533/// at the specified scope in the program. The L value specifies a loop
5534/// nest to evaluate the expression at, where null is the top-level or a
5535/// specified loop is immediately inside of the loop.
5536///
5537/// This method can be used to compute the exit value for a variable defined
5538/// in a loop by querying what the value will hold in the parent loop.
5539///
Dan Gohman8ca08852009-05-24 23:25:42 +00005540/// In the case that a relevant loop exit value cannot be computed, the
5541/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005542const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005543 // Check to see if we've folded this expression at this loop before.
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005544 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5545 for (unsigned u = 0; u < Values.size(); u++) {
5546 if (Values[u].first == L)
5547 return Values[u].second ? Values[u].second : V;
5548 }
Craig Topper9f008862014-04-15 04:59:12 +00005549 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005550 // Otherwise compute it.
5551 const SCEV *C = computeSCEVAtScope(V, L);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005552 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5553 for (unsigned u = Values2.size(); u > 0; u--) {
5554 if (Values2[u - 1].first == L) {
5555 Values2[u - 1].second = C;
5556 break;
5557 }
5558 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005559 return C;
5560}
5561
Nick Lewyckya6674c72011-10-22 19:58:20 +00005562/// This builds up a Constant using the ConstantExpr interface. That way, we
5563/// will return Constants for objects which aren't represented by a
5564/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5565/// Returns NULL if the SCEV isn't representable as a Constant.
5566static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00005567 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00005568 case scCouldNotCompute:
5569 case scAddRecExpr:
5570 break;
5571 case scConstant:
5572 return cast<SCEVConstant>(V)->getValue();
5573 case scUnknown:
5574 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5575 case scSignExtend: {
5576 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5577 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5578 return ConstantExpr::getSExt(CastOp, SS->getType());
5579 break;
5580 }
5581 case scZeroExtend: {
5582 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5583 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5584 return ConstantExpr::getZExt(CastOp, SZ->getType());
5585 break;
5586 }
5587 case scTruncate: {
5588 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5589 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5590 return ConstantExpr::getTrunc(CastOp, ST->getType());
5591 break;
5592 }
5593 case scAddExpr: {
5594 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5595 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005596 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5597 unsigned AS = PTy->getAddressSpace();
5598 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5599 C = ConstantExpr::getBitCast(C, DestPtrTy);
5600 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00005601 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5602 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005603 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005604
5605 // First pointer!
5606 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005607 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00005608 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005609 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005610 // The offsets have been converted to bytes. We can add bytes to an
5611 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005612 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005613 }
5614
5615 // Don't bother trying to sum two pointers. We probably can't
5616 // statically compute a load that results from it anyway.
5617 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00005618 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005619
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005620 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5621 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00005622 C2 = ConstantExpr::getIntegerCast(
5623 C2, Type::getInt32Ty(C->getContext()), true);
5624 C = ConstantExpr::getGetElementPtr(C, C2);
5625 } else
5626 C = ConstantExpr::getAdd(C, C2);
5627 }
5628 return C;
5629 }
5630 break;
5631 }
5632 case scMulExpr: {
5633 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5634 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5635 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00005636 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005637 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5638 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005639 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005640 C = ConstantExpr::getMul(C, C2);
5641 }
5642 return C;
5643 }
5644 break;
5645 }
5646 case scUDivExpr: {
5647 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5648 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5649 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5650 if (LHS->getType() == RHS->getType())
5651 return ConstantExpr::getUDiv(LHS, RHS);
5652 break;
5653 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00005654 case scSMaxExpr:
5655 case scUMaxExpr:
5656 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005657 }
Craig Topper9f008862014-04-15 04:59:12 +00005658 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005659}
5660
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005661const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005662 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00005663
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00005664 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00005665 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00005666 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005667 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00005668 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00005669 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5670 if (PHINode *PN = dyn_cast<PHINode>(I))
5671 if (PN->getParent() == LI->getHeader()) {
5672 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00005673 // to see if the loop that contains it has a known backedge-taken
5674 // count. If so, we may be able to force computation of the exit
5675 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00005676 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00005677 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00005678 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005679 // Okay, we know how many times the containing loop executes. If
5680 // this is a constant evolving PHI node, get the final value at
5681 // the specified iteration number.
5682 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman0bddac12009-02-24 18:55:53 +00005683 BTCC->getValue()->getValue(),
Chris Lattnerdd730472004-04-17 22:58:41 +00005684 LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00005685 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00005686 }
5687 }
5688
Reid Spencere6328ca2006-12-04 21:33:23 +00005689 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00005690 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00005691 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00005692 // result. This is particularly useful for computing loop exit values.
5693 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005694 SmallVector<Constant *, 4> Operands;
5695 bool MadeImprovement = false;
Chris Lattnerdd730472004-04-17 22:58:41 +00005696 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5697 Value *Op = I->getOperand(i);
5698 if (Constant *C = dyn_cast<Constant>(Op)) {
5699 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005700 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00005701 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005702
5703 // If any of the operands is non-constant and if they are
5704 // non-integer and non-pointer, don't even try to analyze them
5705 // with scev techniques.
5706 if (!isSCEVable(Op->getType()))
5707 return V;
5708
5709 const SCEV *OrigV = getSCEV(Op);
5710 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5711 MadeImprovement |= OrigV != OpV;
5712
Nick Lewyckya6674c72011-10-22 19:58:20 +00005713 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005714 if (!C) return V;
5715 if (C->getType() != Op->getType())
5716 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5717 Op->getType(),
5718 false),
5719 C, Op->getType());
5720 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00005721 }
Dan Gohmance973df2009-06-24 04:48:43 +00005722
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005723 // Check to see if getSCEVAtScope actually made an improvement.
5724 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00005725 Constant *C = nullptr;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005726 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5727 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005728 Operands[0], Operands[1], DL,
Chad Rosier43a33062011-12-02 01:26:24 +00005729 TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005730 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5731 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005732 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005733 } else
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005734 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005735 Operands, DL, TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005736 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00005737 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005738 }
Chris Lattnerdd730472004-04-17 22:58:41 +00005739 }
5740 }
5741
5742 // This is some other type of SCEVUnknown, just return it.
5743 return V;
5744 }
5745
Dan Gohmana30370b2009-05-04 22:02:23 +00005746 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005747 // Avoid performing the look-up in the common case where the specified
5748 // expression has no loop-variant portions.
5749 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005750 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005751 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005752 // Okay, at least one of these operands is loop variant but might be
5753 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00005754 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5755 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00005756 NewOps.push_back(OpAtScope);
5757
5758 for (++i; i != e; ++i) {
5759 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005760 NewOps.push_back(OpAtScope);
5761 }
5762 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005763 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00005764 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005765 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00005766 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005767 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00005768 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005769 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00005770 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00005771 }
5772 }
5773 // If we got here, all operands are loop invariant.
5774 return Comm;
5775 }
5776
Dan Gohmana30370b2009-05-04 22:02:23 +00005777 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005778 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5779 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00005780 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5781 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00005782 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00005783 }
5784
5785 // If this is a loop recurrence for a loop that does not contain L, then we
5786 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00005787 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005788 // First, attempt to evaluate each operand.
5789 // Avoid performing the look-up in the common case where the specified
5790 // expression has no loop-variant portions.
5791 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5792 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5793 if (OpAtScope == AddRec->getOperand(i))
5794 continue;
5795
5796 // Okay, at least one of these operands is loop variant but might be
5797 // foldable. Build a new instance of the folded commutative expression.
5798 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5799 AddRec->op_begin()+i);
5800 NewOps.push_back(OpAtScope);
5801 for (++i; i != e; ++i)
5802 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5803
Andrew Trick759ba082011-04-27 01:21:25 +00005804 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00005805 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00005806 AddRec->getNoWrapFlags(SCEV::FlagNW));
5807 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00005808 // The addrec may be folded to a nonrecurrence, for example, if the
5809 // induction variable is multiplied by zero after constant folding. Go
5810 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00005811 if (!AddRec)
5812 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005813 break;
5814 }
5815
5816 // If the scope is outside the addrec's loop, evaluate it by using the
5817 // loop exit value of the addrec.
5818 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005819 // To evaluate this recurrence, we need to know how many times the AddRec
5820 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005821 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005822 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00005823
Eli Friedman61f67622008-08-04 23:49:06 +00005824 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00005825 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00005826 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005827
Dan Gohman8ca08852009-05-24 23:25:42 +00005828 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00005829 }
5830
Dan Gohmana30370b2009-05-04 22:02:23 +00005831 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005832 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005833 if (Op == Cast->getOperand())
5834 return Cast; // must be loop invariant
5835 return getZeroExtendExpr(Op, Cast->getType());
5836 }
5837
Dan Gohmana30370b2009-05-04 22:02:23 +00005838 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005839 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005840 if (Op == Cast->getOperand())
5841 return Cast; // must be loop invariant
5842 return getSignExtendExpr(Op, Cast->getType());
5843 }
5844
Dan Gohmana30370b2009-05-04 22:02:23 +00005845 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005846 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005847 if (Op == Cast->getOperand())
5848 return Cast; // must be loop invariant
5849 return getTruncateExpr(Op, Cast->getType());
5850 }
5851
Torok Edwinfbcc6632009-07-14 16:55:14 +00005852 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00005853}
5854
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005855/// getSCEVAtScope - This is a convenience function which does
5856/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00005857const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00005858 return getSCEVAtScope(getSCEV(V), L);
5859}
5860
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005861/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5862/// following equation:
5863///
5864/// A * X = B (mod N)
5865///
5866/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5867/// A and B isn't important.
5868///
5869/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005870static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005871 ScalarEvolution &SE) {
5872 uint32_t BW = A.getBitWidth();
5873 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5874 assert(A != 0 && "A must be non-zero.");
5875
5876 // 1. D = gcd(A, N)
5877 //
5878 // The gcd of A and N may have only one prime factor: 2. The number of
5879 // trailing zeros in A is its multiplicity
5880 uint32_t Mult2 = A.countTrailingZeros();
5881 // D = 2^Mult2
5882
5883 // 2. Check if B is divisible by D.
5884 //
5885 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5886 // is not less than multiplicity of this prime factor for D.
5887 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00005888 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005889
5890 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5891 // modulo (N / D).
5892 //
5893 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5894 // bit width during computations.
5895 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5896 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00005897 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005898 APInt I = AD.multiplicativeInverse(Mod);
5899
5900 // 4. Compute the minimum unsigned root of the equation:
5901 // I * (B / D) mod (N / D)
5902 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5903
5904 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5905 // bits.
5906 return SE.getConstant(Result.trunc(BW));
5907}
Chris Lattnerd934c702004-04-02 20:23:17 +00005908
5909/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5910/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5911/// might be the same) or two SCEVCouldNotCompute objects.
5912///
Dan Gohmanaf752342009-07-07 17:06:11 +00005913static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00005914SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005915 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00005916 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5917 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5918 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00005919
Chris Lattnerd934c702004-04-02 20:23:17 +00005920 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00005921 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00005922 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005923 return std::make_pair(CNC, CNC);
5924 }
5925
Reid Spencer983e3b32007-03-01 07:25:48 +00005926 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnercad61e82007-04-15 19:52:49 +00005927 const APInt &L = LC->getValue()->getValue();
5928 const APInt &M = MC->getValue()->getValue();
5929 const APInt &N = NC->getValue()->getValue();
Reid Spencer983e3b32007-03-01 07:25:48 +00005930 APInt Two(BitWidth, 2);
5931 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00005932
Dan Gohmance973df2009-06-24 04:48:43 +00005933 {
Reid Spencer983e3b32007-03-01 07:25:48 +00005934 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00005935 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00005936 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5937 // The B coefficient is M-N/2
5938 APInt B(M);
5939 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00005940
Reid Spencer983e3b32007-03-01 07:25:48 +00005941 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00005942 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00005943
Reid Spencer983e3b32007-03-01 07:25:48 +00005944 // Compute the B^2-4ac term.
5945 APInt SqrtTerm(B);
5946 SqrtTerm *= B;
5947 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00005948
Nick Lewyckyfb780832012-08-01 09:14:36 +00005949 if (SqrtTerm.isNegative()) {
5950 // The loop is provably infinite.
5951 const SCEV *CNC = SE.getCouldNotCompute();
5952 return std::make_pair(CNC, CNC);
5953 }
5954
Reid Spencer983e3b32007-03-01 07:25:48 +00005955 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5956 // integer value or else APInt::sqrt() will assert.
5957 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00005958
Dan Gohmance973df2009-06-24 04:48:43 +00005959 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00005960 // The divisions must be performed as signed divisions.
5961 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00005962 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00005963 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00005964 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky7b14e202008-11-03 02:43:49 +00005965 return std::make_pair(CNC, CNC);
5966 }
5967
Owen Anderson47db9412009-07-22 00:24:57 +00005968 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00005969
5970 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00005971 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00005972 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00005973 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00005974
Dan Gohmance973df2009-06-24 04:48:43 +00005975 return std::make_pair(SE.getConstant(Solution1),
Dan Gohmana37eaf22007-10-22 18:31:58 +00005976 SE.getConstant(Solution2));
Nick Lewycky31555522011-10-03 07:10:45 +00005977 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00005978}
5979
5980/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00005981/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00005982///
5983/// This is only used for loops with a "x != y" exit test. The exit condition is
5984/// now expressed as a single expression, V = x-y. So the exit test is
5985/// effectively V != 0. We know and take advantage of the fact that this
5986/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005987ScalarEvolution::ExitLimit
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005988ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005989 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00005990 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005991 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00005992 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005993 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00005994 }
5995
Dan Gohman48f82222009-05-04 22:30:44 +00005996 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005997 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005998 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005999
Chris Lattnerdff679f2011-01-09 22:39:48 +00006000 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6001 // the quadratic equation to solve it.
6002 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6003 std::pair<const SCEV *,const SCEV *> Roots =
6004 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00006005 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6006 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00006007 if (R1 && R2) {
Chris Lattner09169212004-04-02 20:26:46 +00006008#if 0
David Greenedf1c4972009-12-23 22:18:14 +00006009 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmane20f8242009-04-21 00:47:46 +00006010 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00006011#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00006012 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006013 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00006014 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6015 R1->getValue(),
6016 R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006017 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00006018 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00006019
Chris Lattnerd934c702004-04-02 20:23:17 +00006020 // We can only use this value if the chrec ends up with an exact zero
6021 // value at this index. When solving for "X*X != 5", for example, we
6022 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00006023 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00006024 if (Val->isZero())
6025 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00006026 }
6027 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00006028 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006029 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006030
Chris Lattnerdff679f2011-01-09 22:39:48 +00006031 // Otherwise we can only handle this if it is affine.
6032 if (!AddRec->isAffine())
6033 return getCouldNotCompute();
6034
6035 // If this is an affine expression, the execution count of this branch is
6036 // the minimum unsigned root of the following equation:
6037 //
6038 // Start + Step*N = 0 (mod 2^BW)
6039 //
6040 // equivalent to:
6041 //
6042 // Step*N = -Start (mod 2^BW)
6043 //
6044 // where BW is the common bit width of Start and Step.
6045
6046 // Get the initial value for the loop.
6047 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6048 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6049
6050 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00006051 //
6052 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6053 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6054 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6055 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00006056 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00006057 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00006058 return getCouldNotCompute();
6059
Andrew Trick8b55b732011-03-14 16:50:06 +00006060 // For positive steps (counting up until unsigned overflow):
6061 // N = -Start/Step (as unsigned)
6062 // For negative steps (counting down to zero):
6063 // N = Start/-Step
6064 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickf1781db2011-03-14 17:28:02 +00006065 bool CountDown = StepC->getValue()->getValue().isNegative();
6066 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00006067
6068 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00006069 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6070 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00006071 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6072 ConstantRange CR = getUnsignedRange(Start);
6073 const SCEV *MaxBECount;
6074 if (!CountDown && CR.getUnsignedMin().isMinValue())
6075 // When counting up, the worst starting value is 1, not 0.
6076 MaxBECount = CR.getUnsignedMax().isMinValue()
6077 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6078 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6079 else
6080 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6081 : -CR.getUnsignedMin());
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006082 return ExitLimit(Distance, MaxBECount);
Nick Lewycky31555522011-10-03 07:10:45 +00006083 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00006084
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006085 // If the step exactly divides the distance then unsigned divide computes the
6086 // backedge count.
6087 const SCEV *Q, *R;
6088 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6089 SCEVDivision::divide(SE, Distance, Step, &Q, &R);
6090 if (R->isZero()) {
Andrew Trickee5aa7f2014-01-15 06:42:11 +00006091 const SCEV *Exact =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006092 getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6093 return ExitLimit(Exact, Exact);
Andrew Trickee5aa7f2014-01-15 06:42:11 +00006094 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006095
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006096 // If the condition controls loop exit (the loop exits only if the expression
6097 // is true) and the addition is no-wrap we can use unsigned divide to
6098 // compute the backedge count. In this case, the step may not divide the
6099 // distance, but we don't care because if the condition is "missed" the loop
6100 // will have undefined behavior due to wrapping.
6101 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6102 const SCEV *Exact =
6103 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6104 return ExitLimit(Exact, Exact);
6105 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006106
Chris Lattnerdff679f2011-01-09 22:39:48 +00006107 // Then, try to solve the above equation provided that Start is constant.
6108 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6109 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6110 -StartC->getValue()->getValue(),
6111 *this);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006112 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006113}
6114
6115/// HowFarToNonZero - Return the number of times a backedge checking the
6116/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006117/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00006118ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00006119ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006120 // Loops that look like: while (X == 0) are very strange indeed. We don't
6121 // handle them yet except for the trivial case. This could be expanded in the
6122 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00006123
Chris Lattnerd934c702004-04-02 20:23:17 +00006124 // If the value is a constant, check to see if it is known to be non-zero
6125 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00006126 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00006127 if (!C->getValue()->isNullValue())
Dan Gohman1d2ded72010-05-03 22:09:21 +00006128 return getConstant(C->getType(), 0);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006129 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006130 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006131
Chris Lattnerd934c702004-04-02 20:23:17 +00006132 // We could implement others, but I really doubt anyone writes loops like
6133 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006134 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006135}
6136
Dan Gohmanf9081a22008-09-15 22:18:04 +00006137/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6138/// (which may not be an immediate predecessor) which has exactly one
6139/// successor from which BB is reachable, or null if no such block is
6140/// found.
6141///
Dan Gohman4e3c1132010-04-15 16:19:08 +00006142std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00006143ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00006144 // If the block has a unique predecessor, then there is no path from the
6145 // predecessor to the block that does not go through the direct edge
6146 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00006147 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman4e3c1132010-04-15 16:19:08 +00006148 return std::make_pair(Pred, BB);
Dan Gohmanf9081a22008-09-15 22:18:04 +00006149
6150 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006151 // If the header has a unique predecessor outside the loop, it must be
6152 // a block that has exactly one successor that can reach the loop.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006153 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006154 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanf9081a22008-09-15 22:18:04 +00006155
Dan Gohman4e3c1132010-04-15 16:19:08 +00006156 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanf9081a22008-09-15 22:18:04 +00006157}
6158
Dan Gohman450f4e02009-06-20 00:35:32 +00006159/// HasSameValue - SCEV structural equivalence is usually sufficient for
6160/// testing whether two expressions are equal, however for the purposes of
6161/// looking for a condition guarding a loop, it can be useful to be a little
6162/// more general, since a front-end may have replicated the controlling
6163/// expression.
6164///
Dan Gohmanaf752342009-07-07 17:06:11 +00006165static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00006166 // Quick check to see if they are the same SCEV.
6167 if (A == B) return true;
6168
6169 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6170 // two different instructions with the same value. Check for this case.
6171 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6172 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6173 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6174 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman2d085562009-08-25 17:56:57 +00006175 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman450f4e02009-06-20 00:35:32 +00006176 return true;
6177
6178 // Otherwise assume they may have a different value.
6179 return false;
6180}
6181
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006182/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006183/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006184///
6185bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006186 const SCEV *&LHS, const SCEV *&RHS,
6187 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006188 bool Changed = false;
6189
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006190 // If we hit the max recursion limit bail out.
6191 if (Depth >= 3)
6192 return false;
6193
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006194 // Canonicalize a constant to the right side.
6195 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6196 // Check for both operands constant.
6197 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6198 if (ConstantExpr::getICmp(Pred,
6199 LHSC->getValue(),
6200 RHSC->getValue())->isNullValue())
6201 goto trivially_false;
6202 else
6203 goto trivially_true;
6204 }
6205 // Otherwise swap the operands to put the constant on the right.
6206 std::swap(LHS, RHS);
6207 Pred = ICmpInst::getSwappedPredicate(Pred);
6208 Changed = true;
6209 }
6210
6211 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00006212 // addrec's loop, put the addrec on the left. Also make a dominance check,
6213 // as both operands could be addrecs loop-invariant in each other's loop.
6214 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6215 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00006216 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006217 std::swap(LHS, RHS);
6218 Pred = ICmpInst::getSwappedPredicate(Pred);
6219 Changed = true;
6220 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00006221 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006222
6223 // If there's a constant operand, canonicalize comparisons with boundary
6224 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6225 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6226 const APInt &RA = RC->getValue()->getValue();
6227 switch (Pred) {
6228 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6229 case ICmpInst::ICMP_EQ:
6230 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006231 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6232 if (!RA)
6233 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6234 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00006235 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6236 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006237 RHS = AE->getOperand(1);
6238 LHS = ME->getOperand(1);
6239 Changed = true;
6240 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006241 break;
6242 case ICmpInst::ICMP_UGE:
6243 if ((RA - 1).isMinValue()) {
6244 Pred = ICmpInst::ICMP_NE;
6245 RHS = getConstant(RA - 1);
6246 Changed = true;
6247 break;
6248 }
6249 if (RA.isMaxValue()) {
6250 Pred = ICmpInst::ICMP_EQ;
6251 Changed = true;
6252 break;
6253 }
6254 if (RA.isMinValue()) goto trivially_true;
6255
6256 Pred = ICmpInst::ICMP_UGT;
6257 RHS = getConstant(RA - 1);
6258 Changed = true;
6259 break;
6260 case ICmpInst::ICMP_ULE:
6261 if ((RA + 1).isMaxValue()) {
6262 Pred = ICmpInst::ICMP_NE;
6263 RHS = getConstant(RA + 1);
6264 Changed = true;
6265 break;
6266 }
6267 if (RA.isMinValue()) {
6268 Pred = ICmpInst::ICMP_EQ;
6269 Changed = true;
6270 break;
6271 }
6272 if (RA.isMaxValue()) goto trivially_true;
6273
6274 Pred = ICmpInst::ICMP_ULT;
6275 RHS = getConstant(RA + 1);
6276 Changed = true;
6277 break;
6278 case ICmpInst::ICMP_SGE:
6279 if ((RA - 1).isMinSignedValue()) {
6280 Pred = ICmpInst::ICMP_NE;
6281 RHS = getConstant(RA - 1);
6282 Changed = true;
6283 break;
6284 }
6285 if (RA.isMaxSignedValue()) {
6286 Pred = ICmpInst::ICMP_EQ;
6287 Changed = true;
6288 break;
6289 }
6290 if (RA.isMinSignedValue()) goto trivially_true;
6291
6292 Pred = ICmpInst::ICMP_SGT;
6293 RHS = getConstant(RA - 1);
6294 Changed = true;
6295 break;
6296 case ICmpInst::ICMP_SLE:
6297 if ((RA + 1).isMaxSignedValue()) {
6298 Pred = ICmpInst::ICMP_NE;
6299 RHS = getConstant(RA + 1);
6300 Changed = true;
6301 break;
6302 }
6303 if (RA.isMinSignedValue()) {
6304 Pred = ICmpInst::ICMP_EQ;
6305 Changed = true;
6306 break;
6307 }
6308 if (RA.isMaxSignedValue()) goto trivially_true;
6309
6310 Pred = ICmpInst::ICMP_SLT;
6311 RHS = getConstant(RA + 1);
6312 Changed = true;
6313 break;
6314 case ICmpInst::ICMP_UGT:
6315 if (RA.isMinValue()) {
6316 Pred = ICmpInst::ICMP_NE;
6317 Changed = true;
6318 break;
6319 }
6320 if ((RA + 1).isMaxValue()) {
6321 Pred = ICmpInst::ICMP_EQ;
6322 RHS = getConstant(RA + 1);
6323 Changed = true;
6324 break;
6325 }
6326 if (RA.isMaxValue()) goto trivially_false;
6327 break;
6328 case ICmpInst::ICMP_ULT:
6329 if (RA.isMaxValue()) {
6330 Pred = ICmpInst::ICMP_NE;
6331 Changed = true;
6332 break;
6333 }
6334 if ((RA - 1).isMinValue()) {
6335 Pred = ICmpInst::ICMP_EQ;
6336 RHS = getConstant(RA - 1);
6337 Changed = true;
6338 break;
6339 }
6340 if (RA.isMinValue()) goto trivially_false;
6341 break;
6342 case ICmpInst::ICMP_SGT:
6343 if (RA.isMinSignedValue()) {
6344 Pred = ICmpInst::ICMP_NE;
6345 Changed = true;
6346 break;
6347 }
6348 if ((RA + 1).isMaxSignedValue()) {
6349 Pred = ICmpInst::ICMP_EQ;
6350 RHS = getConstant(RA + 1);
6351 Changed = true;
6352 break;
6353 }
6354 if (RA.isMaxSignedValue()) goto trivially_false;
6355 break;
6356 case ICmpInst::ICMP_SLT:
6357 if (RA.isMaxSignedValue()) {
6358 Pred = ICmpInst::ICMP_NE;
6359 Changed = true;
6360 break;
6361 }
6362 if ((RA - 1).isMinSignedValue()) {
6363 Pred = ICmpInst::ICMP_EQ;
6364 RHS = getConstant(RA - 1);
6365 Changed = true;
6366 break;
6367 }
6368 if (RA.isMinSignedValue()) goto trivially_false;
6369 break;
6370 }
6371 }
6372
6373 // Check for obvious equality.
6374 if (HasSameValue(LHS, RHS)) {
6375 if (ICmpInst::isTrueWhenEqual(Pred))
6376 goto trivially_true;
6377 if (ICmpInst::isFalseWhenEqual(Pred))
6378 goto trivially_false;
6379 }
6380
Dan Gohman81585c12010-05-03 16:35:17 +00006381 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6382 // adding or subtracting 1 from one of the operands.
6383 switch (Pred) {
6384 case ICmpInst::ICMP_SLE:
6385 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6386 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006387 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006388 Pred = ICmpInst::ICMP_SLT;
6389 Changed = true;
6390 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006391 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006392 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006393 Pred = ICmpInst::ICMP_SLT;
6394 Changed = true;
6395 }
6396 break;
6397 case ICmpInst::ICMP_SGE:
6398 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006399 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006400 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006401 Pred = ICmpInst::ICMP_SGT;
6402 Changed = true;
6403 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6404 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006405 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006406 Pred = ICmpInst::ICMP_SGT;
6407 Changed = true;
6408 }
6409 break;
6410 case ICmpInst::ICMP_ULE:
6411 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006412 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006413 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006414 Pred = ICmpInst::ICMP_ULT;
6415 Changed = true;
6416 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006417 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006418 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006419 Pred = ICmpInst::ICMP_ULT;
6420 Changed = true;
6421 }
6422 break;
6423 case ICmpInst::ICMP_UGE:
6424 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006425 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006426 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006427 Pred = ICmpInst::ICMP_UGT;
6428 Changed = true;
6429 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006430 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006431 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006432 Pred = ICmpInst::ICMP_UGT;
6433 Changed = true;
6434 }
6435 break;
6436 default:
6437 break;
6438 }
6439
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006440 // TODO: More simplifications are possible here.
6441
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006442 // Recursively simplify until we either hit a recursion limit or nothing
6443 // changes.
6444 if (Changed)
6445 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6446
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006447 return Changed;
6448
6449trivially_true:
6450 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006451 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006452 Pred = ICmpInst::ICMP_EQ;
6453 return true;
6454
6455trivially_false:
6456 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006457 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006458 Pred = ICmpInst::ICMP_NE;
6459 return true;
6460}
6461
Dan Gohmane65c9172009-07-13 21:35:55 +00006462bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6463 return getSignedRange(S).getSignedMax().isNegative();
6464}
6465
6466bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6467 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6468}
6469
6470bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6471 return !getSignedRange(S).getSignedMin().isNegative();
6472}
6473
6474bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6475 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6476}
6477
6478bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6479 return isKnownNegative(S) || isKnownPositive(S);
6480}
6481
6482bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6483 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00006484 // Canonicalize the inputs first.
6485 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6486
Dan Gohman07591692010-04-11 22:16:48 +00006487 // If LHS or RHS is an addrec, check to see if the condition is true in
6488 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00006489 // If LHS and RHS are both addrec, both conditions must be true in
6490 // every iteration of the loop.
6491 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6492 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6493 bool LeftGuarded = false;
6494 bool RightGuarded = false;
6495 if (LAR) {
6496 const Loop *L = LAR->getLoop();
6497 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6498 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6499 if (!RAR) return true;
6500 LeftGuarded = true;
6501 }
6502 }
6503 if (RAR) {
6504 const Loop *L = RAR->getLoop();
6505 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6506 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6507 if (!LAR) return true;
6508 RightGuarded = true;
6509 }
6510 }
6511 if (LeftGuarded && RightGuarded)
6512 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006513
Dan Gohman07591692010-04-11 22:16:48 +00006514 // Otherwise see what can be done with known constant ranges.
6515 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6516}
6517
6518bool
6519ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6520 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006521 if (HasSameValue(LHS, RHS))
6522 return ICmpInst::isTrueWhenEqual(Pred);
6523
Dan Gohman07591692010-04-11 22:16:48 +00006524 // This code is split out from isKnownPredicate because it is called from
6525 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00006526 switch (Pred) {
6527 default:
Dan Gohman8c129d72009-07-16 17:34:36 +00006528 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohmane65c9172009-07-13 21:35:55 +00006529 case ICmpInst::ICMP_SGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00006530 std::swap(LHS, RHS);
6531 case ICmpInst::ICMP_SLT: {
6532 ConstantRange LHSRange = getSignedRange(LHS);
6533 ConstantRange RHSRange = getSignedRange(RHS);
6534 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6535 return true;
6536 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6537 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006538 break;
6539 }
6540 case ICmpInst::ICMP_SGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00006541 std::swap(LHS, RHS);
6542 case ICmpInst::ICMP_SLE: {
6543 ConstantRange LHSRange = getSignedRange(LHS);
6544 ConstantRange RHSRange = getSignedRange(RHS);
6545 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6546 return true;
6547 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6548 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006549 break;
6550 }
6551 case ICmpInst::ICMP_UGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00006552 std::swap(LHS, RHS);
6553 case ICmpInst::ICMP_ULT: {
6554 ConstantRange LHSRange = getUnsignedRange(LHS);
6555 ConstantRange RHSRange = getUnsignedRange(RHS);
6556 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6557 return true;
6558 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6559 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006560 break;
6561 }
6562 case ICmpInst::ICMP_UGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00006563 std::swap(LHS, RHS);
6564 case ICmpInst::ICMP_ULE: {
6565 ConstantRange LHSRange = getUnsignedRange(LHS);
6566 ConstantRange RHSRange = getUnsignedRange(RHS);
6567 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6568 return true;
6569 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6570 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006571 break;
6572 }
6573 case ICmpInst::ICMP_NE: {
6574 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6575 return true;
6576 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6577 return true;
6578
6579 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6580 if (isKnownNonZero(Diff))
6581 return true;
6582 break;
6583 }
6584 case ICmpInst::ICMP_EQ:
Dan Gohman34392622009-07-20 23:54:43 +00006585 // The check at the top of the function catches the case where
6586 // the values are known to be equal.
Dan Gohmane65c9172009-07-13 21:35:55 +00006587 break;
6588 }
6589 return false;
6590}
6591
6592/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6593/// protected by a conditional between LHS and RHS. This is used to
6594/// to eliminate casts.
6595bool
6596ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6597 ICmpInst::Predicate Pred,
6598 const SCEV *LHS, const SCEV *RHS) {
6599 // Interpret a null as meaning no loop, where there is obviously no guard
6600 // (interprocedural conditions notwithstanding).
6601 if (!L) return true;
6602
Sanjoy Das1f05c512014-10-10 21:22:34 +00006603 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6604
Dan Gohmane65c9172009-07-13 21:35:55 +00006605 BasicBlock *Latch = L->getLoopLatch();
6606 if (!Latch)
6607 return false;
6608
6609 BranchInst *LoopContinuePredicate =
6610 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006611 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6612 isImpliedCond(Pred, LHS, RHS,
6613 LoopContinuePredicate->getCondition(),
6614 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6615 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006616
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006617 // Check conditions due to any @llvm.assume intrinsics.
6618 for (auto &CI : AT->assumptions(F)) {
6619 if (!DT->dominates(CI, Latch->getTerminator()))
6620 continue;
6621
6622 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6623 return true;
6624 }
6625
6626 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006627}
6628
Dan Gohmanb50349a2010-04-11 19:27:13 +00006629/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00006630/// by a conditional between LHS and RHS. This is used to help avoid max
6631/// expressions in loop trip counts, and to eliminate casts.
6632bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00006633ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6634 ICmpInst::Predicate Pred,
6635 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00006636 // Interpret a null as meaning no loop, where there is obviously no guard
6637 // (interprocedural conditions notwithstanding).
6638 if (!L) return false;
6639
Sanjoy Das1f05c512014-10-10 21:22:34 +00006640 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6641
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006642 // Starting at the loop predecessor, climb up the predecessor chain, as long
6643 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00006644 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00006645 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006646 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00006647 Pair.first;
6648 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00006649
6650 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00006651 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00006652 if (!LoopEntryPredicate ||
6653 LoopEntryPredicate->isUnconditional())
6654 continue;
6655
Dan Gohmane18c2d62010-08-10 23:46:30 +00006656 if (isImpliedCond(Pred, LHS, RHS,
6657 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00006658 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00006659 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00006660 }
6661
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006662 // Check conditions due to any @llvm.assume intrinsics.
6663 for (auto &CI : AT->assumptions(F)) {
6664 if (!DT->dominates(CI, L->getHeader()))
6665 continue;
6666
6667 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6668 return true;
6669 }
6670
Dan Gohman2a62fd92008-08-12 20:17:31 +00006671 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00006672}
6673
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00006674/// RAII wrapper to prevent recursive application of isImpliedCond.
6675/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6676/// currently evaluating isImpliedCond.
6677struct MarkPendingLoopPredicate {
6678 Value *Cond;
6679 DenseSet<Value*> &LoopPreds;
6680 bool Pending;
6681
6682 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6683 : Cond(C), LoopPreds(LP) {
6684 Pending = !LoopPreds.insert(Cond).second;
6685 }
6686 ~MarkPendingLoopPredicate() {
6687 if (!Pending)
6688 LoopPreds.erase(Cond);
6689 }
6690};
6691
Dan Gohman430f0cc2009-07-21 23:03:19 +00006692/// isImpliedCond - Test whether the condition described by Pred, LHS,
6693/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00006694bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006695 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00006696 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006697 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00006698 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6699 if (Mark.Pending)
6700 return false;
6701
Dan Gohman8b0a4192010-03-01 17:49:51 +00006702 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00006703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006704 if (BO->getOpcode() == Instruction::And) {
6705 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00006706 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6707 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006708 } else if (BO->getOpcode() == Instruction::Or) {
6709 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00006710 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6711 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006712 }
6713 }
6714
Dan Gohmane18c2d62010-08-10 23:46:30 +00006715 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006716 if (!ICI) return false;
6717
Dan Gohmane65c9172009-07-13 21:35:55 +00006718 // Bail if the ICmp's operands' types are wider than the needed type
6719 // before attempting to call getSCEV on them. This avoids infinite
6720 // recursion, since the analysis of widening casts can require loop
6721 // exit condition information for overflow checking, which would
6722 // lead back here.
6723 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman430f0cc2009-07-21 23:03:19 +00006724 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohmane65c9172009-07-13 21:35:55 +00006725 return false;
6726
Andrew Trickfa594032012-11-29 18:35:13 +00006727 // Now that we found a conditional branch that dominates the loop or controls
6728 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00006729 ICmpInst::Predicate FoundPred;
6730 if (Inverse)
6731 FoundPred = ICI->getInversePredicate();
6732 else
6733 FoundPred = ICI->getPredicate();
6734
6735 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6736 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00006737
6738 // Balance the types. The case where FoundLHS' type is wider than
6739 // LHS' type is checked for above.
6740 if (getTypeSizeInBits(LHS->getType()) >
6741 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00006742 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006743 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6744 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6745 } else {
6746 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6747 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6748 }
6749 }
6750
Dan Gohman430f0cc2009-07-21 23:03:19 +00006751 // Canonicalize the query to match the way instcombine will have
6752 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00006753 if (SimplifyICmpOperands(Pred, LHS, RHS))
6754 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00006755 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00006756 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6757 if (FoundLHS == FoundRHS)
6758 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00006759
6760 // Check to see if we can make the LHS or RHS match.
6761 if (LHS == FoundRHS || RHS == FoundLHS) {
6762 if (isa<SCEVConstant>(RHS)) {
6763 std::swap(FoundLHS, FoundRHS);
6764 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6765 } else {
6766 std::swap(LHS, RHS);
6767 Pred = ICmpInst::getSwappedPredicate(Pred);
6768 }
6769 }
6770
6771 // Check whether the found predicate is the same as the desired predicate.
6772 if (FoundPred == Pred)
6773 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6774
6775 // Check whether swapping the found predicate makes it the same as the
6776 // desired predicate.
6777 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6778 if (isa<SCEVConstant>(RHS))
6779 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6780 else
6781 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6782 RHS, LHS, FoundLHS, FoundRHS);
6783 }
6784
6785 // Check whether the actual condition is beyond sufficient.
6786 if (FoundPred == ICmpInst::ICMP_EQ)
6787 if (ICmpInst::isTrueWhenEqual(Pred))
6788 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6789 return true;
6790 if (Pred == ICmpInst::ICMP_NE)
6791 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6792 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6793 return true;
6794
6795 // Otherwise assume the worst.
6796 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006797}
6798
Dan Gohman430f0cc2009-07-21 23:03:19 +00006799/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00006800/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006801/// and FoundRHS is true.
6802bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6803 const SCEV *LHS, const SCEV *RHS,
6804 const SCEV *FoundLHS,
6805 const SCEV *FoundRHS) {
6806 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6807 FoundLHS, FoundRHS) ||
6808 // ~x < ~y --> x > y
6809 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6810 getNotSCEV(FoundRHS),
6811 getNotSCEV(FoundLHS));
6812}
6813
6814/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00006815/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006816/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00006817bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00006818ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
6819 const SCEV *LHS, const SCEV *RHS,
6820 const SCEV *FoundLHS,
6821 const SCEV *FoundRHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006822 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00006823 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6824 case ICmpInst::ICMP_EQ:
6825 case ICmpInst::ICMP_NE:
6826 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
6827 return true;
6828 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00006829 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006830 case ICmpInst::ICMP_SLE:
Dan Gohman07591692010-04-11 22:16:48 +00006831 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
6832 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006833 return true;
6834 break;
6835 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006836 case ICmpInst::ICMP_SGE:
Dan Gohman07591692010-04-11 22:16:48 +00006837 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
6838 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006839 return true;
6840 break;
6841 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006842 case ICmpInst::ICMP_ULE:
Dan Gohman07591692010-04-11 22:16:48 +00006843 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
6844 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006845 return true;
6846 break;
6847 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006848 case ICmpInst::ICMP_UGE:
Dan Gohman07591692010-04-11 22:16:48 +00006849 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
6850 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006851 return true;
6852 break;
6853 }
6854
6855 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006856}
6857
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006858// Verify if an linear IV with positive stride can overflow when in a
6859// less-than comparison, knowing the invariant term of the comparison, the
6860// stride and the knowledge of NSW/NUW flags on the recurrence.
6861bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
6862 bool IsSigned, bool NoWrap) {
6863 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00006864
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006865 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6866 const SCEV *One = getConstant(Stride->getType(), 1);
Andrew Trick2afa3252011-03-09 17:29:58 +00006867
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006868 if (IsSigned) {
6869 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
6870 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
6871 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6872 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00006873
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006874 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
6875 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00006876 }
Dan Gohman01048422009-06-21 23:46:38 +00006877
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006878 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
6879 APInt MaxValue = APInt::getMaxValue(BitWidth);
6880 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6881 .getUnsignedMax();
6882
6883 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
6884 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
6885}
6886
6887// Verify if an linear IV with negative stride can overflow when in a
6888// greater-than comparison, knowing the invariant term of the comparison,
6889// the stride and the knowledge of NSW/NUW flags on the recurrence.
6890bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
6891 bool IsSigned, bool NoWrap) {
6892 if (NoWrap) return false;
6893
6894 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6895 const SCEV *One = getConstant(Stride->getType(), 1);
6896
6897 if (IsSigned) {
6898 APInt MinRHS = getSignedRange(RHS).getSignedMin();
6899 APInt MinValue = APInt::getSignedMinValue(BitWidth);
6900 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6901 .getSignedMax();
6902
6903 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
6904 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
6905 }
6906
6907 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
6908 APInt MinValue = APInt::getMinValue(BitWidth);
6909 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6910 .getUnsignedMax();
6911
6912 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
6913 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
6914}
6915
6916// Compute the backedge taken count knowing the interval difference, the
6917// stride and presence of the equality in the comparison.
6918const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
6919 bool Equality) {
6920 const SCEV *One = getConstant(Step->getType(), 1);
6921 Delta = Equality ? getAddExpr(Delta, Step)
6922 : getAddExpr(Delta, getMinusSCEV(Step, One));
6923 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00006924}
6925
Chris Lattner587a75b2005-08-15 23:33:51 +00006926/// HowManyLessThans - Return the number of times a backedge containing the
6927/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006928/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00006929///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006930/// @param ControlsExit is true when the LHS < RHS condition directly controls
6931/// the branch (loops exits only if condition is true). In this case, we can use
6932/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006933ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00006934ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006935 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006936 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006937 // We handle only IV < Invariant
6938 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006939 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00006940
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006941 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohman2b8da352009-04-30 20:47:05 +00006942
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006943 // Avoid weird loops
6944 if (!IV || IV->getLoop() != L || !IV->isAffine())
6945 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00006946
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006947 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006948 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00006949
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006950 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00006951
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006952 // Avoid negative or zero stride values
6953 if (!isKnownPositive(Stride))
6954 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00006955
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006956 // Avoid proven overflow cases: this will ensure that the backedge taken count
6957 // will not generate any unsigned overflow. Relaxed no-overflow conditions
6958 // exploit NoWrapFlags, allowing to optimize in presence of undefined
6959 // behaviors like the case of C language.
6960 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
6961 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00006962
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006963 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
6964 : ICmpInst::ICMP_ULT;
6965 const SCEV *Start = IV->getStart();
6966 const SCEV *End = RHS;
6967 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
6968 End = IsSigned ? getSMaxExpr(RHS, Start)
6969 : getUMaxExpr(RHS, Start);
Dan Gohman51aaf022010-01-26 04:40:18 +00006970
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006971 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00006972
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006973 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
6974 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00006975
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006976 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
6977 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00006978
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006979 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
6980 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
6981 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00006982
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006983 // Although End can be a MAX expression we estimate MaxEnd considering only
6984 // the case End = RHS. This is safe because in the other case (End - Start)
6985 // is zero, leading to a zero maximum backedge taken count.
6986 APInt MaxEnd =
6987 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
6988 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
6989
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00006990 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006991 if (isa<SCEVConstant>(BECount))
6992 MaxBECount = BECount;
6993 else
6994 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
6995 getConstant(MinStride), false);
6996
6997 if (isa<SCEVCouldNotCompute>(MaxBECount))
6998 MaxBECount = BECount;
6999
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007000 return ExitLimit(BECount, MaxBECount);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007001}
7002
7003ScalarEvolution::ExitLimit
7004ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
7005 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007006 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007007 // We handle only IV > Invariant
7008 if (!isLoopInvariant(RHS, L))
7009 return getCouldNotCompute();
7010
7011 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7012
7013 // Avoid weird loops
7014 if (!IV || IV->getLoop() != L || !IV->isAffine())
7015 return getCouldNotCompute();
7016
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007017 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007018 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7019
7020 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
7021
7022 // Avoid negative or zero stride values
7023 if (!isKnownPositive(Stride))
7024 return getCouldNotCompute();
7025
7026 // Avoid proven overflow cases: this will ensure that the backedge taken count
7027 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7028 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7029 // behaviors like the case of C language.
7030 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
7031 return getCouldNotCompute();
7032
7033 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
7034 : ICmpInst::ICMP_UGT;
7035
7036 const SCEV *Start = IV->getStart();
7037 const SCEV *End = RHS;
7038 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
7039 End = IsSigned ? getSMinExpr(RHS, Start)
7040 : getUMinExpr(RHS, Start);
7041
7042 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
7043
7044 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
7045 : getUnsignedRange(Start).getUnsignedMax();
7046
7047 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7048 : getUnsignedRange(Stride).getUnsignedMin();
7049
7050 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7051 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
7052 : APInt::getMinValue(BitWidth) + (MinStride - 1);
7053
7054 // Although End can be a MIN expression we estimate MinEnd considering only
7055 // the case End = RHS. This is safe because in the other case (Start - End)
7056 // is zero, leading to a zero maximum backedge taken count.
7057 APInt MinEnd =
7058 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
7059 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
7060
7061
7062 const SCEV *MaxBECount = getCouldNotCompute();
7063 if (isa<SCEVConstant>(BECount))
7064 MaxBECount = BECount;
7065 else
7066 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
7067 getConstant(MinStride), false);
7068
7069 if (isa<SCEVCouldNotCompute>(MaxBECount))
7070 MaxBECount = BECount;
7071
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007072 return ExitLimit(BECount, MaxBECount);
Chris Lattner587a75b2005-08-15 23:33:51 +00007073}
7074
Chris Lattnerd934c702004-04-02 20:23:17 +00007075/// getNumIterationsInRange - Return the number of iterations of this loop that
7076/// produce values in the specified constant range. Another way of looking at
7077/// this is that it returns the first iteration number where the value is not in
7078/// the condition, thus computing the exit count. If the iteration count can't
7079/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007080const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00007081 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00007082 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00007083 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007084
7085 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00007086 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00007087 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007088 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00007089 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00007090 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00007091 getNoWrapFlags(FlagNW));
Dan Gohmana30370b2009-05-04 22:02:23 +00007092 if (const SCEVAddRecExpr *ShiftedAddRec =
7093 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00007094 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohmana37eaf22007-10-22 18:31:58 +00007095 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00007096 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00007097 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007098 }
7099
7100 // The only time we can solve this is when we have all constant indices.
7101 // Otherwise, we cannot determine the overflow conditions.
7102 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
7103 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman31efa302009-04-18 17:58:19 +00007104 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007105
7106
7107 // Okay at this point we know that all elements of the chrec are constants and
7108 // that the start element is zero.
7109
7110 // First check to see if the range contains zero. If not, the first
7111 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00007112 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00007113 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman1d2ded72010-05-03 22:09:21 +00007114 return SE.getConstant(getType(), 0);
Misha Brukman01808ca2005-04-21 21:13:18 +00007115
Chris Lattnerd934c702004-04-02 20:23:17 +00007116 if (isAffine()) {
7117 // If this is an affine expression then we have this situation:
7118 // Solve {0,+,A} in Range === Ax in Range
7119
Nick Lewycky52460262007-07-16 02:08:00 +00007120 // We know that zero is in the range. If A is positive then we know that
7121 // the upper value of the range must be the first possible exit value.
7122 // If A is negative then the lower of the range is the last possible loop
7123 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00007124 APInt One(BitWidth,1);
Nick Lewycky52460262007-07-16 02:08:00 +00007125 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
7126 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00007127
Nick Lewycky52460262007-07-16 02:08:00 +00007128 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00007129 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00007130 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00007131
7132 // Evaluate at the exit value. If we really did fall out of the valid
7133 // range, then we computed our trip count, otherwise wrap around or other
7134 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00007135 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007136 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00007137 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007138
7139 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00007140 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00007141 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00007142 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00007143 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00007144 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00007145 } else if (isQuadratic()) {
7146 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
7147 // quadratic equation to solve it. To do this, we must frame our problem in
7148 // terms of figuring out when zero is crossed, instead of when
7149 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00007150 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00007151 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00007152 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
7153 // getNoWrapFlags(FlagNW)
7154 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00007155
7156 // Next, solve the constructed addrec
Dan Gohmanaf752342009-07-07 17:06:11 +00007157 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohmana37eaf22007-10-22 18:31:58 +00007158 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00007159 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7160 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00007161 if (R1) {
7162 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007163 if (ConstantInt *CB =
Owen Anderson487375e2009-07-29 18:55:55 +00007164 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Andersonf1f17432009-07-06 22:37:39 +00007165 R1->getValue(), R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007166 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00007167 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00007168
Chris Lattnerd934c702004-04-02 20:23:17 +00007169 // Make sure the root is not off by one. The returned iteration should
7170 // not be in the range, but the previous one should be. When solving
7171 // for "X*X < 5", for example, we should not return a root of 2.
7172 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00007173 R1->getValue(),
7174 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007175 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007176 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00007177 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00007178 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman01808ca2005-04-21 21:13:18 +00007179
Dan Gohmana37eaf22007-10-22 18:31:58 +00007180 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007181 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00007182 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00007183 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007184 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007185
Chris Lattnerd934c702004-04-02 20:23:17 +00007186 // If R1 was not in the range, then it is a good return value. Make
7187 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00007188 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00007189 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00007190 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007191 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00007192 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00007193 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007194 }
7195 }
7196 }
7197
Dan Gohman31efa302009-04-18 17:58:19 +00007198 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007199}
7200
Sebastian Pop448712b2014-05-07 18:01:20 +00007201namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00007202struct FindUndefs {
7203 bool Found;
7204 FindUndefs() : Found(false) {}
7205
7206 bool follow(const SCEV *S) {
7207 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
7208 if (isa<UndefValue>(C->getValue()))
7209 Found = true;
7210 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
7211 if (isa<UndefValue>(C->getValue()))
7212 Found = true;
7213 }
7214
7215 // Keep looking if we haven't found it yet.
7216 return !Found;
7217 }
7218 bool isDone() const {
7219 // Stop recursion if we have found an undef.
7220 return Found;
7221 }
7222};
7223}
7224
7225// Return true when S contains at least an undef value.
7226static inline bool
7227containsUndefs(const SCEV *S) {
7228 FindUndefs F;
7229 SCEVTraversal<FindUndefs> ST(F);
7230 ST.visitAll(S);
7231
7232 return F.Found;
7233}
7234
7235namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00007236// Collect all steps of SCEV expressions.
7237struct SCEVCollectStrides {
7238 ScalarEvolution &SE;
7239 SmallVectorImpl<const SCEV *> &Strides;
7240
7241 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
7242 : SE(SE), Strides(S) {}
7243
7244 bool follow(const SCEV *S) {
7245 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
7246 Strides.push_back(AR->getStepRecurrence(SE));
7247 return true;
7248 }
7249 bool isDone() const { return false; }
7250};
7251
7252// Collect all SCEVUnknown and SCEVMulExpr expressions.
7253struct SCEVCollectTerms {
7254 SmallVectorImpl<const SCEV *> &Terms;
7255
7256 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
7257 : Terms(T) {}
7258
7259 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00007260 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00007261 if (!containsUndefs(S))
7262 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00007263
7264 // Stop recursion: once we collected a term, do not walk its operands.
7265 return false;
7266 }
7267
7268 // Keep looking.
7269 return true;
7270 }
7271 bool isDone() const { return false; }
7272};
7273}
7274
7275/// Find parametric terms in this SCEVAddRecExpr.
7276void SCEVAddRecExpr::collectParametricTerms(
7277 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
7278 SmallVector<const SCEV *, 4> Strides;
7279 SCEVCollectStrides StrideCollector(SE, Strides);
7280 visitAll(this, StrideCollector);
7281
7282 DEBUG({
7283 dbgs() << "Strides:\n";
7284 for (const SCEV *S : Strides)
7285 dbgs() << *S << "\n";
7286 });
7287
7288 for (const SCEV *S : Strides) {
7289 SCEVCollectTerms TermCollector(Terms);
7290 visitAll(S, TermCollector);
7291 }
7292
7293 DEBUG({
7294 dbgs() << "Terms:\n";
7295 for (const SCEV *T : Terms)
7296 dbgs() << *T << "\n";
7297 });
7298}
7299
Sebastian Popb1a548f2014-05-12 19:01:53 +00007300static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00007301 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00007302 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00007303 int Last = Terms.size() - 1;
7304 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00007305
Sebastian Pop448712b2014-05-07 18:01:20 +00007306 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00007307 if (Last == 0) {
7308 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00007309 SmallVector<const SCEV *, 2> Qs;
7310 for (const SCEV *Op : M->operands())
7311 if (!isa<SCEVConstant>(Op))
7312 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00007313
Sebastian Pope30bd352014-05-27 22:41:56 +00007314 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00007315 }
7316
Sebastian Pope30bd352014-05-27 22:41:56 +00007317 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007318 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00007319 }
7320
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00007321 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00007322 // Normalize the terms before the next call to findArrayDimensionsRec.
7323 const SCEV *Q, *R;
Sebastian Pope30bd352014-05-27 22:41:56 +00007324 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007325
7326 // Bail out when GCD does not evenly divide one of the terms.
7327 if (!R->isZero())
7328 return false;
7329
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00007330 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00007331 }
7332
Tobias Grosser3080cf12014-05-08 07:55:34 +00007333 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00007334 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7335 return isa<SCEVConstant>(E);
7336 }),
7337 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00007338
Sebastian Pop448712b2014-05-07 18:01:20 +00007339 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00007340 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7341 return false;
7342
Sebastian Pope30bd352014-05-27 22:41:56 +00007343 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007344 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00007345}
Sebastian Popc62c6792013-11-12 22:47:20 +00007346
Sebastian Pop448712b2014-05-07 18:01:20 +00007347namespace {
7348struct FindParameter {
7349 bool FoundParameter;
7350 FindParameter() : FoundParameter(false) {}
Sebastian Popc62c6792013-11-12 22:47:20 +00007351
Sebastian Pop448712b2014-05-07 18:01:20 +00007352 bool follow(const SCEV *S) {
7353 if (isa<SCEVUnknown>(S)) {
7354 FoundParameter = true;
7355 // Stop recursion: we found a parameter.
7356 return false;
7357 }
7358 // Keep looking.
7359 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00007360 }
Sebastian Pop448712b2014-05-07 18:01:20 +00007361 bool isDone() const {
7362 // Stop recursion if we have found a parameter.
7363 return FoundParameter;
Sebastian Popc62c6792013-11-12 22:47:20 +00007364 }
Sebastian Popc62c6792013-11-12 22:47:20 +00007365};
7366}
7367
Sebastian Pop448712b2014-05-07 18:01:20 +00007368// Returns true when S contains at least a SCEVUnknown parameter.
7369static inline bool
7370containsParameters(const SCEV *S) {
7371 FindParameter F;
7372 SCEVTraversal<FindParameter> ST(F);
7373 ST.visitAll(S);
7374
7375 return F.FoundParameter;
7376}
7377
7378// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7379static inline bool
7380containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7381 for (const SCEV *T : Terms)
7382 if (containsParameters(T))
7383 return true;
7384 return false;
7385}
7386
7387// Return the number of product terms in S.
7388static inline int numberOfTerms(const SCEV *S) {
7389 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7390 return Expr->getNumOperands();
7391 return 1;
7392}
7393
Sebastian Popa6e58602014-05-27 22:41:45 +00007394static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7395 if (isa<SCEVConstant>(T))
7396 return nullptr;
7397
7398 if (isa<SCEVUnknown>(T))
7399 return T;
7400
7401 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7402 SmallVector<const SCEV *, 2> Factors;
7403 for (const SCEV *Op : M->operands())
7404 if (!isa<SCEVConstant>(Op))
7405 Factors.push_back(Op);
7406
7407 return SE.getMulExpr(Factors);
7408 }
7409
7410 return T;
7411}
7412
7413/// Return the size of an element read or written by Inst.
7414const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7415 Type *Ty;
7416 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7417 Ty = Store->getValueOperand()->getType();
7418 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00007419 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00007420 else
7421 return nullptr;
7422
7423 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7424 return getSizeOfExpr(ETy, Ty);
7425}
7426
Sebastian Pop448712b2014-05-07 18:01:20 +00007427/// Second step of delinearization: compute the array dimensions Sizes from the
7428/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00007429void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7430 SmallVectorImpl<const SCEV *> &Sizes,
7431 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007432
Sebastian Pop53524082014-05-29 19:44:05 +00007433 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00007434 return;
7435
7436 // Early return when Terms do not contain parameters: we do not delinearize
7437 // non parametric SCEVs.
7438 if (!containsParameters(Terms))
7439 return;
7440
7441 DEBUG({
7442 dbgs() << "Terms:\n";
7443 for (const SCEV *T : Terms)
7444 dbgs() << *T << "\n";
7445 });
7446
7447 // Remove duplicates.
7448 std::sort(Terms.begin(), Terms.end());
7449 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7450
7451 // Put larger terms first.
7452 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7453 return numberOfTerms(LHS) > numberOfTerms(RHS);
7454 });
7455
Sebastian Popa6e58602014-05-27 22:41:45 +00007456 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7457
7458 // Divide all terms by the element size.
7459 for (const SCEV *&Term : Terms) {
7460 const SCEV *Q, *R;
7461 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
7462 Term = Q;
7463 }
7464
7465 SmallVector<const SCEV *, 4> NewTerms;
7466
7467 // Remove constant factors.
7468 for (const SCEV *T : Terms)
7469 if (const SCEV *NewT = removeConstantFactors(SE, T))
7470 NewTerms.push_back(NewT);
7471
Sebastian Pop448712b2014-05-07 18:01:20 +00007472 DEBUG({
7473 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00007474 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00007475 dbgs() << *T << "\n";
7476 });
7477
Sebastian Popa6e58602014-05-27 22:41:45 +00007478 if (NewTerms.empty() ||
7479 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00007480 Sizes.clear();
7481 return;
7482 }
Sebastian Pop448712b2014-05-07 18:01:20 +00007483
Sebastian Popa6e58602014-05-27 22:41:45 +00007484 // The last element to be pushed into Sizes is the size of an element.
7485 Sizes.push_back(ElementSize);
7486
Sebastian Pop448712b2014-05-07 18:01:20 +00007487 DEBUG({
7488 dbgs() << "Sizes:\n";
7489 for (const SCEV *S : Sizes)
7490 dbgs() << *S << "\n";
7491 });
7492}
7493
7494/// Third step of delinearization: compute the access functions for the
7495/// Subscripts based on the dimensions in Sizes.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007496void SCEVAddRecExpr::computeAccessFunctions(
Sebastian Pop448712b2014-05-07 18:01:20 +00007497 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7498 SmallVectorImpl<const SCEV *> &Sizes) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007499
Sebastian Popb1a548f2014-05-12 19:01:53 +00007500 // Early exit in case this SCEV is not an affine multivariate function.
7501 if (Sizes.empty() || !this->isAffine())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007502 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007503
Sebastian Pop28e6b972014-05-27 22:41:51 +00007504 const SCEV *Res = this;
Sebastian Pop448712b2014-05-07 18:01:20 +00007505 int Last = Sizes.size() - 1;
7506 for (int i = Last; i >= 0; i--) {
7507 const SCEV *Q, *R;
7508 SCEVDivision::divide(SE, Res, Sizes[i], &Q, &R);
7509
7510 DEBUG({
7511 dbgs() << "Res: " << *Res << "\n";
7512 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7513 dbgs() << "Res divided by Sizes[i]:\n";
7514 dbgs() << "Quotient: " << *Q << "\n";
7515 dbgs() << "Remainder: " << *R << "\n";
7516 });
7517
7518 Res = Q;
7519
Sebastian Popa6e58602014-05-27 22:41:45 +00007520 // Do not record the last subscript corresponding to the size of elements in
7521 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00007522 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00007523
7524 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007525 if (isa<SCEVAddRecExpr>(R)) {
7526 Subscripts.clear();
7527 Sizes.clear();
7528 return;
7529 }
Sebastian Popa6e58602014-05-27 22:41:45 +00007530
Sebastian Pop448712b2014-05-07 18:01:20 +00007531 continue;
7532 }
7533
7534 // Record the access function for the current subscript.
7535 Subscripts.push_back(R);
7536 }
7537
7538 // Also push in last position the remainder of the last division: it will be
7539 // the access function of the innermost dimension.
7540 Subscripts.push_back(Res);
7541
7542 std::reverse(Subscripts.begin(), Subscripts.end());
7543
7544 DEBUG({
7545 dbgs() << "Subscripts:\n";
7546 for (const SCEV *S : Subscripts)
7547 dbgs() << *S << "\n";
7548 });
Sebastian Pop448712b2014-05-07 18:01:20 +00007549}
7550
Sebastian Popc62c6792013-11-12 22:47:20 +00007551/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7552/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00007553/// is the offset start of the array. The SCEV->delinearize algorithm computes
7554/// the multiples of SCEV coefficients: that is a pattern matching of sub
7555/// expressions in the stride and base of a SCEV corresponding to the
7556/// computation of a GCD (greatest common divisor) of base and stride. When
7557/// SCEV->delinearize fails, it returns the SCEV unchanged.
7558///
7559/// For example: when analyzing the memory access A[i][j][k] in this loop nest
7560///
7561/// void foo(long n, long m, long o, double A[n][m][o]) {
7562///
7563/// for (long i = 0; i < n; i++)
7564/// for (long j = 0; j < m; j++)
7565/// for (long k = 0; k < o; k++)
7566/// A[i][j][k] = 1.0;
7567/// }
7568///
7569/// the delinearization input is the following AddRec SCEV:
7570///
7571/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7572///
7573/// From this SCEV, we are able to say that the base offset of the access is %A
7574/// because it appears as an offset that does not divide any of the strides in
7575/// the loops:
7576///
7577/// CHECK: Base offset: %A
7578///
7579/// and then SCEV->delinearize determines the size of some of the dimensions of
7580/// the array as these are the multiples by which the strides are happening:
7581///
7582/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7583///
7584/// Note that the outermost dimension remains of UnknownSize because there are
7585/// no strides that would help identifying the size of the last dimension: when
7586/// the array has been statically allocated, one could compute the size of that
7587/// dimension by dividing the overall size of the array by the size of the known
7588/// dimensions: %m * %o * 8.
7589///
7590/// Finally delinearize provides the access functions for the array reference
7591/// that does correspond to A[i][j][k] of the above C testcase:
7592///
7593/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7594///
7595/// The testcases are checking the output of a function pass:
7596/// DelinearizationPass that walks through all loads and stores of a function
7597/// asking for the SCEV of the memory access with respect to all enclosing
7598/// loops, calling SCEV->delinearize on that and printing the results.
7599
Sebastian Pop28e6b972014-05-27 22:41:51 +00007600void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7601 SmallVectorImpl<const SCEV *> &Subscripts,
7602 SmallVectorImpl<const SCEV *> &Sizes,
7603 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007604 // First step: collect parametric terms.
7605 SmallVector<const SCEV *, 4> Terms;
7606 collectParametricTerms(SE, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00007607
Sebastian Popb1a548f2014-05-12 19:01:53 +00007608 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007609 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007610
Sebastian Pop448712b2014-05-07 18:01:20 +00007611 // Second step: find subscript sizes.
Sebastian Popa6e58602014-05-27 22:41:45 +00007612 SE.findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00007613
Sebastian Popb1a548f2014-05-12 19:01:53 +00007614 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007615 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007616
Sebastian Pop448712b2014-05-07 18:01:20 +00007617 // Third step: compute the access functions for each subscript.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007618 computeAccessFunctions(SE, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00007619
Sebastian Pop28e6b972014-05-27 22:41:51 +00007620 if (Subscripts.empty())
7621 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007622
Sebastian Pop448712b2014-05-07 18:01:20 +00007623 DEBUG({
7624 dbgs() << "succeeded to delinearize " << *this << "\n";
7625 dbgs() << "ArrayDecl[UnknownSize]";
7626 for (const SCEV *S : Sizes)
7627 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00007628
Sebastian Pop444621a2014-05-09 22:45:02 +00007629 dbgs() << "\nArrayRef";
7630 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00007631 dbgs() << "[" << *S << "]";
7632 dbgs() << "\n";
7633 });
Sebastian Popc62c6792013-11-12 22:47:20 +00007634}
Chris Lattnerd934c702004-04-02 20:23:17 +00007635
7636//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00007637// SCEVCallbackVH Class Implementation
7638//===----------------------------------------------------------------------===//
7639
Dan Gohmand33a0902009-05-19 19:22:47 +00007640void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00007641 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00007642 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7643 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007644 SE->ValueExprMap.erase(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00007645 // this now dangles!
7646}
7647
Dan Gohman7a066722010-07-28 01:09:07 +00007648void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00007649 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00007650
Dan Gohman48f82222009-05-04 22:30:44 +00007651 // Forget all the expressions associated with users of the old value,
7652 // so that future queries will recompute the expressions using the new
7653 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00007654 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007655 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00007656 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00007657 while (!Worklist.empty()) {
7658 User *U = Worklist.pop_back_val();
7659 // Deleting the Old value will cause this to dangle. Postpone
7660 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007661 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00007662 continue;
Dan Gohmanf34f8632009-07-14 14:34:04 +00007663 if (!Visited.insert(U))
7664 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00007665 if (PHINode *PN = dyn_cast<PHINode>(U))
7666 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007667 SE->ValueExprMap.erase(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00007668 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00007669 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007670 // Delete the Old value.
7671 if (PHINode *PN = dyn_cast<PHINode>(Old))
7672 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007673 SE->ValueExprMap.erase(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007674 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00007675}
7676
Dan Gohmand33a0902009-05-19 19:22:47 +00007677ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00007678 : CallbackVH(V), SE(se) {}
7679
7680//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00007681// ScalarEvolution Class Implementation
7682//===----------------------------------------------------------------------===//
7683
Dan Gohmanc8e23622009-04-21 23:15:49 +00007684ScalarEvolution::ScalarEvolution()
Craig Topper9f008862014-04-15 04:59:12 +00007685 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7686 BlockDispositions(64), FirstUnknown(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +00007687 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanc8e23622009-04-21 23:15:49 +00007688}
7689
Chris Lattnerd934c702004-04-02 20:23:17 +00007690bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007691 this->F = &F;
Hal Finkel60db0582014-09-07 18:57:58 +00007692 AT = &getAnalysis<AssumptionTracker>();
Dan Gohmanc8e23622009-04-21 23:15:49 +00007693 LI = &getAnalysis<LoopInfo>();
Rafael Espindola93512512014-02-25 17:30:31 +00007694 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +00007695 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +00007696 TLI = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +00007697 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerd934c702004-04-02 20:23:17 +00007698 return false;
7699}
7700
7701void ScalarEvolution::releaseMemory() {
Dan Gohman7cac9572010-08-02 23:49:30 +00007702 // Iterate through all the SCEVUnknown instances and call their
7703 // destructors, so that they release their references to their values.
7704 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7705 U->~SCEVUnknown();
Craig Topper9f008862014-04-15 04:59:12 +00007706 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00007707
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007708 ValueExprMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00007709
7710 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7711 // that a loop had multiple computable exits.
7712 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7713 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7714 I != E; ++I) {
7715 I->second.clear();
7716 }
7717
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007718 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7719
Dan Gohmanc8e23622009-04-21 23:15:49 +00007720 BackedgeTakenCounts.clear();
7721 ConstantEvolutionLoopExitValue.clear();
Dan Gohman5122d612009-05-08 20:47:27 +00007722 ValuesAtScopes.clear();
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007723 LoopDispositions.clear();
Dan Gohman8ea83d82010-11-18 00:34:22 +00007724 BlockDispositions.clear();
Dan Gohman761065e2010-11-17 02:44:44 +00007725 UnsignedRanges.clear();
7726 SignedRanges.clear();
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007727 UniqueSCEVs.clear();
7728 SCEVAllocator.Reset();
Chris Lattnerd934c702004-04-02 20:23:17 +00007729}
7730
7731void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
7732 AU.setPreservesAll();
Hal Finkel60db0582014-09-07 18:57:58 +00007733 AU.addRequired<AssumptionTracker>();
Chris Lattnerd934c702004-04-02 20:23:17 +00007734 AU.addRequiredTransitive<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +00007735 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +00007736 AU.addRequired<TargetLibraryInfo>();
Dan Gohman0a40ad92009-04-16 03:18:22 +00007737}
7738
Dan Gohmanc8e23622009-04-21 23:15:49 +00007739bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00007740 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00007741}
7742
Dan Gohmanc8e23622009-04-21 23:15:49 +00007743static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00007744 const Loop *L) {
7745 // Print all inner loops first
7746 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
7747 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00007748
Dan Gohmanbc694912010-01-09 18:17:45 +00007749 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007750 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007751 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00007752
Dan Gohmancb0efec2009-12-18 01:14:11 +00007753 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00007754 L->getExitBlocks(ExitBlocks);
7755 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00007756 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00007757
Dan Gohman0bddac12009-02-24 18:55:53 +00007758 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
7759 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007760 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00007761 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00007762 }
7763
Dan Gohmanbc694912010-01-09 18:17:45 +00007764 OS << "\n"
7765 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007766 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007767 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00007768
7769 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
7770 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
7771 } else {
7772 OS << "Unpredictable max backedge-taken count. ";
7773 }
7774
7775 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00007776}
7777
Dan Gohmancb0efec2009-12-18 01:14:11 +00007778void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00007779 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00007780 // out SCEV values of all instructions that are interesting. Doing
7781 // this potentially causes it to create new SCEV objects though,
7782 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00007783 // observable from outside the class though, so casting away the
7784 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00007785 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007786
Dan Gohmanbc694912010-01-09 18:17:45 +00007787 OS << "Classifying expressions for: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007788 F->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007789 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00007790 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand18dc2c2010-05-03 17:03:23 +00007791 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanfda3c4a2009-07-13 23:03:05 +00007792 OS << *I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00007793 OS << " --> ";
Dan Gohmanaf752342009-07-07 17:06:11 +00007794 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattnerd934c702004-04-02 20:23:17 +00007795 SV->print(OS);
Misha Brukman01808ca2005-04-21 21:13:18 +00007796
Dan Gohmanb9063a82009-06-19 17:49:54 +00007797 const Loop *L = LI->getLoopFor((*I).getParent());
7798
Dan Gohmanaf752342009-07-07 17:06:11 +00007799 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00007800 if (AtUse != SV) {
7801 OS << " --> ";
7802 AtUse->print(OS);
7803 }
7804
7805 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00007806 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00007807 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00007808 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007809 OS << "<<Unknown>>";
7810 } else {
7811 OS << *ExitValue;
7812 }
7813 }
7814
Chris Lattnerd934c702004-04-02 20:23:17 +00007815 OS << "\n";
7816 }
7817
Dan Gohmanbc694912010-01-09 18:17:45 +00007818 OS << "Determining loop execution counts for: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007819 F->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007820 OS << "\n";
Dan Gohmanc8e23622009-04-21 23:15:49 +00007821 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
7822 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00007823}
Dan Gohmane20f8242009-04-21 00:47:46 +00007824
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007825ScalarEvolution::LoopDisposition
7826ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007827 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values = LoopDispositions[S];
7828 for (unsigned u = 0; u < Values.size(); u++) {
7829 if (Values[u].first == L)
7830 return Values[u].second;
7831 }
7832 Values.push_back(std::make_pair(L, LoopVariant));
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007833 LoopDisposition D = computeLoopDisposition(S, L);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007834 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values2 = LoopDispositions[S];
7835 for (unsigned u = Values2.size(); u > 0; u--) {
7836 if (Values2[u - 1].first == L) {
7837 Values2[u - 1].second = D;
7838 break;
7839 }
7840 }
7841 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007842}
7843
7844ScalarEvolution::LoopDisposition
7845ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00007846 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00007847 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007848 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007849 case scTruncate:
7850 case scZeroExtend:
7851 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007852 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00007853 case scAddRecExpr: {
7854 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7855
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007856 // If L is the addrec's loop, it's computable.
7857 if (AR->getLoop() == L)
7858 return LoopComputable;
7859
Dan Gohmanafd6db92010-11-17 21:23:15 +00007860 // Add recurrences are never invariant in the function-body (null loop).
7861 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007862 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007863
7864 // This recurrence is variant w.r.t. L if L contains AR's loop.
7865 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007866 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007867
7868 // This recurrence is invariant w.r.t. L if AR's loop contains L.
7869 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007870 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007871
7872 // This recurrence is variant w.r.t. L if any of its operands
7873 // are variant.
7874 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
7875 I != E; ++I)
7876 if (!isLoopInvariant(*I, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007877 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007878
7879 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007880 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007881 }
7882 case scAddExpr:
7883 case scMulExpr:
7884 case scUMaxExpr:
7885 case scSMaxExpr: {
7886 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohmanafd6db92010-11-17 21:23:15 +00007887 bool HasVarying = false;
7888 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
7889 I != E; ++I) {
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007890 LoopDisposition D = getLoopDisposition(*I, L);
7891 if (D == LoopVariant)
7892 return LoopVariant;
7893 if (D == LoopComputable)
7894 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007895 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007896 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007897 }
7898 case scUDivExpr: {
7899 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007900 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
7901 if (LD == LoopVariant)
7902 return LoopVariant;
7903 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
7904 if (RD == LoopVariant)
7905 return LoopVariant;
7906 return (LD == LoopInvariant && RD == LoopInvariant) ?
7907 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007908 }
7909 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007910 // All non-instruction values are loop invariant. All instructions are loop
7911 // invariant if they are not contained in the specified loop.
7912 // Instructions are never considered invariant in the function body
7913 // (null loop) because they are defined within the "loop".
7914 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
7915 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
7916 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007917 case scCouldNotCompute:
7918 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00007919 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00007920 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007921}
7922
7923bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
7924 return getLoopDisposition(S, L) == LoopInvariant;
7925}
7926
7927bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
7928 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007929}
Dan Gohman20d9ce22010-11-17 21:41:58 +00007930
Dan Gohman8ea83d82010-11-18 00:34:22 +00007931ScalarEvolution::BlockDisposition
7932ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007933 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values = BlockDispositions[S];
7934 for (unsigned u = 0; u < Values.size(); u++) {
7935 if (Values[u].first == BB)
7936 return Values[u].second;
7937 }
7938 Values.push_back(std::make_pair(BB, DoesNotDominateBlock));
Dan Gohman8ea83d82010-11-18 00:34:22 +00007939 BlockDisposition D = computeBlockDisposition(S, BB);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007940 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values2 = BlockDispositions[S];
7941 for (unsigned u = Values2.size(); u > 0; u--) {
7942 if (Values2[u - 1].first == BB) {
7943 Values2[u - 1].second = D;
7944 break;
7945 }
7946 }
7947 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007948}
7949
Dan Gohman8ea83d82010-11-18 00:34:22 +00007950ScalarEvolution::BlockDisposition
7951ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00007952 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00007953 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00007954 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007955 case scTruncate:
7956 case scZeroExtend:
7957 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00007958 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00007959 case scAddRecExpr: {
7960 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00007961 // to test for proper dominance too, because the instruction which
7962 // produces the addrec's value is a PHI, and a PHI effectively properly
7963 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00007964 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7965 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00007966 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007967 }
7968 // FALL THROUGH into SCEVNAryExpr handling.
7969 case scAddExpr:
7970 case scMulExpr:
7971 case scUMaxExpr:
7972 case scSMaxExpr: {
7973 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00007974 bool Proper = true;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007975 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman8ea83d82010-11-18 00:34:22 +00007976 I != E; ++I) {
7977 BlockDisposition D = getBlockDisposition(*I, BB);
7978 if (D == DoesNotDominateBlock)
7979 return DoesNotDominateBlock;
7980 if (D == DominatesBlock)
7981 Proper = false;
7982 }
7983 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007984 }
7985 case scUDivExpr: {
7986 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00007987 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
7988 BlockDisposition LD = getBlockDisposition(LHS, BB);
7989 if (LD == DoesNotDominateBlock)
7990 return DoesNotDominateBlock;
7991 BlockDisposition RD = getBlockDisposition(RHS, BB);
7992 if (RD == DoesNotDominateBlock)
7993 return DoesNotDominateBlock;
7994 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
7995 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007996 }
7997 case scUnknown:
7998 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00007999 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
8000 if (I->getParent() == BB)
8001 return DominatesBlock;
8002 if (DT->properlyDominates(I->getParent(), BB))
8003 return ProperlyDominatesBlock;
8004 return DoesNotDominateBlock;
8005 }
8006 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008007 case scCouldNotCompute:
8008 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00008009 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00008010 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00008011}
8012
8013bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
8014 return getBlockDisposition(S, BB) >= DominatesBlock;
8015}
8016
8017bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
8018 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008019}
Dan Gohman534749b2010-11-17 22:27:42 +00008020
Andrew Trick365e31c2012-07-13 23:33:03 +00008021namespace {
8022// Search for a SCEV expression node within an expression tree.
8023// Implements SCEVTraversal::Visitor.
8024struct SCEVSearch {
8025 const SCEV *Node;
8026 bool IsFound;
8027
8028 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
8029
8030 bool follow(const SCEV *S) {
8031 IsFound |= (S == Node);
8032 return !IsFound;
8033 }
8034 bool isDone() const { return IsFound; }
8035};
8036}
8037
Dan Gohman534749b2010-11-17 22:27:42 +00008038bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Andrew Trick365e31c2012-07-13 23:33:03 +00008039 SCEVSearch Search(Op);
8040 visitAll(S, Search);
8041 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00008042}
Dan Gohman7e6b3932010-11-17 23:28:48 +00008043
8044void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8045 ValuesAtScopes.erase(S);
8046 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00008047 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00008048 UnsignedRanges.erase(S);
8049 SignedRanges.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00008050
8051 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8052 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8053 BackedgeTakenInfo &BEInfo = I->second;
8054 if (BEInfo.hasOperand(S, this)) {
8055 BEInfo.clear();
8056 BackedgeTakenCounts.erase(I++);
8057 }
8058 else
8059 ++I;
8060 }
Dan Gohman7e6b3932010-11-17 23:28:48 +00008061}
Benjamin Kramer214935e2012-10-26 17:31:32 +00008062
8063typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008064
Alp Tokercb402912014-01-24 17:20:08 +00008065/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008066static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8067 size_t Pos = 0;
8068 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8069 Str.replace(Pos, From.size(), To.data(), To.size());
8070 Pos += To.size();
8071 }
8072}
8073
Benjamin Kramer214935e2012-10-26 17:31:32 +00008074/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8075static void
8076getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8077 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8078 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8079
8080 std::string &S = Map[L];
8081 if (S.empty()) {
8082 raw_string_ostream OS(S);
8083 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008084
8085 // false and 0 are semantically equivalent. This can happen in dead loops.
8086 replaceSubString(OS.str(), "false", "0");
8087 // Remove wrap flags, their use in SCEV is highly fragile.
8088 // FIXME: Remove this when SCEV gets smarter about them.
8089 replaceSubString(OS.str(), "<nw>", "");
8090 replaceSubString(OS.str(), "<nsw>", "");
8091 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00008092 }
8093 }
8094}
8095
8096void ScalarEvolution::verifyAnalysis() const {
8097 if (!VerifySCEV)
8098 return;
8099
8100 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8101
8102 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8103 // FIXME: It would be much better to store actual values instead of strings,
8104 // but SCEV pointers will change if we drop the caches.
8105 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8106 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8107 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8108
8109 // Gather stringified backedge taken counts for all loops without using
8110 // SCEV's caches.
8111 SE.releaseMemory();
8112 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8113 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8114
8115 // Now compare whether they're the same with and without caches. This allows
8116 // verifying that no pass changed the cache.
8117 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8118 "New loops suddenly appeared!");
8119
8120 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8121 OldE = BackedgeDumpsOld.end(),
8122 NewI = BackedgeDumpsNew.begin();
8123 OldI != OldE; ++OldI, ++NewI) {
8124 assert(OldI->first == NewI->first && "Loop order changed!");
8125
8126 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8127 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008128 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00008129 // means that a pass is buggy or SCEV has to learn a new pattern but is
8130 // usually not harmful.
8131 if (OldI->second != NewI->second &&
8132 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008133 NewI->second.find("undef") == std::string::npos &&
8134 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00008135 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008136 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00008137 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008138 << "' changed from '" << OldI->second
8139 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00008140 std::abort();
8141 }
8142 }
8143
8144 // TODO: Verify more things.
8145}