blob: bd747f7c0b7a107cefcd21a5b792a6dd29e740e8 [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"
Sanjoy Dasc46bceb2016-09-27 18:01:42 +000064#include "llvm/ADT/ScopeExit.h"
Sanjoy Das17078692016-10-31 03:32:43 +000065#include "llvm/ADT/Sequence.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000068#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000069#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000070#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000071#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000072#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000073#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000074#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000075#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000076#include "llvm/IR/Constants.h"
77#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000079#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000080#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000081#include "llvm/IR/GlobalAlias.h"
82#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000083#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000084#include "llvm/IR/Instructions.h"
85#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000086#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000087#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000088#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000089#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000090#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000091#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000092#include "llvm/Support/KnownBits.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000093#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000094#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000095#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000096#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000097using namespace llvm;
98
Chandler Carruthf1221bd2014-04-22 02:48:03 +000099#define DEBUG_TYPE "scalar-evolution"
100
Chris Lattner57ef9422006-12-19 22:30:33 +0000101STATISTIC(NumArrayLenItCounts,
102 "Number of trip counts computed with array length");
103STATISTIC(NumTripCountsComputed,
104 "Number of loops with predictable loop counts");
105STATISTIC(NumTripCountsNotComputed,
106 "Number of loops without predictable loop counts");
107STATISTIC(NumBruteForceTripCountsComputed,
108 "Number of loops with trip counts computed by force");
109
Dan Gohmand78c4002008-05-13 00:00:25 +0000110static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000111MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
112 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000113 "symbolically execute a constant "
114 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000115 cl::init(100));
116
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000117// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
Sanjoy Das0cdcdf02017-04-24 02:35:19 +0000118static cl::opt<bool>
119VerifySCEV("verify-scev",
120 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000121static cl::opt<bool>
122 VerifySCEVMap("verify-scev-maps",
Jeroen Ketemae48e3932016-04-12 23:21:46 +0000123 cl::desc("Verify no dangling value in ScalarEvolution's "
Wei Mia49559b2016-02-04 01:27:38 +0000124 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000125
Li Huangfcfe8cd2016-10-20 21:38:39 +0000126static cl::opt<unsigned> MulOpsInlineThreshold(
127 "scev-mulops-inline-threshold", cl::Hidden,
128 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
129 cl::init(1000));
130
Daniil Fukalovb09dac52017-01-26 13:33:17 +0000131static cl::opt<unsigned> AddOpsInlineThreshold(
132 "scev-addops-inline-threshold", cl::Hidden,
133 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
134 cl::init(500));
135
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000136static cl::opt<unsigned> MaxSCEVCompareDepth(
137 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
138 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
139 cl::init(32));
140
Max Kazantsev2e44d292017-03-31 12:05:30 +0000141static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
142 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
143 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
144 cl::init(2));
145
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000146static cl::opt<unsigned> MaxValueCompareDepth(
147 "scalar-evolution-max-value-compare-depth", cl::Hidden,
148 cl::desc("Maximum depth of recursive value complexity comparisons"),
149 cl::init(2));
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000150
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000151static cl::opt<unsigned>
152 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
153 cl::desc("Maximum depth of recursive AddExpr"),
154 cl::init(32));
155
Michael Liao468fb742017-01-13 18:28:30 +0000156static cl::opt<unsigned> MaxConstantEvolvingDepth(
157 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
158 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
159
Chris Lattnerd934c702004-04-02 20:23:17 +0000160//===----------------------------------------------------------------------===//
161// SCEV class definitions
162//===----------------------------------------------------------------------===//
163
164//===----------------------------------------------------------------------===//
165// Implementation of the SCEV class.
166//
Dan Gohman3423e722009-06-30 20:13:32 +0000167
Matthias Braun8c209aa2017-01-28 02:02:38 +0000168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
169LLVM_DUMP_METHOD void SCEV::dump() const {
Davide Italiano2071f4c2015-10-25 19:55:24 +0000170 print(dbgs());
171 dbgs() << '\n';
172}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000173#endif
Davide Italiano2071f4c2015-10-25 19:55:24 +0000174
Dan Gohman534749b2010-11-17 22:27:42 +0000175void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000176 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000177 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000178 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000179 return;
180 case scTruncate: {
181 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
182 const SCEV *Op = Trunc->getOperand();
183 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
184 << *Trunc->getType() << ")";
185 return;
186 }
187 case scZeroExtend: {
188 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
189 const SCEV *Op = ZExt->getOperand();
190 OS << "(zext " << *Op->getType() << " " << *Op << " to "
191 << *ZExt->getType() << ")";
192 return;
193 }
194 case scSignExtend: {
195 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
196 const SCEV *Op = SExt->getOperand();
197 OS << "(sext " << *Op->getType() << " " << *Op << " to "
198 << *SExt->getType() << ")";
199 return;
200 }
201 case scAddRecExpr: {
202 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
203 OS << "{" << *AR->getOperand(0);
204 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
205 OS << ",+," << *AR->getOperand(i);
206 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000207 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000208 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000209 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000210 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000211 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000212 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
213 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000214 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000215 OS << ">";
216 return;
217 }
218 case scAddExpr:
219 case scMulExpr:
220 case scUMaxExpr:
221 case scSMaxExpr: {
222 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000223 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000224 switch (NAry->getSCEVType()) {
225 case scAddExpr: OpStr = " + "; break;
226 case scMulExpr: OpStr = " * "; break;
227 case scUMaxExpr: OpStr = " umax "; break;
228 case scSMaxExpr: OpStr = " smax "; break;
229 }
230 OS << "(";
231 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
232 I != E; ++I) {
233 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000234 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000235 OS << OpStr;
236 }
237 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000238 switch (NAry->getSCEVType()) {
239 case scAddExpr:
240 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000241 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000242 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000243 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000244 OS << "<nsw>";
245 }
Dan Gohman534749b2010-11-17 22:27:42 +0000246 return;
247 }
248 case scUDivExpr: {
249 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
250 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
251 return;
252 }
253 case scUnknown: {
254 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000255 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000256 if (U->isSizeOf(AllocTy)) {
257 OS << "sizeof(" << *AllocTy << ")";
258 return;
259 }
260 if (U->isAlignOf(AllocTy)) {
261 OS << "alignof(" << *AllocTy << ")";
262 return;
263 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000264
Chris Lattner229907c2011-07-18 04:54:35 +0000265 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000266 Constant *FieldNo;
267 if (U->isOffsetOf(CTy, FieldNo)) {
268 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000269 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000270 OS << ")";
271 return;
272 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000273
Dan Gohman534749b2010-11-17 22:27:42 +0000274 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000275 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000276 return;
277 }
278 case scCouldNotCompute:
279 OS << "***COULDNOTCOMPUTE***";
280 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000281 }
282 llvm_unreachable("Unknown SCEV kind!");
283}
284
Chris Lattner229907c2011-07-18 04:54:35 +0000285Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000286 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000287 case scConstant:
288 return cast<SCEVConstant>(this)->getType();
289 case scTruncate:
290 case scZeroExtend:
291 case scSignExtend:
292 return cast<SCEVCastExpr>(this)->getType();
293 case scAddRecExpr:
294 case scMulExpr:
295 case scUMaxExpr:
296 case scSMaxExpr:
297 return cast<SCEVNAryExpr>(this)->getType();
298 case scAddExpr:
299 return cast<SCEVAddExpr>(this)->getType();
300 case scUDivExpr:
301 return cast<SCEVUDivExpr>(this)->getType();
302 case scUnknown:
303 return cast<SCEVUnknown>(this)->getType();
304 case scCouldNotCompute:
305 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000306 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000307 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000308}
309
Dan Gohmanbe928e32008-06-18 16:23:07 +0000310bool SCEV::isZero() const {
311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
312 return SC->getValue()->isZero();
313 return false;
314}
315
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000316bool SCEV::isOne() const {
317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
318 return SC->getValue()->isOne();
319 return false;
320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Dan Gohman18a96bb2009-06-24 00:30:26 +0000322bool SCEV::isAllOnesValue() const {
323 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
324 return SC->getValue()->isAllOnesValue();
325 return false;
326}
327
Andrew Trick881a7762012-01-07 00:27:31 +0000328bool SCEV::isNonConstantNegative() const {
329 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
330 if (!Mul) return false;
331
332 // If there is a constant factor, it will be first.
333 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
334 if (!SC) return false;
335
336 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000337 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000338}
339
Owen Anderson04052ec2009-06-22 21:57:23 +0000340SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000341 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000342
Chris Lattnerd934c702004-04-02 20:23:17 +0000343bool SCEVCouldNotCompute::classof(const SCEV *S) {
344 return S->getSCEVType() == scCouldNotCompute;
345}
346
Dan Gohmanaf752342009-07-07 17:06:11 +0000347const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000348 FoldingSetNodeID ID;
349 ID.AddInteger(scConstant);
350 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000351 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000352 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000353 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000354 UniqueSCEVs.InsertNode(S, IP);
355 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000356}
Chris Lattnerd934c702004-04-02 20:23:17 +0000357
Nick Lewycky31eaca52014-01-27 10:04:03 +0000358const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000359 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000360}
361
Dan Gohmanaf752342009-07-07 17:06:11 +0000362const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000363ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
364 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000365 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000366}
367
Dan Gohman24ceda82010-06-18 19:54:20 +0000368SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000369 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000370 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000371
Dan Gohman24ceda82010-06-18 19:54:20 +0000372SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000373 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000374 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000375 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
376 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000377 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000378}
Chris Lattnerd934c702004-04-02 20:23:17 +0000379
Dan Gohman24ceda82010-06-18 19:54:20 +0000380SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000381 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000382 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000383 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
384 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000385 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000386}
387
Dan Gohman24ceda82010-06-18 19:54:20 +0000388SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000389 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000390 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000391 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
392 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000393 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000394}
395
Dan Gohman7cac9572010-08-02 23:49:30 +0000396void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000397 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000398 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000399
400 // Remove this SCEVUnknown from the uniquing map.
401 SE->UniqueSCEVs.RemoveNode(this);
402
403 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000404 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000405}
406
407void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000408 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000409 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000410
411 // Remove this SCEVUnknown from the uniquing map.
412 SE->UniqueSCEVs.RemoveNode(this);
413
414 // Update this SCEVUnknown to point to the new value. This is needed
415 // because there may still be outstanding SCEVs which still point to
416 // this SCEVUnknown.
417 setValPtr(New);
418}
419
Chris Lattner229907c2011-07-18 04:54:35 +0000420bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000421 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000422 if (VCE->getOpcode() == Instruction::PtrToInt)
423 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000424 if (CE->getOpcode() == Instruction::GetElementPtr &&
425 CE->getOperand(0)->isNullValue() &&
426 CE->getNumOperands() == 2)
427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
428 if (CI->isOne()) {
429 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
430 ->getElementType();
431 return true;
432 }
Dan Gohmancf913832010-01-28 02:15:55 +0000433
434 return false;
435}
436
Chris Lattner229907c2011-07-18 04:54:35 +0000437bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000438 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000439 if (VCE->getOpcode() == Instruction::PtrToInt)
440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000441 if (CE->getOpcode() == Instruction::GetElementPtr &&
442 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000443 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000444 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000445 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000446 if (!STy->isPacked() &&
447 CE->getNumOperands() == 3 &&
448 CE->getOperand(1)->isNullValue()) {
449 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
450 if (CI->isOne() &&
451 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000452 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000453 AllocTy = STy->getElementType(1);
454 return true;
455 }
456 }
457 }
Dan Gohmancf913832010-01-28 02:15:55 +0000458
459 return false;
460}
461
Chris Lattner229907c2011-07-18 04:54:35 +0000462bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000463 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000464 if (VCE->getOpcode() == Instruction::PtrToInt)
465 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
466 if (CE->getOpcode() == Instruction::GetElementPtr &&
467 CE->getNumOperands() == 3 &&
468 CE->getOperand(0)->isNullValue() &&
469 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000470 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000471 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
472 // Ignore vector types here so that ScalarEvolutionExpander doesn't
473 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000474 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000475 CTy = Ty;
476 FieldNo = CE->getOperand(2);
477 return true;
478 }
479 }
480
481 return false;
482}
483
Chris Lattnereb3e8402004-06-20 06:23:15 +0000484//===----------------------------------------------------------------------===//
485// SCEV Utilities
486//===----------------------------------------------------------------------===//
487
Sanjoy Das17078692016-10-31 03:32:43 +0000488/// Compare the two values \p LV and \p RV in terms of their "complexity" where
489/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
490/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
491/// have been previously deemed to be "equally complex" by this routine. It is
492/// intended to avoid exponential time complexity in cases like:
493///
494/// %a = f(%x, %y)
495/// %b = f(%a, %a)
496/// %c = f(%b, %b)
497///
498/// %d = f(%x, %y)
499/// %e = f(%d, %d)
500/// %f = f(%e, %e)
501///
502/// CompareValueComplexity(%f, %c)
503///
504/// Since we do not continue running this routine on expression trees once we
505/// have seen unequal values, there is no need to track them in the cache.
506static int
507CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
508 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000509 unsigned Depth) {
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000510 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000511 return 0;
512
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000513 // Order pointer values after integer values. This helps SCEVExpander form
514 // GEPs.
515 bool LIsPointer = LV->getType()->isPointerTy(),
516 RIsPointer = RV->getType()->isPointerTy();
517 if (LIsPointer != RIsPointer)
518 return (int)LIsPointer - (int)RIsPointer;
519
520 // Compare getValueID values.
521 unsigned LID = LV->getValueID(), RID = RV->getValueID();
522 if (LID != RID)
523 return (int)LID - (int)RID;
524
525 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000526 if (const auto *LA = dyn_cast<Argument>(LV)) {
527 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000528 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
529 return (int)LArgNo - (int)RArgNo;
530 }
531
Sanjoy Das299e6722016-10-30 23:52:56 +0000532 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
533 const auto *RGV = cast<GlobalValue>(RV);
534
535 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
536 auto LT = GV->getLinkage();
537 return !(GlobalValue::isPrivateLinkage(LT) ||
538 GlobalValue::isInternalLinkage(LT));
539 };
540
541 // Use the names to distinguish the two values, but only if the
542 // names are semantically important.
543 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
544 return LGV->getName().compare(RGV->getName());
545 }
546
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000547 // For instructions, compare their loop depth, and their operand count. This
548 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000549 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
550 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000551
552 // Compare loop depths.
553 const BasicBlock *LParent = LInst->getParent(),
554 *RParent = RInst->getParent();
555 if (LParent != RParent) {
556 unsigned LDepth = LI->getLoopDepth(LParent),
557 RDepth = LI->getLoopDepth(RParent);
558 if (LDepth != RDepth)
559 return (int)LDepth - (int)RDepth;
560 }
561
562 // Compare the number of operands.
563 unsigned LNumOps = LInst->getNumOperands(),
564 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000565 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000566 return (int)LNumOps - (int)RNumOps;
567
Sanjoy Das17078692016-10-31 03:32:43 +0000568 for (unsigned Idx : seq(0u, LNumOps)) {
569 int Result =
570 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000571 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000572 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000573 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000574 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000575 }
576
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000577 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000578 return 0;
579}
580
Sanjoy Das237c8452016-09-27 18:01:48 +0000581// Return negative, zero, or positive, if LHS is less than, equal to, or greater
582// than RHS, respectively. A three-way result allows recursive comparisons to be
583// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000584static int CompareSCEVComplexity(
585 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
586 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
587 unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000588 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
589 if (LHS == RHS)
590 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000591
Sanjoy Das237c8452016-09-27 18:01:48 +0000592 // Primarily, sort the SCEVs by their getSCEVType().
593 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
594 if (LType != RType)
595 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000596
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000597 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000598 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000599 // Aside from the getSCEVType() ordering, the particular ordering
600 // isn't very important except that it's beneficial to be consistent,
601 // so that (a + b) and (b + a) don't end up as different expressions.
602 switch (static_cast<SCEVTypes>(LType)) {
603 case scUnknown: {
604 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
605 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000606
Sanjoy Das17078692016-10-31 03:32:43 +0000607 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000608 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
609 Depth + 1);
610 if (X == 0)
611 EqCacheSCEV.insert({LHS, RHS});
612 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000613 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000614
Sanjoy Das237c8452016-09-27 18:01:48 +0000615 case scConstant: {
616 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
617 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
618
619 // Compare constant values.
620 const APInt &LA = LC->getAPInt();
621 const APInt &RA = RC->getAPInt();
622 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
623 if (LBitWidth != RBitWidth)
624 return (int)LBitWidth - (int)RBitWidth;
625 return LA.ult(RA) ? -1 : 1;
626 }
627
628 case scAddRecExpr: {
629 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
630 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
631
632 // Compare addrec loop depths.
633 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
634 if (LLoop != RLoop) {
635 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
636 if (LDepth != RDepth)
637 return (int)LDepth - (int)RDepth;
638 }
639
640 // Addrec complexity grows with operand count.
641 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
642 if (LNumOps != RNumOps)
643 return (int)LNumOps - (int)RNumOps;
644
645 // Lexicographically compare.
646 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000647 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
648 RA->getOperand(i), Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000649 if (X != 0)
650 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000651 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000652 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000653 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000654 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000655
656 case scAddExpr:
657 case scMulExpr:
658 case scSMaxExpr:
659 case scUMaxExpr: {
660 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
661 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
662
663 // Lexicographically compare n-ary expressions.
664 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
665 if (LNumOps != RNumOps)
666 return (int)LNumOps - (int)RNumOps;
667
668 for (unsigned i = 0; i != LNumOps; ++i) {
669 if (i >= RNumOps)
670 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000671 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
672 RC->getOperand(i), Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000673 if (X != 0)
674 return X;
675 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000676 EqCacheSCEV.insert({LHS, RHS});
677 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000678 }
679
680 case scUDivExpr: {
681 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
682 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
683
684 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000685 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
686 Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000687 if (X != 0)
688 return X;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000689 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
690 Depth + 1);
691 if (X == 0)
692 EqCacheSCEV.insert({LHS, RHS});
693 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000694 }
695
696 case scTruncate:
697 case scZeroExtend:
698 case scSignExtend: {
699 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
700 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
701
702 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000703 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
704 RC->getOperand(), Depth + 1);
705 if (X == 0)
706 EqCacheSCEV.insert({LHS, RHS});
707 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000708 }
709
710 case scCouldNotCompute:
711 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
712 }
713 llvm_unreachable("Unknown SCEV kind!");
714}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000715
Sanjoy Dasf8570812016-05-29 00:38:22 +0000716/// Given a list of SCEV objects, order them by their complexity, and group
717/// objects of the same complexity together by value. When this routine is
718/// finished, we know that any duplicates in the vector are consecutive and that
719/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000720///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000721/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000722/// results from this routine. In other words, we don't want the results of
723/// this to depend on where the addresses of various SCEV objects happened to
724/// land in memory.
725///
Dan Gohmanaf752342009-07-07 17:06:11 +0000726static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000727 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000728 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000729
730 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000731 if (Ops.size() == 2) {
732 // This is the common case, which also happens to be trivially simple.
733 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000734 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000735 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000736 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000737 return;
738 }
739
Dan Gohman24ceda82010-06-18 19:54:20 +0000740 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000741 std::stable_sort(Ops.begin(), Ops.end(),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000742 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
743 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000744 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000745
746 // Now that we are sorted by complexity, group elements of the same
747 // complexity. Note that this is, at worst, N^2, but the vector is likely to
748 // be extremely short in practice. Note that we take this approach because we
749 // do not want to depend on the addresses of the objects we are grouping.
750 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
751 const SCEV *S = Ops[i];
752 unsigned Complexity = S->getSCEVType();
753
754 // If there are any objects of the same complexity and same value as this
755 // one, group them.
756 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
757 if (Ops[j] == S) { // Found a duplicate.
758 // Move it to immediately after i'th element.
759 std::swap(Ops[i+1], Ops[j]);
760 ++i; // no need to rescan it.
761 if (i == e-2) return; // Done!
762 }
763 }
764 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000765}
766
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000767// Returns the size of the SCEV S.
768static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000769 struct FindSCEVSize {
770 int Size;
771 FindSCEVSize() : Size(0) {}
772
773 bool follow(const SCEV *S) {
774 ++Size;
775 // Keep looking at all operands of S.
776 return true;
777 }
778 bool isDone() const {
779 return false;
780 }
781 };
782
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000783 FindSCEVSize F;
784 SCEVTraversal<FindSCEVSize> ST(F);
785 ST.visitAll(S);
786 return F.Size;
787}
788
789namespace {
790
David Majnemer4e879362014-12-14 09:12:33 +0000791struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000792public:
793 // Computes the Quotient and Remainder of the division of Numerator by
794 // Denominator.
795 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
796 const SCEV *Denominator, const SCEV **Quotient,
797 const SCEV **Remainder) {
798 assert(Numerator && Denominator && "Uninitialized SCEV");
799
David Majnemer4e879362014-12-14 09:12:33 +0000800 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000801
802 // Check for the trivial case here to avoid having to check for it in the
803 // rest of the code.
804 if (Numerator == Denominator) {
805 *Quotient = D.One;
806 *Remainder = D.Zero;
807 return;
808 }
809
810 if (Numerator->isZero()) {
811 *Quotient = D.Zero;
812 *Remainder = D.Zero;
813 return;
814 }
815
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000816 // A simple case when N/1. The quotient is N.
817 if (Denominator->isOne()) {
818 *Quotient = Numerator;
819 *Remainder = D.Zero;
820 return;
821 }
822
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000823 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000824 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000825 const SCEV *Q, *R;
826 *Quotient = Numerator;
827 for (const SCEV *Op : T->operands()) {
828 divide(SE, *Quotient, Op, &Q, &R);
829 *Quotient = Q;
830
831 // Bail out when the Numerator is not divisible by one of the terms of
832 // the Denominator.
833 if (!R->isZero()) {
834 *Quotient = D.Zero;
835 *Remainder = Numerator;
836 return;
837 }
838 }
839 *Remainder = D.Zero;
840 return;
841 }
842
843 D.visit(Numerator);
844 *Quotient = D.Quotient;
845 *Remainder = D.Remainder;
846 }
847
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000848 // Except in the trivial case described above, we do not know how to divide
849 // Expr by Denominator for the following functions with empty implementation.
850 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
851 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
852 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
853 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
854 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
855 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
856 void visitUnknown(const SCEVUnknown *Numerator) {}
857 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
858
David Majnemer4e879362014-12-14 09:12:33 +0000859 void visitConstant(const SCEVConstant *Numerator) {
860 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000861 APInt NumeratorVal = Numerator->getAPInt();
862 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000863 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
864 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
865
866 if (NumeratorBW > DenominatorBW)
867 DenominatorVal = DenominatorVal.sext(NumeratorBW);
868 else if (NumeratorBW < DenominatorBW)
869 NumeratorVal = NumeratorVal.sext(DenominatorBW);
870
871 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
872 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
873 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
874 Quotient = SE.getConstant(QuotientVal);
875 Remainder = SE.getConstant(RemainderVal);
876 return;
877 }
878 }
879
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000880 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
881 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000882 if (!Numerator->isAffine())
883 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000884 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
885 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000886 // Bail out if the types do not match.
887 Type *Ty = Denominator->getType();
888 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000889 Ty != StepQ->getType() || Ty != StepR->getType())
890 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000891 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
892 Numerator->getNoWrapFlags());
893 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
894 Numerator->getNoWrapFlags());
895 }
896
897 void visitAddExpr(const SCEVAddExpr *Numerator) {
898 SmallVector<const SCEV *, 2> Qs, Rs;
899 Type *Ty = Denominator->getType();
900
901 for (const SCEV *Op : Numerator->operands()) {
902 const SCEV *Q, *R;
903 divide(SE, Op, Denominator, &Q, &R);
904
905 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000906 if (Ty != Q->getType() || Ty != R->getType())
907 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000908
909 Qs.push_back(Q);
910 Rs.push_back(R);
911 }
912
913 if (Qs.size() == 1) {
914 Quotient = Qs[0];
915 Remainder = Rs[0];
916 return;
917 }
918
919 Quotient = SE.getAddExpr(Qs);
920 Remainder = SE.getAddExpr(Rs);
921 }
922
923 void visitMulExpr(const SCEVMulExpr *Numerator) {
924 SmallVector<const SCEV *, 2> Qs;
925 Type *Ty = Denominator->getType();
926
927 bool FoundDenominatorTerm = false;
928 for (const SCEV *Op : Numerator->operands()) {
929 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000930 if (Ty != Op->getType())
931 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000932
933 if (FoundDenominatorTerm) {
934 Qs.push_back(Op);
935 continue;
936 }
937
938 // Check whether Denominator divides one of the product operands.
939 const SCEV *Q, *R;
940 divide(SE, Op, Denominator, &Q, &R);
941 if (!R->isZero()) {
942 Qs.push_back(Op);
943 continue;
944 }
945
946 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000947 if (Ty != Q->getType())
948 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000949
950 FoundDenominatorTerm = true;
951 Qs.push_back(Q);
952 }
953
954 if (FoundDenominatorTerm) {
955 Remainder = Zero;
956 if (Qs.size() == 1)
957 Quotient = Qs[0];
958 else
959 Quotient = SE.getMulExpr(Qs);
960 return;
961 }
962
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000963 if (!isa<SCEVUnknown>(Denominator))
964 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000965
966 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
967 ValueToValueMap RewriteMap;
968 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
969 cast<SCEVConstant>(Zero)->getValue();
970 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
971
972 if (Remainder->isZero()) {
973 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
974 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
975 cast<SCEVConstant>(One)->getValue();
976 Quotient =
977 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
978 return;
979 }
980
981 // Quotient is (Numerator - Remainder) divided by Denominator.
982 const SCEV *Q, *R;
983 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000984 // This SCEV does not seem to simplify: fail the division here.
985 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
986 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000987 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000988 if (R != Zero)
989 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000990 Quotient = Q;
991 }
992
993private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000994 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
995 const SCEV *Denominator)
996 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000997 Zero = SE.getZero(Denominator->getType());
998 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000999
Matthew Simpsonddb4d972015-09-10 18:12:47 +00001000 // We generally do not know how to divide Expr by Denominator. We
1001 // initialize the division to a "cannot divide" state to simplify the rest
1002 // of the code.
1003 cannotDivide(Numerator);
1004 }
1005
1006 // Convenience function for giving up on the division. We set the quotient to
1007 // be equal to zero and the remainder to be equal to the numerator.
1008 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +00001009 Quotient = Zero;
1010 Remainder = Numerator;
1011 }
1012
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001013 ScalarEvolution &SE;
1014 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +00001015};
1016
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001017}
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001018
Chris Lattnerd934c702004-04-02 20:23:17 +00001019//===----------------------------------------------------------------------===//
1020// Simple SCEV method implementations
1021//===----------------------------------------------------------------------===//
1022
Sanjoy Dasf8570812016-05-29 00:38:22 +00001023/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +00001024static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +00001025 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001026 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001027 // Handle the simplest case efficiently.
1028 if (K == 1)
1029 return SE.getTruncateOrZeroExtend(It, ResultTy);
1030
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001031 // We are using the following formula for BC(It, K):
1032 //
1033 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1034 //
Eli Friedman61f67622008-08-04 23:49:06 +00001035 // Suppose, W is the bitwidth of the return value. We must be prepared for
1036 // overflow. Hence, we must assure that the result of our computation is
1037 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1038 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001039 //
Eli Friedman61f67622008-08-04 23:49:06 +00001040 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001041 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001042 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1043 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001044 //
Eli Friedman61f67622008-08-04 23:49:06 +00001045 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046 //
Eli Friedman61f67622008-08-04 23:49:06 +00001047 // This formula is trivially equivalent to the previous formula. However,
1048 // this formula can be implemented much more efficiently. The trick is that
1049 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1050 // arithmetic. To do exact division in modular arithmetic, all we have
1051 // to do is multiply by the inverse. Therefore, this step can be done at
1052 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001053 //
Eli Friedman61f67622008-08-04 23:49:06 +00001054 // The next issue is how to safely do the division by 2^T. The way this
1055 // is done is by doing the multiplication step at a width of at least W + T
1056 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1057 // when we perform the division by 2^T (which is equivalent to a right shift
1058 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1059 // truncated out after the division by 2^T.
1060 //
1061 // In comparison to just directly using the first formula, this technique
1062 // is much more efficient; using the first formula requires W * K bits,
1063 // but this formula less than W + K bits. Also, the first formula requires
1064 // a division step, whereas this formula only requires multiplies and shifts.
1065 //
1066 // It doesn't matter whether the subtraction step is done in the calculation
1067 // width or the input iteration count's width; if the subtraction overflows,
1068 // the result must be zero anyway. We prefer here to do it in the width of
1069 // the induction variable because it helps a lot for certain cases; CodeGen
1070 // isn't smart enough to ignore the overflow, which leads to much less
1071 // efficient code if the width of the subtraction is wider than the native
1072 // register width.
1073 //
1074 // (It's possible to not widen at all by pulling out factors of 2 before
1075 // the multiplication; for example, K=2 can be calculated as
1076 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1077 // extra arithmetic, so it's not an obvious win, and it gets
1078 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001079
Eli Friedman61f67622008-08-04 23:49:06 +00001080 // Protection from insane SCEVs; this bound is conservative,
1081 // but it probably doesn't matter.
1082 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001083 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001084
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001085 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001086
Eli Friedman61f67622008-08-04 23:49:06 +00001087 // Calculate K! / 2^T and T; we divide out the factors of two before
1088 // multiplying for calculating K! / 2^T to avoid overflow.
1089 // Other overflow doesn't matter because we only care about the bottom
1090 // W bits of the result.
1091 APInt OddFactorial(W, 1);
1092 unsigned T = 1;
1093 for (unsigned i = 3; i <= K; ++i) {
1094 APInt Mult(W, i);
1095 unsigned TwoFactors = Mult.countTrailingZeros();
1096 T += TwoFactors;
Craig Topperfc947bc2017-04-18 17:14:21 +00001097 Mult.lshrInPlace(TwoFactors);
Eli Friedman61f67622008-08-04 23:49:06 +00001098 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001099 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001100
Eli Friedman61f67622008-08-04 23:49:06 +00001101 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001102 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001103
Dan Gohman8b0a4192010-03-01 17:49:51 +00001104 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001105 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001106
1107 // Calculate the multiplicative inverse of K! / 2^T;
1108 // this multiplication factor will perform the exact division by
1109 // K! / 2^T.
1110 APInt Mod = APInt::getSignedMinValue(W+1);
1111 APInt MultiplyFactor = OddFactorial.zext(W+1);
1112 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1113 MultiplyFactor = MultiplyFactor.trunc(W);
1114
1115 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001116 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001117 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001118 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001119 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001120 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001121 Dividend = SE.getMulExpr(Dividend,
1122 SE.getTruncateOrZeroExtend(S, CalculationTy));
1123 }
1124
1125 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001126 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001127
1128 // Truncate the result, and divide by K! / 2^T.
1129
1130 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1131 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001132}
1133
Sanjoy Dasf8570812016-05-29 00:38:22 +00001134/// Return the value of this chain of recurrences at the specified iteration
1135/// number. We can evaluate this recurrence by multiplying each element in the
1136/// chain by the binomial coefficient corresponding to it. In other words, we
1137/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001138///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001139/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001140///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001141/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001142///
Dan Gohmanaf752342009-07-07 17:06:11 +00001143const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001144 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001145 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001146 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001147 // The computation is correct in the face of overflow provided that the
1148 // multiplication is performed _after_ the evaluation of the binomial
1149 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001150 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001151 if (isa<SCEVCouldNotCompute>(Coeff))
1152 return Coeff;
1153
1154 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001155 }
1156 return Result;
1157}
1158
Chris Lattnerd934c702004-04-02 20:23:17 +00001159//===----------------------------------------------------------------------===//
1160// SCEV Expression folder implementations
1161//===----------------------------------------------------------------------===//
1162
Dan Gohmanaf752342009-07-07 17:06:11 +00001163const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001164 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001165 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001166 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001167 assert(isSCEVable(Ty) &&
1168 "This is not a conversion to a SCEVable type!");
1169 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001170
Dan Gohman3a302cb2009-07-13 20:50:19 +00001171 FoldingSetNodeID ID;
1172 ID.AddInteger(scTruncate);
1173 ID.AddPointer(Op);
1174 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001175 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001176 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1177
Dan Gohman3423e722009-06-30 20:13:32 +00001178 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001179 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001180 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001181 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001182
Dan Gohman79af8542009-04-22 16:20:48 +00001183 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001184 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001185 return getTruncateExpr(ST->getOperand(), Ty);
1186
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001187 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001188 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001189 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1190
1191 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001192 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001193 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1194
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001195 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001196 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001197 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1198 SmallVector<const SCEV *, 4> Operands;
1199 bool hasTrunc = false;
1200 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1201 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001202 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1203 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001204 Operands.push_back(S);
1205 }
1206 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001207 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001208 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001209 }
1210
Nick Lewycky5c901f32011-01-19 18:56:00 +00001211 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001212 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001213 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1214 SmallVector<const SCEV *, 4> Operands;
1215 bool hasTrunc = false;
1216 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1217 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001218 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1219 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001220 Operands.push_back(S);
1221 }
1222 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001223 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001224 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001225 }
1226
Dan Gohman5a728c92009-06-18 16:24:47 +00001227 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001228 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001229 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001230 for (const SCEV *Op : AddRec->operands())
1231 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001232 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001233 }
1234
Dan Gohman89dd42a2010-06-25 18:47:08 +00001235 // The cast wasn't folded; create an explicit cast node. We can reuse
1236 // the existing insert position since if we get here, we won't have
1237 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001238 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1239 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001240 UniqueSCEVs.InsertNode(S, IP);
1241 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001242}
1243
Sanjoy Das4153f472015-02-18 01:47:07 +00001244// Get the limit of a recurrence such that incrementing by Step cannot cause
1245// signed overflow as long as the value of the recurrence within the
1246// loop does not exceed this limit before incrementing.
1247static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1248 ICmpInst::Predicate *Pred,
1249 ScalarEvolution *SE) {
1250 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1251 if (SE->isKnownPositive(Step)) {
1252 *Pred = ICmpInst::ICMP_SLT;
1253 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1254 SE->getSignedRange(Step).getSignedMax());
1255 }
1256 if (SE->isKnownNegative(Step)) {
1257 *Pred = ICmpInst::ICMP_SGT;
1258 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1259 SE->getSignedRange(Step).getSignedMin());
1260 }
1261 return nullptr;
1262}
1263
1264// Get the limit of a recurrence such that incrementing by Step cannot cause
1265// unsigned overflow as long as the value of the recurrence within the loop does
1266// not exceed this limit before incrementing.
1267static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1268 ICmpInst::Predicate *Pred,
1269 ScalarEvolution *SE) {
1270 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1271 *Pred = ICmpInst::ICMP_ULT;
1272
1273 return SE->getConstant(APInt::getMinValue(BitWidth) -
1274 SE->getUnsignedRange(Step).getUnsignedMax());
1275}
1276
1277namespace {
1278
1279struct ExtendOpTraitsBase {
Wei Mi8c405332017-04-17 20:40:05 +00001280 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1281 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
Sanjoy Das4153f472015-02-18 01:47:07 +00001282};
1283
1284// Used to make code generic over signed and unsigned overflow.
1285template <typename ExtendOp> struct ExtendOpTraits {
1286 // Members present:
1287 //
1288 // static const SCEV::NoWrapFlags WrapType;
1289 //
1290 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1291 //
1292 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1293 // ICmpInst::Predicate *Pred,
1294 // ScalarEvolution *SE);
1295};
1296
1297template <>
1298struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1299 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1300
1301 static const GetExtendExprTy GetExtendExpr;
1302
1303 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1304 ICmpInst::Predicate *Pred,
1305 ScalarEvolution *SE) {
1306 return getSignedOverflowLimitForStep(Step, Pred, SE);
1307 }
1308};
1309
Wei Mi8c405332017-04-17 20:40:05 +00001310const ExtendOpTraitsBase::GetExtendExprTy
1311 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1312 &ScalarEvolution::getSignExtendExprCached;
Sanjoy Das4153f472015-02-18 01:47:07 +00001313
1314template <>
1315struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1316 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1317
1318 static const GetExtendExprTy GetExtendExpr;
1319
1320 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1321 ICmpInst::Predicate *Pred,
1322 ScalarEvolution *SE) {
1323 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1324 }
1325};
1326
Wei Mi8c405332017-04-17 20:40:05 +00001327const ExtendOpTraitsBase::GetExtendExprTy
1328 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1329 &ScalarEvolution::getZeroExtendExprCached;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001330}
Sanjoy Das4153f472015-02-18 01:47:07 +00001331
1332// The recurrence AR has been shown to have no signed/unsigned wrap or something
1333// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1334// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1335// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1336// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1337// expression "Step + sext/zext(PreIncAR)" is congruent with
1338// "sext/zext(PostIncAR)"
1339template <typename ExtendOpTy>
1340static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
Wei Mi8c405332017-04-17 20:40:05 +00001341 ScalarEvolution *SE,
1342 ScalarEvolution::ExtendCacheTy &Cache) {
Sanjoy Das4153f472015-02-18 01:47:07 +00001343 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1344 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1345
1346 const Loop *L = AR->getLoop();
1347 const SCEV *Start = AR->getStart();
1348 const SCEV *Step = AR->getStepRecurrence(*SE);
1349
1350 // Check for a simple looking step prior to loop entry.
1351 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1352 if (!SA)
1353 return nullptr;
1354
1355 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1356 // subtraction is expensive. For this purpose, perform a quick and dirty
1357 // difference, by checking for Step in the operand list.
1358 SmallVector<const SCEV *, 4> DiffOps;
1359 for (const SCEV *Op : SA->operands())
1360 if (Op != Step)
1361 DiffOps.push_back(Op);
1362
1363 if (DiffOps.size() == SA->getNumOperands())
1364 return nullptr;
1365
1366 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1367 // `Step`:
1368
1369 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001370 auto PreStartFlags =
1371 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1372 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001373 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1374 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1375
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001376 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1377 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001378 //
1379
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001380 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1381 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1382 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001383 return PreStart;
1384
1385 // 2. Direct overflow check on the step operation's expression.
1386 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1387 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1388 const SCEV *OperandExtendedStart =
Wei Mi8c405332017-04-17 20:40:05 +00001389 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1390 (SE->*GetExtendExpr)(Step, WideTy, Cache));
1391 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
Sanjoy Das4153f472015-02-18 01:47:07 +00001392 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1393 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1394 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1395 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1396 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1397 }
1398 return PreStart;
1399 }
1400
1401 // 3. Loop precondition.
1402 ICmpInst::Predicate Pred;
1403 const SCEV *OverflowLimit =
1404 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1405
1406 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001407 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001408 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001409
Sanjoy Das4153f472015-02-18 01:47:07 +00001410 return nullptr;
1411}
1412
1413// Get the normalized zero or sign extended expression for this AddRec's Start.
1414template <typename ExtendOpTy>
1415static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
Wei Mi8c405332017-04-17 20:40:05 +00001416 ScalarEvolution *SE,
1417 ScalarEvolution::ExtendCacheTy &Cache) {
Sanjoy Das4153f472015-02-18 01:47:07 +00001418 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1419
Wei Mi8c405332017-04-17 20:40:05 +00001420 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
Sanjoy Das4153f472015-02-18 01:47:07 +00001421 if (!PreStart)
Wei Mi8c405332017-04-17 20:40:05 +00001422 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
Sanjoy Das4153f472015-02-18 01:47:07 +00001423
Wei Mi8c405332017-04-17 20:40:05 +00001424 return SE->getAddExpr(
1425 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1426 (SE->*GetExtendExpr)(PreStart, Ty, Cache));
Sanjoy Das4153f472015-02-18 01:47:07 +00001427}
1428
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001429// Try to prove away overflow by looking at "nearby" add recurrences. A
1430// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1431// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1432//
1433// Formally:
1434//
1435// {S,+,X} == {S-T,+,X} + T
1436// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1437//
1438// If ({S-T,+,X} + T) does not overflow ... (1)
1439//
1440// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1441//
1442// If {S-T,+,X} does not overflow ... (2)
1443//
1444// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1445// == {Ext(S-T)+Ext(T),+,Ext(X)}
1446//
1447// If (S-T)+T does not overflow ... (3)
1448//
1449// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1450// == {Ext(S),+,Ext(X)} == LHS
1451//
1452// Thus, if (1), (2) and (3) are true for some T, then
1453// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1454//
1455// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1456// does not overflow" restricted to the 0th iteration. Therefore we only need
1457// to check for (1) and (2).
1458//
1459// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1460// is `Delta` (defined below).
1461//
1462template <typename ExtendOpTy>
1463bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1464 const SCEV *Step,
1465 const Loop *L) {
1466 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1467
1468 // We restrict `Start` to a constant to prevent SCEV from spending too much
1469 // time here. It is correct (but more expensive) to continue with a
1470 // non-constant `Start` and do a general SCEV subtraction to compute
1471 // `PreStart` below.
1472 //
1473 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1474 if (!StartC)
1475 return false;
1476
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001477 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001478
1479 for (unsigned Delta : {-2, -1, 1, 2}) {
1480 const SCEV *PreStart = getConstant(StartAI - Delta);
1481
Sanjoy Das42801102015-10-23 06:57:21 +00001482 FoldingSetNodeID ID;
1483 ID.AddInteger(scAddRecExpr);
1484 ID.AddPointer(PreStart);
1485 ID.AddPointer(Step);
1486 ID.AddPointer(L);
1487 void *IP = nullptr;
1488 const auto *PreAR =
1489 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1490
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001491 // Give up if we don't already have the add recurrence we need because
1492 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001493 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1494 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1495 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1496 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1497 DeltaS, &Pred, this);
1498 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1499 return true;
1500 }
1501 }
1502
1503 return false;
1504}
1505
Wei Mi8c405332017-04-17 20:40:05 +00001506const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1507 // Use the local cache to prevent exponential behavior of
1508 // getZeroExtendExprImpl.
1509 ExtendCacheTy Cache;
1510 return getZeroExtendExprCached(Op, Ty, Cache);
1511}
1512
1513/// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1514/// related entry in the \p Cache, call getZeroExtendExprImpl and save
1515/// the result in the \p Cache.
1516const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1517 ExtendCacheTy &Cache) {
1518 auto It = Cache.find({Op, Ty});
1519 if (It != Cache.end())
1520 return It->second;
1521 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1522 auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1523 assert(InsertResult.second && "Expect the key was not in the cache");
Wei Mi66c4dd22017-04-17 21:00:45 +00001524 (void)InsertResult;
Wei Mi8c405332017-04-17 20:40:05 +00001525 return ZExt;
1526}
1527
1528/// The real implementation of getZeroExtendExpr.
1529const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1530 ExtendCacheTy &Cache) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001531 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001532 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001533 assert(isSCEVable(Ty) &&
1534 "This is not a conversion to a SCEVable type!");
1535 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001536
Dan Gohman3423e722009-06-30 20:13:32 +00001537 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001538 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1539 return getConstant(
Wei Mi8c405332017-04-17 20:40:05 +00001540 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001541
Dan Gohman79af8542009-04-22 16:20:48 +00001542 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001543 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Wei Mi8c405332017-04-17 20:40:05 +00001544 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
Dan Gohman79af8542009-04-22 16:20:48 +00001545
Dan Gohman74a0ba12009-07-13 20:55:53 +00001546 // Before doing any expensive analysis, check to see if we've already
1547 // computed a SCEV for this Op and Ty.
1548 FoldingSetNodeID ID;
1549 ID.AddInteger(scZeroExtend);
1550 ID.AddPointer(Op);
1551 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001552 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1554
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001555 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1556 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1557 // It's possible the bits taken off by the truncate were all zero bits. If
1558 // so, we should be able to simplify this further.
1559 const SCEV *X = ST->getOperand();
1560 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001561 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1562 unsigned NewBits = getTypeSizeInBits(Ty);
1563 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001564 CR.zextOrTrunc(NewBits)))
1565 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001566 }
1567
Dan Gohman76466372009-04-27 20:16:15 +00001568 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001569 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001570 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001571 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001572 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001573 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001574 const SCEV *Start = AR->getStart();
1575 const SCEV *Step = AR->getStepRecurrence(*this);
1576 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1577 const Loop *L = AR->getLoop();
1578
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001579 if (!AR->hasNoUnsignedWrap()) {
1580 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1581 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1582 }
1583
Dan Gohman62ef6a72009-07-25 01:22:26 +00001584 // If we have special knowledge that this addrec won't overflow,
1585 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001586 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001587 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001588 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1589 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001590
Dan Gohman76466372009-04-27 20:16:15 +00001591 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1592 // Note that this serves two purposes: It filters out loops that are
1593 // simply not analyzable, and it covers the case where this code is
1594 // being called from within backedge-taken count analysis, such that
1595 // attempting to ask for the backedge-taken count would likely result
1596 // in infinite recursion. In the later case, the analysis code will
1597 // cope with a conservative value, and it will take care to purge
1598 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001599 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001600 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001601 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001602 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001603
1604 // Check whether the backedge-taken count can be losslessly casted to
1605 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001606 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001607 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001608 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001609 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1610 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001611 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001612 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001613 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Wei Mi8c405332017-04-17 20:40:05 +00001614 const SCEV *ZAdd =
1615 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1616 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001617 const SCEV *WideMaxBECount =
Wei Mi8c405332017-04-17 20:40:05 +00001618 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1619 const SCEV *OperandExtendedAdd = getAddExpr(
1620 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1621 Step, WideTy, Cache)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001622 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001623 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1624 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001625 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001626 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001627 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1628 getZeroExtendExprCached(Step, Ty, Cache), L,
1629 AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001630 }
Dan Gohman76466372009-04-27 20:16:15 +00001631 // Similar to above, only this time treat the step value as signed.
1632 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001633 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001634 getAddExpr(WideStart,
1635 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001636 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001637 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001638 // Cache knowledge of AR NW, which is propagated to this AddRec.
1639 // Negative step causes unsigned wrap, but it still can't self-wrap.
1640 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001641 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001642 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001643 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
Sanjoy Das4153f472015-02-18 01:47:07 +00001644 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001645 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001646 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001647 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001648
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001649 // Normally, in the cases we can prove no-overflow via a
1650 // backedge guarding condition, we can also compute a backedge
1651 // taken count for the loop. The exceptions are assumptions and
1652 // guards present in the loop -- SCEV is not great at exploiting
1653 // these to compute max backedge taken counts, but can still use
1654 // these to prove lack of overflow. Use this fact to avoid
1655 // doing extra work that may not pay off.
1656 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001657 !AC.assumptions().empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001658 // If the backedge is guarded by a comparison with the pre-inc
1659 // value the addrec is safe. Also, if the entry is guarded by
1660 // a comparison with the start value and the backedge is
1661 // guarded by a comparison with the post-inc value, the addrec
1662 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001663 if (isKnownPositive(Step)) {
1664 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1665 getUnsignedRange(Step).getUnsignedMax());
1666 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001667 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001668 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001669 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001670 // Cache knowledge of AR NUW, which is propagated to this
1671 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001672 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001673 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001674 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001675 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1676 getZeroExtendExprCached(Step, Ty, Cache), L,
1677 AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001678 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001679 } else if (isKnownNegative(Step)) {
1680 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1681 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001682 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1683 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001684 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001685 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001686 // Cache knowledge of AR NW, which is propagated to this
1687 // AddRec. Negative step causes unsigned wrap, but it
1688 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001689 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1690 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001691 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001692 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
Sanjoy Das4153f472015-02-18 01:47:07 +00001693 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001694 }
Dan Gohman76466372009-04-27 20:16:15 +00001695 }
1696 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001697
1698 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1700 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001701 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1702 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001703 }
Dan Gohman76466372009-04-27 20:16:15 +00001704 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001705
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001706 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1707 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001708 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001709 // If the addition does not unsign overflow then we can, by definition,
1710 // commute the zero extension with the addition operation.
1711 SmallVector<const SCEV *, 4> Ops;
1712 for (const auto *Op : SA->operands())
Wei Mi8c405332017-04-17 20:40:05 +00001713 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001714 return getAddExpr(Ops, SCEV::FlagNUW);
1715 }
1716 }
1717
Dan Gohman74a0ba12009-07-13 20:55:53 +00001718 // The cast wasn't folded; create an explicit cast node.
1719 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001721 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1722 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001723 UniqueSCEVs.InsertNode(S, IP);
1724 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001725}
1726
Wei Mi8c405332017-04-17 20:40:05 +00001727const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1728 // Use the local cache to prevent exponential behavior of
1729 // getSignExtendExprImpl.
1730 ExtendCacheTy Cache;
1731 return getSignExtendExprCached(Op, Ty, Cache);
1732}
1733
1734/// Query \p Cache before calling getSignExtendExprImpl. If there is no
1735/// related entry in the \p Cache, call getSignExtendExprImpl and save
1736/// the result in the \p Cache.
1737const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1738 ExtendCacheTy &Cache) {
1739 auto It = Cache.find({Op, Ty});
1740 if (It != Cache.end())
1741 return It->second;
1742 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1743 auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1744 assert(InsertResult.second && "Expect the key was not in the cache");
Benjamin Kramer61d85bc2017-04-17 21:07:26 +00001745 (void)InsertResult;
Wei Mi8c405332017-04-17 20:40:05 +00001746 return SExt;
1747}
1748
1749/// The real implementation of getSignExtendExpr.
1750const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1751 ExtendCacheTy &Cache) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001752 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001753 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001754 assert(isSCEVable(Ty) &&
1755 "This is not a conversion to a SCEVable type!");
1756 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001757
Dan Gohman3423e722009-06-30 20:13:32 +00001758 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001759 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1760 return getConstant(
Wei Mi8c405332017-04-17 20:40:05 +00001761 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001762
Dan Gohman79af8542009-04-22 16:20:48 +00001763 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001764 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Wei Mi8c405332017-04-17 20:40:05 +00001765 return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
Dan Gohman79af8542009-04-22 16:20:48 +00001766
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001767 // sext(zext(x)) --> zext(x)
1768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1769 return getZeroExtendExpr(SZ->getOperand(), Ty);
1770
Dan Gohman74a0ba12009-07-13 20:55:53 +00001771 // Before doing any expensive analysis, check to see if we've already
1772 // computed a SCEV for this Op and Ty.
1773 FoldingSetNodeID ID;
1774 ID.AddInteger(scSignExtend);
1775 ID.AddPointer(Op);
1776 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001777 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1779
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001780 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1781 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1782 // It's possible the bits taken off by the truncate were all sign bits. If
1783 // so, we should be able to simplify this further.
1784 const SCEV *X = ST->getOperand();
1785 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001786 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1787 unsigned NewBits = getTypeSizeInBits(Ty);
1788 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001789 CR.sextOrTrunc(NewBits)))
1790 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001791 }
1792
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001793 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001794 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001795 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001796 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1797 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001798 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001799 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001800 const APInt &C1 = SC1->getAPInt();
1801 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001802 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001803 C2.ugt(C1) && C2.isPowerOf2())
Wei Mi8c405332017-04-17 20:40:05 +00001804 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1805 getSignExtendExprCached(SMul, Ty, Cache));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001806 }
1807 }
1808 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001809
1810 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001811 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001812 // If the addition does not sign overflow then we can, by definition,
1813 // commute the sign extension with the addition operation.
1814 SmallVector<const SCEV *, 4> Ops;
1815 for (const auto *Op : SA->operands())
Wei Mi8c405332017-04-17 20:40:05 +00001816 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
Sanjoy Dasa060e602015-10-22 19:57:25 +00001817 return getAddExpr(Ops, SCEV::FlagNSW);
1818 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001819 }
Dan Gohman76466372009-04-27 20:16:15 +00001820 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001821 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001822 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001823 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001824 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001825 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001826 const SCEV *Start = AR->getStart();
1827 const SCEV *Step = AR->getStepRecurrence(*this);
1828 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1829 const Loop *L = AR->getLoop();
1830
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001831 if (!AR->hasNoSignedWrap()) {
1832 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1833 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1834 }
1835
Dan Gohman62ef6a72009-07-25 01:22:26 +00001836 // If we have special knowledge that this addrec won't overflow,
1837 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001838 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001839 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001840 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1841 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001842
Dan Gohman76466372009-04-27 20:16:15 +00001843 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1844 // Note that this serves two purposes: It filters out loops that are
1845 // simply not analyzable, and it covers the case where this code is
1846 // being called from within backedge-taken count analysis, such that
1847 // attempting to ask for the backedge-taken count would likely result
1848 // in infinite recursion. In the later case, the analysis code will
1849 // cope with a conservative value, and it will take care to purge
1850 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001851 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001852 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001853 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001854 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001855
1856 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001857 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001858 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001859 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001860 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001861 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1862 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001863 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001864 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001865 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Wei Mi8c405332017-04-17 20:40:05 +00001866 const SCEV *SAdd =
1867 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1868 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001869 const SCEV *WideMaxBECount =
Wei Mi8c405332017-04-17 20:40:05 +00001870 getZeroExtendExpr(CastedMaxBECount, WideTy);
1871 const SCEV *OperandExtendedAdd = getAddExpr(
1872 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1873 Step, WideTy, Cache)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001874 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001875 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001877 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001878 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001879 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1880 getSignExtendExprCached(Step, Ty, Cache), L,
1881 AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001882 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001883 // Similar to above, only this time treat the step value as unsigned.
1884 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001885 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001886 getAddExpr(WideStart,
1887 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001888 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001889 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001890 // If AR wraps around then
1891 //
1892 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1893 // => SAdd != OperandExtendedAdd
1894 //
1895 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1896 // (SAdd == OperandExtendedAdd => AR is NW)
1897
1898 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1899
Dan Gohman8c129d72009-07-16 17:34:36 +00001900 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001901 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001902 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
Sanjoy Das4153f472015-02-18 01:47:07 +00001903 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001904 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001905 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001906 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001907
Sanjoy Das787c2462016-05-11 17:41:26 +00001908 // Normally, in the cases we can prove no-overflow via a
1909 // backedge guarding condition, we can also compute a backedge
1910 // taken count for the loop. The exceptions are assumptions and
1911 // guards present in the loop -- SCEV is not great at exploiting
1912 // these to compute max backedge taken counts, but can still use
1913 // these to prove lack of overflow. Use this fact to avoid
1914 // doing extra work that may not pay off.
1915
1916 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001917 !AC.assumptions().empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001918 // If the backedge is guarded by a comparison with the pre-inc
1919 // value the addrec is safe. Also, if the entry is guarded by
1920 // a comparison with the start value and the backedge is
1921 // guarded by a comparison with the post-inc value, the addrec
1922 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001923 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001924 const SCEV *OverflowLimit =
1925 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001926 if (OverflowLimit &&
1927 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1928 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1929 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1930 OverflowLimit)))) {
1931 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1932 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001933 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001934 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1935 getSignExtendExprCached(Step, Ty, Cache), L,
1936 AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001937 }
1938 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001939
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001940 // If Start and Step are constants, check if we can apply this
1941 // transformation:
1942 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001943 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1944 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001945 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001946 const APInt &C1 = SC1->getAPInt();
1947 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001948 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1949 C2.isPowerOf2()) {
Wei Mi8c405332017-04-17 20:40:05 +00001950 Start = getSignExtendExprCached(Start, Ty, Cache);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001951 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1952 AR->getNoWrapFlags());
Wei Mi8c405332017-04-17 20:40:05 +00001953 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001954 }
1955 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001956
1957 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1958 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1959 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001960 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1961 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001962 }
Dan Gohman76466372009-04-27 20:16:15 +00001963 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001964
Sanjoy Das11ef6062016-03-03 18:31:23 +00001965 // If the input value is provably positive and we could not simplify
1966 // away the sext build a zext instead.
1967 if (isKnownNonNegative(Op))
1968 return getZeroExtendExpr(Op, Ty);
1969
Dan Gohman74a0ba12009-07-13 20:55:53 +00001970 // The cast wasn't folded; create an explicit cast node.
1971 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001972 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001973 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1974 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001975 UniqueSCEVs.InsertNode(S, IP);
1976 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001977}
1978
Dan Gohman8db2edc2009-06-13 15:56:47 +00001979/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1980/// unspecified bits out to the given type.
1981///
Dan Gohmanaf752342009-07-07 17:06:11 +00001982const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001983 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001984 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1985 "This is not an extending conversion!");
1986 assert(isSCEVable(Ty) &&
1987 "This is not a conversion to a SCEVable type!");
1988 Ty = getEffectiveSCEVType(Ty);
1989
1990 // Sign-extend negative constants.
1991 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001992 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001993 return getSignExtendExpr(Op, Ty);
1994
1995 // Peel off a truncate cast.
1996 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001997 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001998 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1999 return getAnyExtendExpr(NewOp, Ty);
2000 return getTruncateOrNoop(NewOp, Ty);
2001 }
2002
2003 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00002004 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00002005 if (!isa<SCEVZeroExtendExpr>(ZExt))
2006 return ZExt;
2007
2008 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00002009 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00002010 if (!isa<SCEVSignExtendExpr>(SExt))
2011 return SExt;
2012
Dan Gohman51ad99d2010-01-21 02:09:26 +00002013 // Force the cast to be folded into the operands of an addrec.
2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2015 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00002016 for (const SCEV *Op : AR->operands())
2017 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002018 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002019 }
2020
Dan Gohman8db2edc2009-06-13 15:56:47 +00002021 // If the expression is obviously signed, use the sext cast value.
2022 if (isa<SCEVSMaxExpr>(Op))
2023 return SExt;
2024
2025 // Absent any other information, use the zext cast value.
2026 return ZExt;
2027}
2028
Sanjoy Dasf8570812016-05-29 00:38:22 +00002029/// Process the given Ops list, which is a list of operands to be added under
2030/// the given scale, update the given map. This is a helper function for
2031/// getAddRecExpr. As an example of what it does, given a sequence of operands
2032/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00002033///
Tobias Grosserba49e422014-03-05 10:37:17 +00002034/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00002035///
2036/// where A and B are constants, update the map with these values:
2037///
2038/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2039///
2040/// and add 13 + A*B*29 to AccumulatedConstant.
2041/// This will allow getAddRecExpr to produce this:
2042///
2043/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2044///
2045/// This form often exposes folding opportunities that are hidden in
2046/// the original operand list.
2047///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002048/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00002049/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2050/// the common case where no interesting opportunities are present, and
2051/// is also used as a check to avoid infinite recursion.
2052///
2053static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00002054CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002055 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00002056 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002057 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00002058 const APInt &Scale,
2059 ScalarEvolution &SE) {
2060 bool Interesting = false;
2061
Dan Gohman45073042010-06-18 19:12:32 +00002062 // Iterate over the add operands. They are sorted, with constants first.
2063 unsigned i = 0;
2064 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2065 ++i;
2066 // Pull a buried constant out to the outside.
2067 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2068 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002069 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00002070 }
2071
2072 // Next comes everything else. We're especially interested in multiplies
2073 // here, but they're in the middle, so just visit the rest with one loop.
2074 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002075 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2076 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2077 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002078 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00002079 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2080 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00002081 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002082 Interesting |=
2083 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002084 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002085 NewScale, SE);
2086 } else {
2087 // A multiplication of a constant with some other value. Update
2088 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002089 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2090 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002091 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002092 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002093 NewOps.push_back(Pair.first->first);
2094 } else {
2095 Pair.first->second += NewScale;
2096 // The map already had an entry for this value, which may indicate
2097 // a folding opportunity.
2098 Interesting = true;
2099 }
2100 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002101 } else {
2102 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002103 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002104 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002105 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002106 NewOps.push_back(Pair.first->first);
2107 } else {
2108 Pair.first->second += Scale;
2109 // The map already had an entry for this value, which may indicate
2110 // a folding opportunity.
2111 Interesting = true;
2112 }
2113 }
2114 }
2115
2116 return Interesting;
2117}
2118
Sanjoy Das81401d42015-01-10 23:41:24 +00002119// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2120// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2121// can't-overflow flags for the operation if possible.
2122static SCEV::NoWrapFlags
2123StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2124 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002125 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002126 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002127 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002128
2129 bool CanAnalyze =
2130 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2131 (void)CanAnalyze;
2132 assert(CanAnalyze && "don't call from other places!");
2133
2134 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2135 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002136 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002137
2138 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002139 auto IsKnownNonNegative = [&](const SCEV *S) {
2140 return SE->isKnownNonNegative(S);
2141 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002142
Sanjoy Das3b827c72015-11-29 23:40:53 +00002143 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002144 Flags =
2145 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002146
Sanjoy Das8f274152015-10-22 19:57:19 +00002147 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2148
2149 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2150 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2151
2152 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2153 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2154
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002155 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002156 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002157 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2158 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002159 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2160 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2161 }
2162 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002163 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2164 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002165 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2166 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2167 }
2168 }
2169
2170 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002171}
2172
Sanjoy Dasf8570812016-05-29 00:38:22 +00002173/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002174const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002175 SCEV::NoWrapFlags Flags,
2176 unsigned Depth) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002177 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2178 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002179 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002180 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002181#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002182 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002183 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002184 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002185 "SCEVAddExpr operand types don't match!");
2186#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002187
2188 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002189 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002190
Sanjoy Das64895612015-10-09 02:44:45 +00002191 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2192
Chris Lattnerd934c702004-04-02 20:23:17 +00002193 // If there are any constants, fold them together.
2194 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002195 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002196 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002197 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002198 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002199 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002200 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002201 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002202 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002203 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002204 }
2205
2206 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002207 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002208 Ops.erase(Ops.begin());
2209 --Idx;
2210 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002211
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002212 if (Ops.size() == 1) return Ops[0];
2213 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002214
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002215 // Limit recursion calls depth
2216 if (Depth > MaxAddExprDepth)
2217 return getOrCreateAddExpr(Ops, Flags);
2218
Dan Gohman15871f22010-08-27 21:39:59 +00002219 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002220 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002221 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002222 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002223 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002224 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002225 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002226 // Scan ahead to count how many equal operands there are.
2227 unsigned Count = 2;
2228 while (i+Count != e && Ops[i+Count] == Ops[i])
2229 ++Count;
2230 // Merge the values into a multiply.
2231 const SCEV *Scale = getConstant(Ty, Count);
2232 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2233 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002234 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002235 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002236 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002237 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002238 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002239 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002240 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002241 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002242
Dan Gohman2e55cc52009-05-08 21:03:19 +00002243 // Check for truncates. If all the operands are truncated from the same
2244 // type, see if factoring out the truncate would permit the result to be
2245 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2246 // if the contents of the resulting outer trunc fold to something simple.
2247 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2248 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002249 Type *DstType = Trunc->getType();
2250 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002251 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002252 bool Ok = true;
2253 // Check all the operands to see if they can be represented in the
2254 // source type of the truncate.
2255 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2256 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2257 if (T->getOperand()->getType() != SrcType) {
2258 Ok = false;
2259 break;
2260 }
2261 LargeOps.push_back(T->getOperand());
2262 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002263 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002264 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002265 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002266 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2267 if (const SCEVTruncateExpr *T =
2268 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2269 if (T->getOperand()->getType() != SrcType) {
2270 Ok = false;
2271 break;
2272 }
2273 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002274 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002275 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002276 } else {
2277 Ok = false;
2278 break;
2279 }
2280 }
2281 if (Ok)
2282 LargeOps.push_back(getMulExpr(LargeMulOps));
2283 } else {
2284 Ok = false;
2285 break;
2286 }
2287 }
2288 if (Ok) {
2289 // Evaluate the expression in the larger type.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002290 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002291 // If it folds to something simple, use it. Otherwise, don't.
2292 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2293 return getTruncateExpr(Fold, DstType);
2294 }
2295 }
2296
2297 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002298 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2299 ++Idx;
2300
2301 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002302 if (Idx < Ops.size()) {
2303 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002304 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Daniil Fukalovb09dac52017-01-26 13:33:17 +00002305 if (Ops.size() > AddOpsInlineThreshold ||
2306 Add->getNumOperands() > AddOpsInlineThreshold)
2307 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002308 // If we have an add, expand the add operands onto the end of the operands
2309 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002310 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002311 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002312 DeletedAdd = true;
2313 }
2314
2315 // If we deleted at least one add, we added operands to the end of the list,
2316 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002317 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002318 if (DeletedAdd)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002319 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002320 }
2321
2322 // Skip over the add expression until we get to a multiply.
2323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2324 ++Idx;
2325
Dan Gohman038d02e2009-06-14 22:58:51 +00002326 // Check to see if there are any folding opportunities present with
2327 // operands multiplied by constant values.
2328 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2329 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002330 DenseMap<const SCEV *, APInt> M;
2331 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002332 APInt AccumulatedConstant(BitWidth, 0);
2333 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002334 Ops.data(), Ops.size(),
2335 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002336 struct APIntCompare {
2337 bool operator()(const APInt &LHS, const APInt &RHS) const {
2338 return LHS.ult(RHS);
2339 }
2340 };
2341
Dan Gohman038d02e2009-06-14 22:58:51 +00002342 // Some interesting folding opportunity is present, so its worthwhile to
2343 // re-generate the operands list. Group the operands by constant scale,
2344 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002345 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002346 for (const SCEV *NewOp : NewOps)
2347 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002348 // Re-generate the operands list.
2349 Ops.clear();
2350 if (AccumulatedConstant != 0)
2351 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002352 for (auto &MulOp : MulOpLists)
2353 if (MulOp.first != 0)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002354 Ops.push_back(getMulExpr(
2355 getConstant(MulOp.first),
2356 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002357 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002358 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002359 if (Ops.size() == 1)
2360 return Ops[0];
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002361 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman038d02e2009-06-14 22:58:51 +00002362 }
2363 }
2364
Chris Lattnerd934c702004-04-02 20:23:17 +00002365 // If we are adding something to a multiply expression, make sure the
2366 // something is not already an operand of the multiply. If so, merge it into
2367 // the multiply.
2368 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002369 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002370 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002371 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002372 if (isa<SCEVConstant>(MulOpSCEV))
2373 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002374 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002375 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002376 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002377 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002378 if (Mul->getNumOperands() != 2) {
2379 // If the multiply has more than two operands, we must get the
2380 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002381 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2382 Mul->op_begin()+MulOp);
2383 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002384 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002385 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002386 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2387 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman157847f2010-08-12 14:52:55 +00002388 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002389 if (Ops.size() == 2) return OuterMul;
2390 if (AddOp < Idx) {
2391 Ops.erase(Ops.begin()+AddOp);
2392 Ops.erase(Ops.begin()+Idx-1);
2393 } else {
2394 Ops.erase(Ops.begin()+Idx);
2395 Ops.erase(Ops.begin()+AddOp-1);
2396 }
2397 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002398 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002399 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002400
Chris Lattnerd934c702004-04-02 20:23:17 +00002401 // Check this multiply against other multiplies being added together.
2402 for (unsigned OtherMulIdx = Idx+1;
2403 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2404 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002405 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002406 // If MulOp occurs in OtherMul, we can fold the two multiplies
2407 // together.
2408 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2409 OMulOp != e; ++OMulOp)
2410 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2411 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002412 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002413 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002414 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002415 Mul->op_begin()+MulOp);
2416 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002417 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002418 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002419 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002420 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002421 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002422 OtherMul->op_begin()+OMulOp);
2423 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002424 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002425 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002426 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2427 const SCEV *InnerMulSum =
2428 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohmanaf752342009-07-07 17:06:11 +00002429 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002430 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002431 Ops.erase(Ops.begin()+Idx);
2432 Ops.erase(Ops.begin()+OtherMulIdx-1);
2433 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002434 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002435 }
2436 }
2437 }
2438 }
2439
2440 // If there are any add recurrences in the operands list, see if any other
2441 // added values are loop invariant. If so, we can fold them into the
2442 // recurrence.
2443 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2444 ++Idx;
2445
2446 // Scan over all recurrences, trying to fold loop invariants into them.
2447 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2448 // Scan all of the other operands to this add and add them to the vector if
2449 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002450 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002451 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002452 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002453 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002454 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002455 LIOps.push_back(Ops[i]);
2456 Ops.erase(Ops.begin()+i);
2457 --i; --e;
2458 }
2459
2460 // If we found some loop invariants, fold them into the recurrence.
2461 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002462 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002463 LIOps.push_back(AddRec->getStart());
2464
Dan Gohmanaf752342009-07-07 17:06:11 +00002465 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002466 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002467 // This follows from the fact that the no-wrap flags on the outer add
2468 // expression are applicable on the 0th iteration, when the add recurrence
2469 // will be equal to its start value.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002470 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002471
Dan Gohman16206132010-06-30 07:16:37 +00002472 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002473 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002474 // Always propagate NW.
2475 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002476 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002477
Chris Lattnerd934c702004-04-02 20:23:17 +00002478 // If all of the other operands were loop invariant, we are done.
2479 if (Ops.size() == 1) return NewRec;
2480
Nick Lewyckydb66b822011-09-06 05:08:09 +00002481 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002482 for (unsigned i = 0;; ++i)
2483 if (Ops[i] == AddRec) {
2484 Ops[i] = NewRec;
2485 break;
2486 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002487 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002488 }
2489
2490 // Okay, if there weren't any loop invariants to be folded, check to see if
2491 // there are multiple AddRec's with the same loop induction variable being
2492 // added together. If so, we can fold them.
2493 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002494 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2495 ++OtherIdx)
2496 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2497 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2498 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2499 AddRec->op_end());
2500 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2501 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002502 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002503 if (OtherAddRec->getLoop() == AddRecLoop) {
2504 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2505 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002506 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002507 AddRecOps.append(OtherAddRec->op_begin()+i,
2508 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002509 break;
2510 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002511 SmallVector<const SCEV *, 2> TwoOps = {
2512 AddRecOps[i], OtherAddRec->getOperand(i)};
2513 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002514 }
2515 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002516 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002517 // Step size has changed, so we cannot guarantee no self-wraparound.
2518 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002519 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002520 }
2521
2522 // Otherwise couldn't fold anything into this recurrence. Move onto the
2523 // next one.
2524 }
2525
2526 // Okay, it looks like we really DO need an add expr. Check to see if we
2527 // already have one, otherwise create a new one.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002528 return getOrCreateAddExpr(Ops, Flags);
2529}
2530
2531const SCEV *
2532ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2533 SCEV::NoWrapFlags Flags) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002534 FoldingSetNodeID ID;
2535 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002536 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2537 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002538 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002539 SCEVAddExpr *S =
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002540 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
Dan Gohman51ad99d2010-01-21 02:09:26 +00002541 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002542 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2543 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002544 S = new (SCEVAllocator)
2545 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002546 UniqueSCEVs.InsertNode(S, IP);
2547 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002548 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002549 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002550}
2551
Nick Lewycky287682e2011-10-04 06:51:26 +00002552static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2553 uint64_t k = i*j;
2554 if (j > 1 && k / j != i) Overflow = true;
2555 return k;
2556}
2557
2558/// Compute the result of "n choose k", the binomial coefficient. If an
2559/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002560/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002561static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2562 // We use the multiplicative formula:
2563 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2564 // At each iteration, we take the n-th term of the numeral and divide by the
2565 // (k-n)th term of the denominator. This division will always produce an
2566 // integral result, and helps reduce the chance of overflow in the
2567 // intermediate computations. However, we can still overflow even when the
2568 // final result would fit.
2569
2570 if (n == 0 || n == k) return 1;
2571 if (k > n) return 0;
2572
2573 if (k > n/2)
2574 k = n-k;
2575
2576 uint64_t r = 1;
2577 for (uint64_t i = 1; i <= k; ++i) {
2578 r = umul_ov(r, n-(i-1), Overflow);
2579 r /= i;
2580 }
2581 return r;
2582}
2583
Nick Lewycky05044c22014-12-06 00:45:50 +00002584/// Determine if any of the operands in this SCEV are a constant or if
2585/// any of the add or multiply expressions in this SCEV contain a constant.
2586static bool containsConstantSomewhere(const SCEV *StartExpr) {
2587 SmallVector<const SCEV *, 4> Ops;
2588 Ops.push_back(StartExpr);
2589 while (!Ops.empty()) {
2590 const SCEV *CurrentExpr = Ops.pop_back_val();
2591 if (isa<SCEVConstant>(*CurrentExpr))
2592 return true;
2593
2594 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2595 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002596 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002597 }
2598 }
2599 return false;
2600}
2601
Sanjoy Dasf8570812016-05-29 00:38:22 +00002602/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002603const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002604 SCEV::NoWrapFlags Flags) {
2605 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2606 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002607 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002608 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002609#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002610 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002611 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002612 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002613 "SCEVMulExpr operand types don't match!");
2614#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002615
2616 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002617 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002618
Sanjoy Das64895612015-10-09 02:44:45 +00002619 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2620
Chris Lattnerd934c702004-04-02 20:23:17 +00002621 // If there are any constants, fold them together.
2622 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002623 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002624
2625 // C1*(C2+V) -> C1*C2 + C1*V
2626 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002627 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2628 // If any of Add's ops are Adds or Muls with a constant,
2629 // apply this transformation as well.
2630 if (Add->getNumOperands() == 2)
2631 if (containsConstantSomewhere(Add))
2632 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2633 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002634
Chris Lattnerd934c702004-04-02 20:23:17 +00002635 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002636 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002637 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002638 ConstantInt *Fold =
2639 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002640 Ops[0] = getConstant(Fold);
2641 Ops.erase(Ops.begin()+1); // Erase the folded element
2642 if (Ops.size() == 1) return Ops[0];
2643 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002644 }
2645
2646 // If we are left with a constant one being multiplied, strip it off.
2647 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2648 Ops.erase(Ops.begin());
2649 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002650 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002651 // If we have a multiply of zero, it will always be zero.
2652 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002653 } else if (Ops[0]->isAllOnesValue()) {
2654 // If we have a mul by -1 of an add, try distributing the -1 among the
2655 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002656 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002657 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2658 SmallVector<const SCEV *, 4> NewOps;
2659 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002660 for (const SCEV *AddOp : Add->operands()) {
2661 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002662 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2663 NewOps.push_back(Mul);
2664 }
2665 if (AnyFolded)
2666 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002667 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002668 // Negation preserves a recurrence's no self-wrap property.
2669 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002670 for (const SCEV *AddRecOp : AddRec->operands())
2671 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2672
Andrew Tricke92dcce2011-03-14 17:38:54 +00002673 return getAddRecExpr(Operands, AddRec->getLoop(),
2674 AddRec->getNoWrapFlags(SCEV::FlagNW));
2675 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002676 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002677 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002678
2679 if (Ops.size() == 1)
2680 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002681 }
2682
2683 // Skip over the add expression until we get to a multiply.
2684 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2685 ++Idx;
2686
Chris Lattnerd934c702004-04-02 20:23:17 +00002687 // If there are mul operands inline them all into this expression.
2688 if (Idx < Ops.size()) {
2689 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002690 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002691 if (Ops.size() > MulOpsInlineThreshold)
2692 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002693 // If we have an mul, expand the mul operands onto the end of the operands
2694 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002695 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002696 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002697 DeletedMul = true;
2698 }
2699
2700 // If we deleted at least one mul, we added operands to the end of the list,
2701 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002702 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002703 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002704 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002705 }
2706
2707 // If there are any add recurrences in the operands list, see if any other
2708 // added values are loop invariant. If so, we can fold them into the
2709 // recurrence.
2710 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2711 ++Idx;
2712
2713 // Scan over all recurrences, trying to fold loop invariants into them.
2714 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2715 // Scan all of the other operands to this mul and add them to the vector if
2716 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002717 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002718 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002719 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002720 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002721 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002722 LIOps.push_back(Ops[i]);
2723 Ops.erase(Ops.begin()+i);
2724 --i; --e;
2725 }
2726
2727 // If we found some loop invariants, fold them into the recurrence.
2728 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002729 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002730 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002731 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002732 const SCEV *Scale = getMulExpr(LIOps);
2733 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2734 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002735
Dan Gohman16206132010-06-30 07:16:37 +00002736 // Build the new addrec. Propagate the NUW and NSW flags if both the
2737 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002738 //
2739 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002740 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002741 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2742 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002743
2744 // If all of the other operands were loop invariant, we are done.
2745 if (Ops.size() == 1) return NewRec;
2746
Nick Lewyckydb66b822011-09-06 05:08:09 +00002747 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002748 for (unsigned i = 0;; ++i)
2749 if (Ops[i] == AddRec) {
2750 Ops[i] = NewRec;
2751 break;
2752 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002753 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002754 }
2755
2756 // Okay, if there weren't any loop invariants to be folded, check to see if
2757 // there are multiple AddRec's with the same loop induction variable being
2758 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002759
2760 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2761 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2762 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2763 // ]]],+,...up to x=2n}.
2764 // Note that the arguments to choose() are always integers with values
2765 // known at compile time, never SCEV objects.
2766 //
2767 // The implementation avoids pointless extra computations when the two
2768 // addrec's are of different length (mathematically, it's equivalent to
2769 // an infinite stream of zeros on the right).
2770 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002771 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002772 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002773 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002774 const SCEVAddRecExpr *OtherAddRec =
2775 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2776 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002777 continue;
2778
Nick Lewycky97756402014-09-01 05:17:15 +00002779 bool Overflow = false;
2780 Type *Ty = AddRec->getType();
2781 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2782 SmallVector<const SCEV*, 7> AddRecOps;
2783 for (int x = 0, xe = AddRec->getNumOperands() +
2784 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002785 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002786 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2787 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2788 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2789 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2790 z < ze && !Overflow; ++z) {
2791 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2792 uint64_t Coeff;
2793 if (LargerThan64Bits)
2794 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2795 else
2796 Coeff = Coeff1*Coeff2;
2797 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2798 const SCEV *Term1 = AddRec->getOperand(y-z);
2799 const SCEV *Term2 = OtherAddRec->getOperand(z);
2800 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002801 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002802 }
Nick Lewycky97756402014-09-01 05:17:15 +00002803 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002804 }
Nick Lewycky97756402014-09-01 05:17:15 +00002805 if (!Overflow) {
2806 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2807 SCEV::FlagAnyWrap);
2808 if (Ops.size() == 2) return NewAddRec;
2809 Ops[Idx] = NewAddRec;
2810 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2811 OpsModified = true;
2812 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2813 if (!AddRec)
2814 break;
2815 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002816 }
Nick Lewycky97756402014-09-01 05:17:15 +00002817 if (OpsModified)
2818 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002819
2820 // Otherwise couldn't fold anything into this recurrence. Move onto the
2821 // next one.
2822 }
2823
2824 // Okay, it looks like we really DO need an mul expr. Check to see if we
2825 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002826 FoldingSetNodeID ID;
2827 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002828 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2829 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002830 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002831 SCEVMulExpr *S =
2832 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2833 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002834 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2835 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002836 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2837 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002838 UniqueSCEVs.InsertNode(S, IP);
2839 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002840 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002841 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002842}
2843
Sanjoy Dasf8570812016-05-29 00:38:22 +00002844/// Get a canonical unsigned division expression, or something simpler if
2845/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002846const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2847 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002848 assert(getEffectiveSCEVType(LHS->getType()) ==
2849 getEffectiveSCEVType(RHS->getType()) &&
2850 "SCEVUDivExpr operand types don't match!");
2851
Dan Gohmana30370b2009-05-04 22:02:23 +00002852 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002853 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002854 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002855 // If the denominator is zero, the result of the udiv is undefined. Don't
2856 // try to analyze it, because the resolution chosen here may differ from
2857 // the resolution chosen in other parts of the compiler.
2858 if (!RHSC->getValue()->isZero()) {
2859 // Determine if the division can be folded into the operands of
2860 // its operands.
2861 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002862 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002863 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002864 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002865 // For non-power-of-two values, effectively round the value up to the
2866 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002867 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002868 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002869 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002870 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002871 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2872 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002873 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2874 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002875 const APInt &StepInt = Step->getAPInt();
2876 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002877 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002878 getZeroExtendExpr(AR, ExtTy) ==
2879 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2880 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002881 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002882 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002883 for (const SCEV *Op : AR->operands())
2884 Operands.push_back(getUDivExpr(Op, RHS));
2885 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002886 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002887 /// Get a canonical UDivExpr for a recurrence.
2888 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2889 // We can currently only fold X%N if X is constant.
2890 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2891 if (StartC && !DivInt.urem(StepInt) &&
2892 getZeroExtendExpr(AR, ExtTy) ==
2893 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2894 getZeroExtendExpr(Step, ExtTy),
2895 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002896 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002897 const APInt &StartRem = StartInt.urem(StepInt);
2898 if (StartRem != 0)
2899 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2900 AR->getLoop(), SCEV::FlagNW);
2901 }
2902 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002903 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2904 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2905 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002906 for (const SCEV *Op : M->operands())
2907 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002908 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2909 // Find an operand that's safely divisible.
2910 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2911 const SCEV *Op = M->getOperand(i);
2912 const SCEV *Div = getUDivExpr(Op, RHSC);
2913 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2914 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2915 M->op_end());
2916 Operands[i] = Div;
2917 return getMulExpr(Operands);
2918 }
2919 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002920 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002921 // (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 +00002922 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002923 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002924 for (const SCEV *Op : A->operands())
2925 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002926 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2927 Operands.clear();
2928 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2929 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2930 if (isa<SCEVUDivExpr>(Op) ||
2931 getMulExpr(Op, RHS) != A->getOperand(i))
2932 break;
2933 Operands.push_back(Op);
2934 }
2935 if (Operands.size() == A->getNumOperands())
2936 return getAddExpr(Operands);
2937 }
2938 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002939
Dan Gohmanacd700a2010-04-22 01:35:11 +00002940 // Fold if both operands are constant.
2941 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2942 Constant *LHSCV = LHSC->getValue();
2943 Constant *RHSCV = RHSC->getValue();
2944 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2945 RHSCV)));
2946 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002947 }
2948 }
2949
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002950 FoldingSetNodeID ID;
2951 ID.AddInteger(scUDivExpr);
2952 ID.AddPointer(LHS);
2953 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002954 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002955 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002956 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2957 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002958 UniqueSCEVs.InsertNode(S, IP);
2959 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002960}
2961
Nick Lewycky31eaca52014-01-27 10:04:03 +00002962static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002963 APInt A = C1->getAPInt().abs();
2964 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002965 uint32_t ABW = A.getBitWidth();
2966 uint32_t BBW = B.getBitWidth();
2967
2968 if (ABW > BBW)
2969 B = B.zext(ABW);
2970 else if (ABW < BBW)
2971 A = A.zext(BBW);
2972
2973 return APIntOps::GreatestCommonDivisor(A, B);
2974}
2975
Sanjoy Dasf8570812016-05-29 00:38:22 +00002976/// Get a canonical unsigned division expression, or something simpler if
2977/// possible. There is no representation for an exact udiv in SCEV IR, but we
2978/// can attempt to remove factors from the LHS and RHS. We can't do this when
2979/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002980const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2981 const SCEV *RHS) {
2982 // TODO: we could try to find factors in all sorts of things, but for now we
2983 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2984 // end of this file for inspiration.
2985
2986 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
Eli Friedmanf1f49c82017-01-18 23:56:42 +00002987 if (!Mul || !Mul->hasNoUnsignedWrap())
Nick Lewycky31eaca52014-01-27 10:04:03 +00002988 return getUDivExpr(LHS, RHS);
2989
2990 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2991 // If the mulexpr multiplies by a constant, then that constant must be the
2992 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002993 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002994 if (LHSCst == RHSCst) {
2995 SmallVector<const SCEV *, 2> Operands;
2996 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2997 return getMulExpr(Operands);
2998 }
2999
3000 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3001 // that there's a factor provided by one of the other terms. We need to
3002 // check.
3003 APInt Factor = gcd(LHSCst, RHSCst);
3004 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003005 LHSCst =
3006 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3007 RHSCst =
3008 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00003009 SmallVector<const SCEV *, 2> Operands;
3010 Operands.push_back(LHSCst);
3011 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3012 LHS = getMulExpr(Operands);
3013 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00003014 Mul = dyn_cast<SCEVMulExpr>(LHS);
3015 if (!Mul)
3016 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00003017 }
3018 }
3019 }
3020
3021 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3022 if (Mul->getOperand(i) == RHS) {
3023 SmallVector<const SCEV *, 2> Operands;
3024 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3025 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3026 return getMulExpr(Operands);
3027 }
3028 }
3029
3030 return getUDivExpr(LHS, RHS);
3031}
Chris Lattnerd934c702004-04-02 20:23:17 +00003032
Sanjoy Dasf8570812016-05-29 00:38:22 +00003033/// Get an add recurrence expression for the specified loop. Simplify the
3034/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00003035const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3036 const Loop *L,
3037 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003038 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00003039 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00003040 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00003041 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00003042 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003043 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00003044 }
3045
3046 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00003047 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00003048}
3049
Sanjoy Dasf8570812016-05-29 00:38:22 +00003050/// Get an add recurrence expression for the specified loop. Simplify the
3051/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00003052const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00003053ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00003054 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003055 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003056#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003057 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003058 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003059 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003060 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003061 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00003062 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003063 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00003064#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00003065
Dan Gohmanbe928e32008-06-18 16:23:07 +00003066 if (Operands.back()->isZero()) {
3067 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00003068 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00003069 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003070
Dan Gohmancf9c64e2010-02-19 18:49:22 +00003071 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3072 // use that information to infer NUW and NSW flags. However, computing a
3073 // BE count requires calling getAddRecExpr, so we may not yet have a
3074 // meaningful BE count at this point (and if we don't, we'd be stuck
3075 // with a SCEVCouldNotCompute as the cached BE count).
3076
Sanjoy Das81401d42015-01-10 23:41:24 +00003077 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003078
Dan Gohman223a5d22008-08-08 18:33:12 +00003079 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00003080 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00003081 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003082 if (L->contains(NestedLoop)
3083 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3084 : (!NestedLoop->contains(L) &&
3085 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003086 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00003087 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00003088 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00003089 // AddRecs require their operands be loop-invariant with respect to their
3090 // loops. Don't perform this transformation if it would break this
3091 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00003092 bool AllInvariant = all_of(
3093 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003094
Dan Gohmancc030b72009-06-26 22:36:20 +00003095 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003096 // Create a recurrence for the outer loop with the same step size.
3097 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003098 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3099 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003100 SCEV::NoWrapFlags OuterFlags =
3101 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003102
3103 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003104 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3105 return isLoopInvariant(Op, NestedLoop);
3106 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003107
Andrew Trick8b55b732011-03-14 16:50:06 +00003108 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003109 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003110 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003111 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3112 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003113 SCEV::NoWrapFlags InnerFlags =
3114 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003115 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3116 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003117 }
3118 // Reset Operands to its original state.
3119 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003120 }
3121 }
3122
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003123 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3124 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003125 FoldingSetNodeID ID;
3126 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003127 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3128 ID.AddPointer(Operands[i]);
3129 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003130 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003131 SCEVAddRecExpr *S =
3132 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3133 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003134 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3135 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003136 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3137 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003138 UniqueSCEVs.InsertNode(S, IP);
3139 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003140 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003141 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003142}
3143
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003144const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003145ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3146 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3147 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003148 // getSCEV(Base)->getType() has the same address space as Base->getType()
3149 // because SCEV::getType() preserves the address space.
3150 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3151 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3152 // instruction to its SCEV, because the Instruction may be guarded by control
3153 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003154 // context. This can be fixed similarly to how these flags are handled for
3155 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003156 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3157 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003158
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003159 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003160 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003161 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003162 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003163 for (const SCEV *IndexExpr : IndexExprs) {
3164 // Compute the (potentially symbolic) offset in bytes for this index.
3165 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3166 // For a struct, add the member offset.
3167 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3168 unsigned FieldNo = Index->getZExtValue();
3169 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3170
3171 // Add the field offset to the running total offset.
3172 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3173
3174 // Update CurTy to the type of the field at Index.
3175 CurTy = STy->getTypeAtIndex(Index);
3176 } else {
3177 // Update CurTy to its element type.
3178 CurTy = cast<SequentialType>(CurTy)->getElementType();
3179 // For an array, add the element offset, explicitly scaled.
3180 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3181 // Getelementptr indices are signed.
3182 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3183
3184 // Multiply the index by the element size to compute the element offset.
3185 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3186
3187 // Add the element offset to the running total offset.
3188 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3189 }
3190 }
3191
3192 // Add the total offset from all the GEP indices to the base.
3193 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3194}
3195
Dan Gohmanabd17092009-06-24 14:49:00 +00003196const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3197 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003198 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003199 return getSMaxExpr(Ops);
3200}
3201
Dan Gohmanaf752342009-07-07 17:06:11 +00003202const SCEV *
3203ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003204 assert(!Ops.empty() && "Cannot get empty smax!");
3205 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003206#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003207 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003208 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003209 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003210 "SCEVSMaxExpr operand types don't match!");
3211#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003212
3213 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003214 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003215
3216 // If there are any constants, fold them together.
3217 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003218 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003219 ++Idx;
3220 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003222 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003223 ConstantInt *Fold = ConstantInt::get(
3224 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003225 Ops[0] = getConstant(Fold);
3226 Ops.erase(Ops.begin()+1); // Erase the folded element
3227 if (Ops.size() == 1) return Ops[0];
3228 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003229 }
3230
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003231 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003232 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3233 Ops.erase(Ops.begin());
3234 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3236 // If we have an smax with a constant maximum-int, it will always be
3237 // maximum-int.
3238 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003239 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003240
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003241 if (Ops.size() == 1) return Ops[0];
3242 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003243
3244 // Find the first SMax
3245 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3246 ++Idx;
3247
3248 // Check to see if one of the operands is an SMax. If so, expand its operands
3249 // onto our operand list, and recurse to simplify.
3250 if (Idx < Ops.size()) {
3251 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003252 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003253 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003254 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003255 DeletedSMax = true;
3256 }
3257
3258 if (DeletedSMax)
3259 return getSMaxExpr(Ops);
3260 }
3261
3262 // Okay, check to see if the same value occurs in the operand list twice. If
3263 // so, delete one. Since we sorted the list, these values are required to
3264 // be adjacent.
3265 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003266 // X smax Y smax Y --> X smax Y
3267 // X smax Y --> X, if X is always greater than Y
3268 if (Ops[i] == Ops[i+1] ||
3269 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3270 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3271 --i; --e;
3272 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003273 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3274 --i; --e;
3275 }
3276
3277 if (Ops.size() == 1) return Ops[0];
3278
3279 assert(!Ops.empty() && "Reduced smax down to nothing!");
3280
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003281 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003282 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003283 FoldingSetNodeID ID;
3284 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003285 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3286 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003287 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003288 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003289 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3290 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003291 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3292 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003293 UniqueSCEVs.InsertNode(S, IP);
3294 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003295}
3296
Dan Gohmanabd17092009-06-24 14:49:00 +00003297const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3298 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003299 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003300 return getUMaxExpr(Ops);
3301}
3302
Dan Gohmanaf752342009-07-07 17:06:11 +00003303const SCEV *
3304ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003305 assert(!Ops.empty() && "Cannot get empty umax!");
3306 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003307#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003308 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003309 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003310 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003311 "SCEVUMaxExpr operand types don't match!");
3312#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003313
3314 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003315 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003316
3317 // If there are any constants, fold them together.
3318 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003319 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003320 ++Idx;
3321 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003322 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003323 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003324 ConstantInt *Fold = ConstantInt::get(
3325 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003326 Ops[0] = getConstant(Fold);
3327 Ops.erase(Ops.begin()+1); // Erase the folded element
3328 if (Ops.size() == 1) return Ops[0];
3329 LHSC = cast<SCEVConstant>(Ops[0]);
3330 }
3331
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003332 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003333 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3334 Ops.erase(Ops.begin());
3335 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003336 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3337 // If we have an umax with a constant maximum-int, it will always be
3338 // maximum-int.
3339 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003340 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003341
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003342 if (Ops.size() == 1) return Ops[0];
3343 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003344
3345 // Find the first UMax
3346 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3347 ++Idx;
3348
3349 // Check to see if one of the operands is a UMax. If so, expand its operands
3350 // onto our operand list, and recurse to simplify.
3351 if (Idx < Ops.size()) {
3352 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003353 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003354 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003355 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003356 DeletedUMax = true;
3357 }
3358
3359 if (DeletedUMax)
3360 return getUMaxExpr(Ops);
3361 }
3362
3363 // Okay, check to see if the same value occurs in the operand list twice. If
3364 // so, delete one. Since we sorted the list, these values are required to
3365 // be adjacent.
3366 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003367 // X umax Y umax Y --> X umax Y
3368 // X umax Y --> X, if X is always greater than Y
3369 if (Ops[i] == Ops[i+1] ||
3370 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3371 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3372 --i; --e;
3373 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003374 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3375 --i; --e;
3376 }
3377
3378 if (Ops.size() == 1) return Ops[0];
3379
3380 assert(!Ops.empty() && "Reduced umax down to nothing!");
3381
3382 // Okay, it looks like we really DO need a umax expr. Check to see if we
3383 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003384 FoldingSetNodeID ID;
3385 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003386 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3387 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003388 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003389 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003390 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3391 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003392 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3393 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003394 UniqueSCEVs.InsertNode(S, IP);
3395 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003396}
3397
Dan Gohmanabd17092009-06-24 14:49:00 +00003398const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3399 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003400 // ~smax(~x, ~y) == smin(x, y).
3401 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3402}
3403
Dan Gohmanabd17092009-06-24 14:49:00 +00003404const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3405 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003406 // ~umax(~x, ~y) == umin(x, y)
3407 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3408}
3409
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003410const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003411 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003412 // constant expression and then folding it back into a ConstantInt.
3413 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003414 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003415}
3416
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003417const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3418 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003419 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003420 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003421 // constant expression and then folding it back into a ConstantInt.
3422 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003423 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003424 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003425}
3426
Dan Gohmanaf752342009-07-07 17:06:11 +00003427const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003428 // Don't attempt to do anything other than create a SCEVUnknown object
3429 // here. createSCEV only calls getUnknown after checking for all other
3430 // interesting possibilities, and any other code that calls getUnknown
3431 // is doing so in order to hide a value from SCEV canonicalization.
3432
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003433 FoldingSetNodeID ID;
3434 ID.AddInteger(scUnknown);
3435 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003436 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003437 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3438 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3439 "Stale SCEVUnknown in uniquing map!");
3440 return S;
3441 }
3442 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3443 FirstUnknown);
3444 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003445 UniqueSCEVs.InsertNode(S, IP);
3446 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003447}
3448
Chris Lattnerd934c702004-04-02 20:23:17 +00003449//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003450// Basic SCEV Analysis and PHI Idiom Recognition Code
3451//
3452
Sanjoy Dasf8570812016-05-29 00:38:22 +00003453/// Test if values of the given type are analyzable within the SCEV
3454/// framework. This primarily includes integer types, and it can optionally
3455/// include pointer types if the ScalarEvolution class has access to
3456/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003457bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003458 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003459 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003460}
3461
Sanjoy Dasf8570812016-05-29 00:38:22 +00003462/// Return the size in bits of the specified type, for which isSCEVable must
3463/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003464uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003465 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003466 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003467}
3468
Sanjoy Dasf8570812016-05-29 00:38:22 +00003469/// Return a type with the same bitwidth as the given type and which represents
3470/// how SCEV will treat the given type, for which isSCEVable must return
3471/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003472Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003473 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3474
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003475 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003476 return Ty;
3477
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003478 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003479 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003480 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003481}
Chris Lattnerd934c702004-04-02 20:23:17 +00003482
Max Kazantsev2e44d292017-03-31 12:05:30 +00003483Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3484 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3485}
3486
Dan Gohmanaf752342009-07-07 17:06:11 +00003487const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003488 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003489}
3490
Sanjoy Das7d752672015-12-08 04:32:54 +00003491bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003492 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3493 auto *SU = dyn_cast<SCEVUnknown>(S);
3494 return SU && SU->getValue() == nullptr;
3495 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003496
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003497 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003498}
3499
Wei Mia49559b2016-02-04 01:27:38 +00003500bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003501 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003502 if (I != HasRecMap.end())
3503 return I->second;
3504
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003505 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003506 HasRecMap.insert({S, FoundAddRec});
3507 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003508}
3509
Wei Mi785858c2016-08-09 20:37:50 +00003510/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3511/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3512/// offset I, then return {S', I}, else return {\p S, nullptr}.
3513static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3514 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3515 if (!Add)
3516 return {S, nullptr};
3517
3518 if (Add->getNumOperands() != 2)
3519 return {S, nullptr};
3520
3521 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3522 if (!ConstOp)
3523 return {S, nullptr};
3524
3525 return {Add->getOperand(1), ConstOp->getValue()};
3526}
3527
3528/// Return the ValueOffsetPair set for \p S. \p S can be represented
3529/// by the value and offset from any ValueOffsetPair in the set.
3530SetVector<ScalarEvolution::ValueOffsetPair> *
3531ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003532 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3533 if (SI == ExprValueMap.end())
3534 return nullptr;
3535#ifndef NDEBUG
3536 if (VerifySCEVMap) {
3537 // Check there is no dangling Value in the set returned.
3538 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003539 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003540 }
3541#endif
3542 return &SI->second;
3543}
3544
Wei Mi785858c2016-08-09 20:37:50 +00003545/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3546/// cannot be used separately. eraseValueFromMap should be used to remove
3547/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003548void ScalarEvolution::eraseValueFromMap(Value *V) {
3549 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3550 if (I != ValueExprMap.end()) {
3551 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003552 // Remove {V, 0} from the set of ExprValueMap[S]
3553 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3554 SV->remove({V, nullptr});
3555
3556 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3557 const SCEV *Stripped;
3558 ConstantInt *Offset;
3559 std::tie(Stripped, Offset) = splitAddExpr(S);
3560 if (Offset != nullptr) {
3561 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3562 SV->remove({V, Offset});
3563 }
Wei Mia49559b2016-02-04 01:27:38 +00003564 ValueExprMap.erase(V);
3565 }
3566}
3567
Sanjoy Dasf8570812016-05-29 00:38:22 +00003568/// Return an existing SCEV if it exists, otherwise analyze the expression and
3569/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003570const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003571 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003572
Jingyue Wu42f1d672015-07-28 18:22:40 +00003573 const SCEV *S = getExistingSCEV(V);
3574 if (S == nullptr) {
3575 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003576 // During PHI resolution, it is possible to create two SCEVs for the same
3577 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003578 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003579 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003580 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003581 if (Pair.second) {
3582 ExprValueMap[S].insert({V, nullptr});
3583
3584 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3585 // ExprValueMap.
3586 const SCEV *Stripped = S;
3587 ConstantInt *Offset = nullptr;
3588 std::tie(Stripped, Offset) = splitAddExpr(S);
3589 // If stripped is SCEVUnknown, don't bother to save
3590 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3591 // increase the complexity of the expansion code.
3592 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3593 // because it may generate add/sub instead of GEP in SCEV expansion.
3594 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3595 !isa<GetElementPtrInst>(V))
3596 ExprValueMap[Stripped].insert({V, Offset});
3597 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003598 }
3599 return S;
3600}
3601
3602const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3603 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3604
Shuxin Yangefc4c012013-07-08 17:33:13 +00003605 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3606 if (I != ValueExprMap.end()) {
3607 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003608 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003609 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003610 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003611 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003612 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003613 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003614}
3615
Sanjoy Dasf8570812016-05-29 00:38:22 +00003616/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003617///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003618const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3619 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003620 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003621 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003622 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003623
Chris Lattner229907c2011-07-18 04:54:35 +00003624 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003625 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003626 return getMulExpr(
3627 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003628}
3629
Sanjoy Dasf8570812016-05-29 00:38:22 +00003630/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003631const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003632 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003633 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003634 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003635
Chris Lattner229907c2011-07-18 04:54:35 +00003636 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003637 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003638 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003639 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003640 return getMinusSCEV(AllOnes, V);
3641}
3642
Chris Lattnerfc877522011-01-09 22:26:35 +00003643const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003644 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003645 // Fast path: X - X --> 0.
3646 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003647 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003648
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003649 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3650 // makes it so that we cannot make much use of NUW.
3651 auto AddFlags = SCEV::FlagAnyWrap;
3652 const bool RHSIsNotMinSigned =
3653 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3654 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3655 // Let M be the minimum representable signed value. Then (-1)*RHS
3656 // signed-wraps if and only if RHS is M. That can happen even for
3657 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3658 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3659 // (-1)*RHS, we need to prove that RHS != M.
3660 //
3661 // If LHS is non-negative and we know that LHS - RHS does not
3662 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3663 // either by proving that RHS > M or that LHS >= 0.
3664 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3665 AddFlags = SCEV::FlagNSW;
3666 }
3667 }
3668
3669 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3670 // RHS is NSW and LHS >= 0.
3671 //
3672 // The difficulty here is that the NSW flag may have been proven
3673 // relative to a loop that is to be found in a recurrence in LHS and
3674 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3675 // larger scope than intended.
3676 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3677
3678 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003679}
3680
Dan Gohmanaf752342009-07-07 17:06:11 +00003681const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003682ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3683 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003684 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3685 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003686 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003687 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003688 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003689 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003690 return getTruncateExpr(V, Ty);
3691 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003692}
3693
Dan Gohmanaf752342009-07-07 17:06:11 +00003694const SCEV *
3695ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003696 Type *Ty) {
3697 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003698 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3699 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003700 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003701 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003702 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003703 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003704 return getTruncateExpr(V, Ty);
3705 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003706}
3707
Dan Gohmanaf752342009-07-07 17:06:11 +00003708const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003709ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3710 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003711 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3712 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003713 "Cannot noop or zero extend with non-integer arguments!");
3714 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3715 "getNoopOrZeroExtend cannot truncate!");
3716 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3717 return V; // No conversion
3718 return getZeroExtendExpr(V, Ty);
3719}
3720
Dan Gohmanaf752342009-07-07 17:06:11 +00003721const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003722ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3723 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003724 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3725 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003726 "Cannot noop or sign extend with non-integer arguments!");
3727 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3728 "getNoopOrSignExtend cannot truncate!");
3729 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3730 return V; // No conversion
3731 return getSignExtendExpr(V, Ty);
3732}
3733
Dan Gohmanaf752342009-07-07 17:06:11 +00003734const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003735ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3736 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003737 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3738 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003739 "Cannot noop or any extend with non-integer arguments!");
3740 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3741 "getNoopOrAnyExtend cannot truncate!");
3742 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3743 return V; // No conversion
3744 return getAnyExtendExpr(V, Ty);
3745}
3746
Dan Gohmanaf752342009-07-07 17:06:11 +00003747const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003748ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3749 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003750 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3751 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003752 "Cannot truncate or noop with non-integer arguments!");
3753 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3754 "getTruncateOrNoop cannot extend!");
3755 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3756 return V; // No conversion
3757 return getTruncateExpr(V, Ty);
3758}
3759
Dan Gohmanabd17092009-06-24 14:49:00 +00003760const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3761 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003762 const SCEV *PromotedLHS = LHS;
3763 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003764
3765 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3766 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3767 else
3768 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3769
3770 return getUMaxExpr(PromotedLHS, PromotedRHS);
3771}
3772
Dan Gohmanabd17092009-06-24 14:49:00 +00003773const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3774 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003775 const SCEV *PromotedLHS = LHS;
3776 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003777
3778 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3779 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3780 else
3781 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3782
3783 return getUMinExpr(PromotedLHS, PromotedRHS);
3784}
3785
Andrew Trick87716c92011-03-17 23:51:11 +00003786const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3787 // A pointer operand may evaluate to a nonpointer expression, such as null.
3788 if (!V->getType()->isPointerTy())
3789 return V;
3790
3791 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3792 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003793 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003794 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003795 for (const SCEV *NAryOp : NAry->operands()) {
3796 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003797 // Cannot find the base of an expression with multiple pointer operands.
3798 if (PtrOp)
3799 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003800 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003801 }
3802 }
3803 if (!PtrOp)
3804 return V;
3805 return getPointerBase(PtrOp);
3806 }
3807 return V;
3808}
3809
Sanjoy Dasf8570812016-05-29 00:38:22 +00003810/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003811static void
3812PushDefUseChildren(Instruction *I,
3813 SmallVectorImpl<Instruction *> &Worklist) {
3814 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003815 for (User *U : I->users())
3816 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003817}
3818
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003819void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003820 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003821 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003822
Dan Gohman0b89dff2009-07-25 01:13:03 +00003823 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003824 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003825 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003826 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003827 if (!Visited.insert(I).second)
3828 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003829
Sanjoy Das63914592015-10-18 00:29:20 +00003830 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003831 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003832 const SCEV *Old = It->second;
3833
Dan Gohman0b89dff2009-07-25 01:13:03 +00003834 // Short-circuit the def-use traversal if the symbolic name
3835 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003836 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003837 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003838
Dan Gohman0b89dff2009-07-25 01:13:03 +00003839 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003840 // structure, it's a PHI that's in the progress of being computed
3841 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3842 // additional loop trip count information isn't going to change anything.
3843 // In the second case, createNodeForPHI will perform the necessary
3844 // updates on its own when it gets to that point. In the third, we do
3845 // want to forget the SCEVUnknown.
3846 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003847 !isa<SCEVUnknown>(Old) ||
3848 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003849 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003850 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003851 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003852 }
3853
3854 PushDefUseChildren(I, Worklist);
3855 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003856}
Chris Lattnerd934c702004-04-02 20:23:17 +00003857
Benjamin Kramer83709b12015-11-16 09:01:28 +00003858namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003859class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3860public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003861 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003862 ScalarEvolution &SE) {
3863 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003864 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003865 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3866 }
3867
3868 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3869 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3870
3871 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3872 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3873 Valid = false;
3874 return Expr;
3875 }
3876
3877 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3878 // Only allow AddRecExprs for this loop.
3879 if (Expr->getLoop() == L)
3880 return Expr->getStart();
3881 Valid = false;
3882 return Expr;
3883 }
3884
3885 bool isValid() { return Valid; }
3886
3887private:
3888 const Loop *L;
3889 bool Valid;
3890};
3891
3892class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3893public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003894 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003895 ScalarEvolution &SE) {
3896 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003897 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003898 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3899 }
3900
3901 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3902 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3903
3904 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3905 // Only allow AddRecExprs for this loop.
3906 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3907 Valid = false;
3908 return Expr;
3909 }
3910
3911 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3912 if (Expr->getLoop() == L && Expr->isAffine())
3913 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3914 Valid = false;
3915 return Expr;
3916 }
3917 bool isValid() { return Valid; }
3918
3919private:
3920 const Loop *L;
3921 bool Valid;
3922};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003923} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003924
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003925SCEV::NoWrapFlags
3926ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3927 if (!AR->isAffine())
3928 return SCEV::FlagAnyWrap;
3929
3930 typedef OverflowingBinaryOperator OBO;
3931 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3932
3933 if (!AR->hasNoSignedWrap()) {
3934 ConstantRange AddRecRange = getSignedRange(AR);
3935 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3936
3937 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3938 Instruction::Add, IncRange, OBO::NoSignedWrap);
3939 if (NSWRegion.contains(AddRecRange))
3940 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3941 }
3942
3943 if (!AR->hasNoUnsignedWrap()) {
3944 ConstantRange AddRecRange = getUnsignedRange(AR);
3945 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3946
3947 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3948 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3949 if (NUWRegion.contains(AddRecRange))
3950 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3951 }
3952
3953 return Result;
3954}
3955
Sanjoy Das118d9192016-03-31 05:14:22 +00003956namespace {
3957/// Represents an abstract binary operation. This may exist as a
3958/// normal instruction or constant expression, or may have been
3959/// derived from an expression tree.
3960struct BinaryOp {
3961 unsigned Opcode;
3962 Value *LHS;
3963 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003964 bool IsNSW;
3965 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003966
3967 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3968 /// constant expression.
3969 Operator *Op;
3970
3971 explicit BinaryOp(Operator *Op)
3972 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003973 IsNSW(false), IsNUW(false), Op(Op) {
3974 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3975 IsNSW = OBO->hasNoSignedWrap();
3976 IsNUW = OBO->hasNoUnsignedWrap();
3977 }
3978 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003979
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003980 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3981 bool IsNUW = false)
3982 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3983 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003984};
3985}
3986
3987
3988/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003989static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003990 auto *Op = dyn_cast<Operator>(V);
3991 if (!Op)
3992 return None;
3993
3994 // Implementation detail: all the cleverness here should happen without
3995 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3996 // SCEV expressions when possible, and we should not break that.
3997
3998 switch (Op->getOpcode()) {
3999 case Instruction::Add:
4000 case Instruction::Sub:
4001 case Instruction::Mul:
4002 case Instruction::UDiv:
4003 case Instruction::And:
4004 case Instruction::Or:
4005 case Instruction::AShr:
4006 case Instruction::Shl:
4007 return BinaryOp(Op);
4008
4009 case Instruction::Xor:
4010 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
Craig Topperbcfd2d12017-04-20 16:56:25 +00004011 // If the RHS of the xor is a signmask, then this is just an add.
4012 // Instcombine turns add of signmask into xor as a strength reduction step.
4013 if (RHSC->getValue().isSignMask())
Sanjoy Das118d9192016-03-31 05:14:22 +00004014 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4015 return BinaryOp(Op);
4016
4017 case Instruction::LShr:
4018 // Turn logical shift right of a constant into a unsigned divide.
4019 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4020 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4021
4022 // If the shift count is not less than the bitwidth, the result of
4023 // the shift is undefined. Don't try to analyze it, because the
4024 // resolution chosen here may differ from the resolution chosen in
4025 // other parts of the compiler.
4026 if (SA->getValue().ult(BitWidth)) {
4027 Constant *X =
4028 ConstantInt::get(SA->getContext(),
4029 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4030 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4031 }
4032 }
4033 return BinaryOp(Op);
4034
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004035 case Instruction::ExtractValue: {
4036 auto *EVI = cast<ExtractValueInst>(Op);
4037 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4038 break;
4039
4040 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4041 if (!CI)
4042 break;
4043
4044 if (auto *F = CI->getCalledFunction())
4045 switch (F->getIntrinsicID()) {
4046 case Intrinsic::sadd_with_overflow:
4047 case Intrinsic::uadd_with_overflow: {
4048 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4049 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4050 CI->getArgOperand(1));
4051
4052 // Now that we know that all uses of the arithmetic-result component of
4053 // CI are guarded by the overflow check, we can go ahead and pretend
4054 // that the arithmetic is non-overflowing.
4055 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4056 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4057 CI->getArgOperand(1), /* IsNSW = */ true,
4058 /* IsNUW = */ false);
4059 else
4060 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4061 CI->getArgOperand(1), /* IsNSW = */ false,
4062 /* IsNUW*/ true);
4063 }
4064
4065 case Intrinsic::ssub_with_overflow:
4066 case Intrinsic::usub_with_overflow:
4067 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4068 CI->getArgOperand(1));
4069
4070 case Intrinsic::smul_with_overflow:
4071 case Intrinsic::umul_with_overflow:
4072 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4073 CI->getArgOperand(1));
4074 default:
4075 break;
4076 }
4077 }
4078
Sanjoy Das118d9192016-03-31 05:14:22 +00004079 default:
4080 break;
4081 }
4082
4083 return None;
4084}
4085
Sanjoy Das55015d22015-10-02 23:09:44 +00004086const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4087 const Loop *L = LI.getLoopFor(PN->getParent());
4088 if (!L || L->getHeader() != PN->getParent())
4089 return nullptr;
4090
4091 // The loop may have multiple entrances or multiple exits; we can analyze
4092 // this phi as an addrec if it has a unique entry value and a unique
4093 // backedge value.
4094 Value *BEValueV = nullptr, *StartValueV = nullptr;
4095 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4096 Value *V = PN->getIncomingValue(i);
4097 if (L->contains(PN->getIncomingBlock(i))) {
4098 if (!BEValueV) {
4099 BEValueV = V;
4100 } else if (BEValueV != V) {
4101 BEValueV = nullptr;
4102 break;
4103 }
4104 } else if (!StartValueV) {
4105 StartValueV = V;
4106 } else if (StartValueV != V) {
4107 StartValueV = nullptr;
4108 break;
4109 }
4110 }
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004111 if (!BEValueV || !StartValueV)
4112 return nullptr;
Sanjoy Das55015d22015-10-02 23:09:44 +00004113
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004114 // While we are analyzing this PHI node, handle its value symbolically.
4115 const SCEV *SymbolicName = getUnknown(PN);
4116 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4117 "PHI node already processed?");
4118 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004119
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004120 // Using this symbolic name for the PHI, analyze the value coming around
4121 // the back-edge.
4122 const SCEV *BEValue = getSCEV(BEValueV);
Sanjoy Das55015d22015-10-02 23:09:44 +00004123
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004124 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4125 // has a special value for the first iteration of the loop.
4126
4127 // If the value coming around the backedge is an add with the symbolic
4128 // value we just inserted, then we found a simple induction variable!
4129 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4130 // If there is a single occurrence of the symbolic value, replace it
4131 // with a recurrence.
4132 unsigned FoundIndex = Add->getNumOperands();
4133 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4134 if (Add->getOperand(i) == SymbolicName)
4135 if (FoundIndex == e) {
4136 FoundIndex = i;
4137 break;
4138 }
4139
4140 if (FoundIndex != Add->getNumOperands()) {
4141 // Create an add with everything but the specified operand.
4142 SmallVector<const SCEV *, 8> Ops;
Sanjoy Das55015d22015-10-02 23:09:44 +00004143 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004144 if (i != FoundIndex)
4145 Ops.push_back(Add->getOperand(i));
4146 const SCEV *Accum = getAddExpr(Ops);
4147
4148 // This is not a valid addrec if the step amount is varying each
4149 // loop iteration, but is not itself an addrec in this loop.
4150 if (isLoopInvariant(Accum, L) ||
4151 (isa<SCEVAddRecExpr>(Accum) &&
4152 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4153 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4154
4155 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4156 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4157 if (BO->IsNUW)
4158 Flags = setFlags(Flags, SCEV::FlagNUW);
4159 if (BO->IsNSW)
4160 Flags = setFlags(Flags, SCEV::FlagNSW);
4161 }
4162 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4163 // If the increment is an inbounds GEP, then we know the address
4164 // space cannot be wrapped around. We cannot make any guarantee
4165 // about signed or unsigned overflow because pointers are
4166 // unsigned but we may have a negative index from the base
4167 // pointer. We can guarantee that no unsigned wrap occurs if the
4168 // indices form a positive value.
4169 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4170 Flags = setFlags(Flags, SCEV::FlagNW);
4171
4172 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4173 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4174 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohman6635bb22010-04-12 07:49:36 +00004175 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004176
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004177 // We cannot transfer nuw and nsw flags from subtraction
4178 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4179 // for instance.
Dan Gohman6635bb22010-04-12 07:49:36 +00004180 }
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004181
Sanjoy Das55015d22015-10-02 23:09:44 +00004182 const SCEV *StartVal = getSCEV(StartValueV);
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004183 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4184
4185 // Okay, for the entire analysis of this edge we assumed the PHI
4186 // to be symbolic. We now need to go back and purge all of the
4187 // entries for the scalars that use the symbolic expression.
4188 forgetSymbolicName(PN, SymbolicName);
4189 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4190
4191 // We can add Flags to the post-inc expression only if we
4192 // know that it us *undefined behavior* for BEValueV to
4193 // overflow.
4194 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4195 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4196 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4197
4198 return PHISCEV;
Chris Lattnerd934c702004-04-02 20:23:17 +00004199 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004200 }
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004201 } else {
4202 // Otherwise, this could be a loop like this:
4203 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4204 // In this case, j = {1,+,1} and BEValue is j.
4205 // Because the other in-value of i (0) fits the evolution of BEValue
4206 // i really is an addrec evolution.
4207 //
4208 // We can generalize this saying that i is the shifted value of BEValue
4209 // by one iteration:
4210 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4211 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4212 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4213 if (Shifted != getCouldNotCompute() &&
4214 Start != getCouldNotCompute()) {
4215 const SCEV *StartVal = getSCEV(StartValueV);
4216 if (Start == StartVal) {
4217 // Okay, for the entire analysis of this edge we assumed the PHI
4218 // to be symbolic. We now need to go back and purge all of the
4219 // entries for the scalars that use the symbolic expression.
4220 forgetSymbolicName(PN, SymbolicName);
4221 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4222 return Shifted;
4223 }
4224 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004225 }
4226
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004227 // Remove the temporary PHI node SCEV that has been inserted while intending
4228 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4229 // as it will prevent later (possibly simpler) SCEV expressions to be added
4230 // to the ValueExprMap.
4231 eraseValueFromMap(PN);
4232
Sanjoy Das55015d22015-10-02 23:09:44 +00004233 return nullptr;
4234}
4235
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004236// Checks if the SCEV S is available at BB. S is considered available at BB
4237// if S can be materialized at BB without introducing a fault.
4238static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4239 BasicBlock *BB) {
4240 struct CheckAvailable {
4241 bool TraversalDone = false;
4242 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004243
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004244 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4245 BasicBlock *BB = nullptr;
4246 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004247
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004248 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4249 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004250
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004251 bool setUnavailable() {
4252 TraversalDone = true;
4253 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004254 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004255 }
4256
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004257 bool follow(const SCEV *S) {
4258 switch (S->getSCEVType()) {
4259 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4260 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004261 // These expressions are available if their operand(s) is/are.
4262 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004263
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004264 case scAddRecExpr: {
4265 // We allow add recurrences that are on the loop BB is in, or some
4266 // outer loop. This guarantees availability because the value of the
4267 // add recurrence at BB is simply the "current" value of the induction
4268 // variable. We can relax this in the future; for instance an add
4269 // recurrence on a sibling dominating loop is also available at BB.
4270 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4271 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004272 return true;
4273
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004274 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004275 }
4276
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004277 case scUnknown: {
4278 // For SCEVUnknown, we check for simple dominance.
4279 const auto *SU = cast<SCEVUnknown>(S);
4280 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004281
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004282 if (isa<Argument>(V))
4283 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004284
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004285 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4286 return false;
4287
4288 return setUnavailable();
4289 }
4290
4291 case scUDivExpr:
4292 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004293 // We do not try to smart about these at all.
4294 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004295 }
4296 llvm_unreachable("switch should be fully covered!");
4297 }
4298
4299 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004300 };
4301
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004302 CheckAvailable CA(L, BB, DT);
4303 SCEVTraversal<CheckAvailable> ST(CA);
4304
4305 ST.visitAll(S);
4306 return CA.Available;
4307}
4308
4309// Try to match a control flow sequence that branches out at BI and merges back
4310// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4311// match.
4312static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4313 Value *&C, Value *&LHS, Value *&RHS) {
4314 C = BI->getCondition();
4315
4316 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4317 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4318
4319 if (!LeftEdge.isSingleEdge())
4320 return false;
4321
4322 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4323
4324 Use &LeftUse = Merge->getOperandUse(0);
4325 Use &RightUse = Merge->getOperandUse(1);
4326
4327 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4328 LHS = LeftUse;
4329 RHS = RightUse;
4330 return true;
4331 }
4332
4333 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4334 LHS = RightUse;
4335 RHS = LeftUse;
4336 return true;
4337 }
4338
4339 return false;
4340}
4341
4342const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004343 auto IsReachable =
4344 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4345 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004346 const Loop *L = LI.getLoopFor(PN->getParent());
4347
Sanjoy Das337d4782015-10-31 23:21:40 +00004348 // We don't want to break LCSSA, even in a SCEV expression tree.
4349 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4350 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4351 return nullptr;
4352
Sanjoy Das55015d22015-10-02 23:09:44 +00004353 // Try to match
4354 //
4355 // br %cond, label %left, label %right
4356 // left:
4357 // br label %merge
4358 // right:
4359 // br label %merge
4360 // merge:
4361 // V = phi [ %x, %left ], [ %y, %right ]
4362 //
4363 // as "select %cond, %x, %y"
4364
4365 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4366 assert(IDom && "At least the entry block should dominate PN");
4367
4368 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4369 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4370
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004371 if (BI && BI->isConditional() &&
4372 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4373 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4374 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004375 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4376 }
4377
4378 return nullptr;
4379}
4380
4381const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4382 if (const SCEV *S = createAddRecFromPHI(PN))
4383 return S;
4384
4385 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4386 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004387
Dan Gohmana9c205c2010-02-25 06:57:05 +00004388 // If the PHI has a single incoming value, follow that value, unless the
4389 // PHI's incoming blocks are in a different loop, in which case doing so
4390 // risks breaking LCSSA form. Instcombine would normally zap these, but
4391 // it doesn't have DominatorTree information, so it may miss cases.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00004392 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004393 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004394 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004395
Chris Lattnerd934c702004-04-02 20:23:17 +00004396 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004397 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004398}
4399
Sanjoy Das55015d22015-10-02 23:09:44 +00004400const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4401 Value *Cond,
4402 Value *TrueVal,
4403 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004404 // Handle "constant" branch or select. This can occur for instance when a
4405 // loop pass transforms an inner loop and moves on to process the outer loop.
4406 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4407 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4408
Sanjoy Dasd0671342015-10-02 19:39:59 +00004409 // Try to match some simple smax or umax patterns.
4410 auto *ICI = dyn_cast<ICmpInst>(Cond);
4411 if (!ICI)
4412 return getUnknown(I);
4413
4414 Value *LHS = ICI->getOperand(0);
4415 Value *RHS = ICI->getOperand(1);
4416
4417 switch (ICI->getPredicate()) {
4418 case ICmpInst::ICMP_SLT:
4419 case ICmpInst::ICMP_SLE:
4420 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004421 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004422 case ICmpInst::ICMP_SGT:
4423 case ICmpInst::ICMP_SGE:
4424 // a >s b ? a+x : b+x -> smax(a, b)+x
4425 // a >s b ? b+x : a+x -> smin(a, b)+x
4426 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4427 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4428 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4429 const SCEV *LA = getSCEV(TrueVal);
4430 const SCEV *RA = getSCEV(FalseVal);
4431 const SCEV *LDiff = getMinusSCEV(LA, LS);
4432 const SCEV *RDiff = getMinusSCEV(RA, RS);
4433 if (LDiff == RDiff)
4434 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4435 LDiff = getMinusSCEV(LA, RS);
4436 RDiff = getMinusSCEV(RA, LS);
4437 if (LDiff == RDiff)
4438 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4439 }
4440 break;
4441 case ICmpInst::ICMP_ULT:
4442 case ICmpInst::ICMP_ULE:
4443 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004444 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004445 case ICmpInst::ICMP_UGT:
4446 case ICmpInst::ICMP_UGE:
4447 // a >u b ? a+x : b+x -> umax(a, b)+x
4448 // a >u b ? b+x : a+x -> umin(a, b)+x
4449 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4450 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4451 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4452 const SCEV *LA = getSCEV(TrueVal);
4453 const SCEV *RA = getSCEV(FalseVal);
4454 const SCEV *LDiff = getMinusSCEV(LA, LS);
4455 const SCEV *RDiff = getMinusSCEV(RA, RS);
4456 if (LDiff == RDiff)
4457 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4458 LDiff = getMinusSCEV(LA, RS);
4459 RDiff = getMinusSCEV(RA, LS);
4460 if (LDiff == RDiff)
4461 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4462 }
4463 break;
4464 case ICmpInst::ICMP_NE:
4465 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4466 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4467 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4468 const SCEV *One = getOne(I->getType());
4469 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4470 const SCEV *LA = getSCEV(TrueVal);
4471 const SCEV *RA = getSCEV(FalseVal);
4472 const SCEV *LDiff = getMinusSCEV(LA, LS);
4473 const SCEV *RDiff = getMinusSCEV(RA, One);
4474 if (LDiff == RDiff)
4475 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4476 }
4477 break;
4478 case ICmpInst::ICMP_EQ:
4479 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4480 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4481 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4482 const SCEV *One = getOne(I->getType());
4483 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4484 const SCEV *LA = getSCEV(TrueVal);
4485 const SCEV *RA = getSCEV(FalseVal);
4486 const SCEV *LDiff = getMinusSCEV(LA, One);
4487 const SCEV *RDiff = getMinusSCEV(RA, LS);
4488 if (LDiff == RDiff)
4489 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4490 }
4491 break;
4492 default:
4493 break;
4494 }
4495
4496 return getUnknown(I);
4497}
4498
Sanjoy Dasf8570812016-05-29 00:38:22 +00004499/// Expand GEP instructions into add and multiply operations. This allows them
4500/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004501const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004502 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004503 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004504 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004505
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004506 SmallVector<const SCEV *, 4> IndexExprs;
4507 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4508 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004509 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004510}
4511
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004512uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004513 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004514 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004515
Dan Gohmana30370b2009-05-04 22:02:23 +00004516 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004517 return std::min(GetMinTrailingZeros(T->getOperand()),
4518 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004519
Dan Gohmana30370b2009-05-04 22:02:23 +00004520 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004521 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004522 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4523 ? getTypeSizeInBits(E->getType())
4524 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004525 }
4526
Dan Gohmana30370b2009-05-04 22:02:23 +00004527 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004528 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004529 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4530 ? getTypeSizeInBits(E->getType())
4531 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004532 }
4533
Dan Gohmana30370b2009-05-04 22:02:23 +00004534 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004535 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004536 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004537 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004538 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004539 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004540 }
4541
Dan Gohmana30370b2009-05-04 22:02:23 +00004542 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004543 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004544 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4545 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004546 for (unsigned i = 1, e = M->getNumOperands();
4547 SumOpRes != BitWidth && i != e; ++i)
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004548 SumOpRes =
4549 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
Nick Lewycky3783b462007-11-22 07:59:40 +00004550 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004551 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004552
Dan Gohmana30370b2009-05-04 22:02:23 +00004553 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004554 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004555 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004556 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004557 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004558 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004559 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004560
Dan Gohmana30370b2009-05-04 22:02:23 +00004561 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004562 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004563 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004564 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004565 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004566 return MinOpRes;
4567 }
4568
Dan Gohmana30370b2009-05-04 22:02:23 +00004569 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004570 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004571 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004572 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004573 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004574 return MinOpRes;
4575 }
4576
Dan Gohmanc702fc02009-06-19 23:29:04 +00004577 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4578 // For a SCEVUnknown, ask ValueTracking.
4579 unsigned BitWidth = getTypeSizeInBits(U->getType());
Craig Topperb45eabc2017-04-26 16:39:58 +00004580 KnownBits Known(BitWidth);
4581 computeKnownBits(U->getValue(), Known, getDataLayout(), 0, &AC,
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004582 nullptr, &DT);
Craig Topperb45eabc2017-04-26 16:39:58 +00004583 return Known.Zero.countTrailingOnes();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004584 }
4585
4586 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004587 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004588}
Chris Lattnerd934c702004-04-02 20:23:17 +00004589
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004590uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4591 auto I = MinTrailingZerosCache.find(S);
4592 if (I != MinTrailingZerosCache.end())
4593 return I->second;
4594
4595 uint32_t Result = GetMinTrailingZerosImpl(S);
4596 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4597 assert(InsertPair.second && "Should insert a new key");
4598 return InsertPair.first->second;
4599}
4600
Sanjoy Dasf8570812016-05-29 00:38:22 +00004601/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004602static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004603 if (Instruction *I = dyn_cast<Instruction>(V))
4604 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4605 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004606
4607 return None;
4608}
4609
Sanjoy Dasf8570812016-05-29 00:38:22 +00004610/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004611/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4612/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004613ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004614ScalarEvolution::getRange(const SCEV *S,
4615 ScalarEvolution::RangeSignHint SignHint) {
4616 DenseMap<const SCEV *, ConstantRange> &Cache =
4617 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4618 : SignedRanges;
4619
Dan Gohman761065e2010-11-17 02:44:44 +00004620 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004621 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4622 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004623 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004624
4625 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004626 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004627
Dan Gohman85be4332010-01-26 19:19:05 +00004628 unsigned BitWidth = getTypeSizeInBits(S->getType());
4629 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4630
Sanjoy Das91b54772015-03-09 21:43:43 +00004631 // If the value has known zeros, the maximum value will have those known zeros
4632 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004633 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004634 if (TZ != 0) {
4635 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4636 ConservativeResult =
4637 ConstantRange(APInt::getMinValue(BitWidth),
4638 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4639 else
4640 ConservativeResult = ConstantRange(
4641 APInt::getSignedMinValue(BitWidth),
4642 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4643 }
Dan Gohman85be4332010-01-26 19:19:05 +00004644
Dan Gohmane65c9172009-07-13 21:35:55 +00004645 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004646 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004647 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004648 X = X.add(getRange(Add->getOperand(i), SignHint));
4649 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004650 }
4651
4652 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004653 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004654 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004655 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4656 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004657 }
4658
4659 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004660 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004661 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004662 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4663 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004664 }
4665
4666 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004667 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004668 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004669 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4670 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004671 }
4672
4673 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004674 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4675 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4676 return setRange(UDiv, SignHint,
4677 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004678 }
4679
4680 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004681 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4682 return setRange(ZExt, SignHint,
4683 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004684 }
4685
4686 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004687 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4688 return setRange(SExt, SignHint,
4689 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004690 }
4691
4692 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004693 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4694 return setRange(Trunc, SignHint,
4695 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004696 }
4697
Dan Gohmane65c9172009-07-13 21:35:55 +00004698 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004699 // If there's no unsigned wrap, the value will never be less than its
4700 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004701 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004702 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004703 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004704 ConservativeResult = ConservativeResult.intersectWith(
4705 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004706
Dan Gohman51ad99d2010-01-21 02:09:26 +00004707 // If there's no signed wrap, and all the operands have the same sign or
4708 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004709 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004710 bool AllNonNeg = true;
4711 bool AllNonPos = true;
4712 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4713 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4714 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4715 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004716 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004717 ConservativeResult = ConservativeResult.intersectWith(
4718 ConstantRange(APInt(BitWidth, 0),
4719 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004720 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004721 ConservativeResult = ConservativeResult.intersectWith(
4722 ConstantRange(APInt::getSignedMinValue(BitWidth),
4723 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004724 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004725
4726 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004727 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004728 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004729 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4730 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004731 auto RangeFromAffine = getRangeForAffineAR(
4732 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4733 BitWidth);
4734 if (!RangeFromAffine.isFullSet())
4735 ConservativeResult =
4736 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004737
4738 auto RangeFromFactoring = getRangeViaFactoring(
4739 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4740 BitWidth);
4741 if (!RangeFromFactoring.isFullSet())
4742 ConservativeResult =
4743 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004744 }
Dan Gohmand261d272009-06-24 01:05:09 +00004745 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004746
Sanjoy Das91b54772015-03-09 21:43:43 +00004747 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004748 }
4749
Dan Gohmanc702fc02009-06-19 23:29:04 +00004750 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004751 // Check if the IR explicitly contains !range metadata.
4752 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4753 if (MDRange.hasValue())
4754 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4755
Sanjoy Das91b54772015-03-09 21:43:43 +00004756 // Split here to avoid paying the compile-time cost of calling both
4757 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4758 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004759 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004760 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4761 // For a SCEVUnknown, ask ValueTracking.
Craig Topperb45eabc2017-04-26 16:39:58 +00004762 KnownBits Known(BitWidth);
4763 computeKnownBits(U->getValue(), Known, DL, 0, &AC, nullptr, &DT);
4764 if (Known.One != ~Known.Zero + 1)
Sanjoy Das91b54772015-03-09 21:43:43 +00004765 ConservativeResult =
Craig Topperb45eabc2017-04-26 16:39:58 +00004766 ConservativeResult.intersectWith(ConstantRange(Known.One,
4767 ~Known.Zero + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004768 } else {
4769 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4770 "generalize as needed!");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004771 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004772 if (NS > 1)
4773 ConservativeResult = ConservativeResult.intersectWith(
4774 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4775 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004776 }
4777
4778 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004779 }
4780
Sanjoy Das91b54772015-03-09 21:43:43 +00004781 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004782}
4783
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004784// Given a StartRange, Step and MaxBECount for an expression compute a range of
4785// values that the expression can take. Initially, the expression has a value
4786// from StartRange and then is changed by Step up to MaxBECount times. Signed
4787// argument defines if we treat Step as signed or unsigned.
4788static ConstantRange getRangeForAffineARHelper(APInt Step,
4789 ConstantRange StartRange,
4790 APInt MaxBECount,
4791 unsigned BitWidth, bool Signed) {
4792 // If either Step or MaxBECount is 0, then the expression won't change, and we
4793 // just need to return the initial range.
4794 if (Step == 0 || MaxBECount == 0)
4795 return StartRange;
4796
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00004797 // If we don't know anything about the initial value (i.e. StartRange is
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004798 // FullRange), then we don't know anything about the final range either.
4799 // Return FullRange.
4800 if (StartRange.isFullSet())
4801 return ConstantRange(BitWidth, /* isFullSet = */ true);
4802
4803 // If Step is signed and negative, then we use its absolute value, but we also
4804 // note that we're moving in the opposite direction.
4805 bool Descending = Signed && Step.isNegative();
4806
4807 if (Signed)
4808 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4809 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4810 // This equations hold true due to the well-defined wrap-around behavior of
4811 // APInt.
4812 Step = Step.abs();
4813
4814 // Check if Offset is more than full span of BitWidth. If it is, the
4815 // expression is guaranteed to overflow.
4816 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4817 return ConstantRange(BitWidth, /* isFullSet = */ true);
4818
4819 // Offset is by how much the expression can change. Checks above guarantee no
4820 // overflow here.
4821 APInt Offset = Step * MaxBECount;
4822
4823 // Minimum value of the final range will match the minimal value of StartRange
4824 // if the expression is increasing and will be decreased by Offset otherwise.
4825 // Maximum value of the final range will match the maximal value of StartRange
4826 // if the expression is decreasing and will be increased by Offset otherwise.
4827 APInt StartLower = StartRange.getLower();
4828 APInt StartUpper = StartRange.getUpper() - 1;
4829 APInt MovedBoundary =
4830 Descending ? (StartLower - Offset) : (StartUpper + Offset);
4831
4832 // It's possible that the new minimum/maximum value will fall into the initial
4833 // range (due to wrap around). This means that the expression can take any
4834 // value in this bitwidth, and we have to return full range.
4835 if (StartRange.contains(MovedBoundary))
4836 return ConstantRange(BitWidth, /* isFullSet = */ true);
4837
4838 APInt NewLower, NewUpper;
4839 if (Descending) {
4840 NewLower = MovedBoundary;
4841 NewUpper = StartUpper;
4842 } else {
4843 NewLower = StartLower;
4844 NewUpper = MovedBoundary;
4845 }
4846
4847 // If we end up with full range, return a proper full range.
4848 if (NewLower == NewUpper + 1)
4849 return ConstantRange(BitWidth, /* isFullSet = */ true);
4850
4851 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4852 return ConstantRange(NewLower, NewUpper + 1);
4853}
4854
Sanjoy Dasb765b632016-03-02 00:57:39 +00004855ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4856 const SCEV *Step,
4857 const SCEV *MaxBECount,
4858 unsigned BitWidth) {
4859 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4860 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4861 "Precondition!");
4862
Sanjoy Dasb765b632016-03-02 00:57:39 +00004863 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4864 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004865 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
Sanjoy Dasb765b632016-03-02 00:57:39 +00004866
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004867 // First, consider step signed.
Sanjoy Dasb765b632016-03-02 00:57:39 +00004868 ConstantRange StartSRange = getSignedRange(Start);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004869 ConstantRange StepSRange = getSignedRange(Step);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004870
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004871 // If Step can be both positive and negative, we need to find ranges for the
4872 // maximum absolute step values in both directions and union them.
4873 ConstantRange SR =
4874 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4875 MaxBECountValue, BitWidth, /* Signed = */ true);
4876 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4877 StartSRange, MaxBECountValue,
4878 BitWidth, /* Signed = */ true));
Sanjoy Dasb765b632016-03-02 00:57:39 +00004879
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004880 // Next, consider step unsigned.
4881 ConstantRange UR = getRangeForAffineARHelper(
4882 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4883 MaxBECountValue, BitWidth, /* Signed = */ false);
4884
4885 // Finally, intersect signed and unsigned ranges.
4886 return SR.intersectWith(UR);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004887}
4888
Sanjoy Dasbf730982016-03-02 00:57:54 +00004889ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4890 const SCEV *Step,
4891 const SCEV *MaxBECount,
4892 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004893 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4894 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4895
4896 struct SelectPattern {
4897 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004898 APInt TrueValue;
4899 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004900
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004901 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4902 const SCEV *S) {
4903 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004904 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004905
4906 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4907 "Should be!");
4908
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004909 // Peel off a constant offset:
4910 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4911 // In the future we could consider being smarter here and handle
4912 // {Start+Step,+,Step} too.
4913 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4914 return;
4915
4916 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4917 S = SA->getOperand(1);
4918 }
4919
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004920 // Peel off a cast operation
4921 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4922 CastOp = SCast->getSCEVType();
4923 S = SCast->getOperand();
4924 }
4925
Sanjoy Dasbf730982016-03-02 00:57:54 +00004926 using namespace llvm::PatternMatch;
4927
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004928 auto *SU = dyn_cast<SCEVUnknown>(S);
4929 const APInt *TrueVal, *FalseVal;
4930 if (!SU ||
4931 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4932 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004933 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004934 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004935 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004936
4937 TrueValue = *TrueVal;
4938 FalseValue = *FalseVal;
4939
4940 // Re-apply the cast we peeled off earlier
4941 if (CastOp.hasValue())
4942 switch (*CastOp) {
4943 default:
4944 llvm_unreachable("Unknown SCEV cast type!");
4945
4946 case scTruncate:
4947 TrueValue = TrueValue.trunc(BitWidth);
4948 FalseValue = FalseValue.trunc(BitWidth);
4949 break;
4950 case scZeroExtend:
4951 TrueValue = TrueValue.zext(BitWidth);
4952 FalseValue = FalseValue.zext(BitWidth);
4953 break;
4954 case scSignExtend:
4955 TrueValue = TrueValue.sext(BitWidth);
4956 FalseValue = FalseValue.sext(BitWidth);
4957 break;
4958 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004959
4960 // Re-apply the constant offset we peeled off earlier
4961 TrueValue += Offset;
4962 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004963 }
4964
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004965 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004966 };
4967
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004968 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004969 if (!StartPattern.isRecognized())
4970 return ConstantRange(BitWidth, /* isFullSet = */ true);
4971
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004972 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004973 if (!StepPattern.isRecognized())
4974 return ConstantRange(BitWidth, /* isFullSet = */ true);
4975
4976 if (StartPattern.Condition != StepPattern.Condition) {
4977 // We don't handle this case today; but we could, by considering four
4978 // possibilities below instead of two. I'm not sure if there are cases where
4979 // that will help over what getRange already does, though.
4980 return ConstantRange(BitWidth, /* isFullSet = */ true);
4981 }
4982
4983 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4984 // construct arbitrary general SCEV expressions here. This function is called
4985 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4986 // say) can end up caching a suboptimal value.
4987
Sanjoy Das6b017a12016-03-02 02:56:29 +00004988 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4989 // C2352 and C2512 (otherwise it isn't needed).
4990
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004991 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004992 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004993 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004994 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004995
Sanjoy Das1168f932016-03-02 02:34:20 +00004996 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004997 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004998 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004999 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00005000
5001 return TrueRange.unionWith(FalseRange);
5002}
5003
Jingyue Wu42f1d672015-07-28 18:22:40 +00005004SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005005 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005006 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5007
5008 // Return early if there are no flags to propagate to the SCEV.
5009 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5010 if (BinOp->hasNoUnsignedWrap())
5011 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5012 if (BinOp->hasNoSignedWrap())
5013 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00005014 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00005015 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005016
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005017 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5018}
5019
5020bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5021 // Here we check that I is in the header of the innermost loop containing I,
5022 // since we only deal with instructions in the loop header. The actual loop we
5023 // need to check later will come from an add recurrence, but getting that
5024 // requires computing the SCEV of the operands, which can be expensive. This
5025 // check we can do cheaply to rule out some cases early.
5026 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00005027 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005028 InnermostContainingLoop->getHeader() != I->getParent())
5029 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005030
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005031 // Only proceed if we can prove that I does not yield poison.
Sanjoy Das08989c72017-04-30 19:41:19 +00005032 if (!programUndefinedIfFullPoison(I))
5033 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005034
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005035 // At this point we know that if I is executed, then it does not wrap
5036 // according to at least one of NSW or NUW. If I is not executed, then we do
5037 // not know if the calculation that I represents would wrap. Multiple
5038 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00005039 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5040 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005041 // that guarantee for cases where I is not executed. So we need to find the
5042 // loop that I is considered in relation to and prove that I is executed for
5043 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00005044 // calculates does not wrap anywhere in the loop, so then we can apply the
5045 // flags to the SCEV.
5046 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005047 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5048 // from different loops, so that we know which loop to prove that I is
5049 // executed in.
5050 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00005051 // I could be an extractvalue from a call to an overflow intrinsic.
5052 // TODO: We can do better here in some cases.
5053 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5054 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005055 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00005056 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005057 bool AllOtherOpsLoopInvariant = true;
5058 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5059 ++OtherOpIndex) {
5060 if (OtherOpIndex != OpIndex) {
5061 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5062 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5063 AllOtherOpsLoopInvariant = false;
5064 break;
5065 }
5066 }
5067 }
5068 if (AllOtherOpsLoopInvariant &&
5069 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5070 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005071 }
5072 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005073 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005074}
5075
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005076bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5077 // If we know that \c I can never be poison period, then that's enough.
5078 if (isSCEVExprNeverPoison(I))
5079 return true;
5080
5081 // For an add recurrence specifically, we assume that infinite loops without
5082 // side effects are undefined behavior, and then reason as follows:
5083 //
5084 // If the add recurrence is poison in any iteration, it is poison on all
5085 // future iterations (since incrementing poison yields poison). If the result
5086 // of the add recurrence is fed into the loop latch condition and the loop
5087 // does not contain any throws or exiting blocks other than the latch, we now
5088 // have the ability to "choose" whether the backedge is taken or not (by
5089 // choosing a sufficiently evil value for the poison feeding into the branch)
5090 // for every iteration including and after the one in which \p I first became
5091 // poison. There are two possibilities (let's call the iteration in which \p
5092 // I first became poison as K):
5093 //
5094 // 1. In the set of iterations including and after K, the loop body executes
5095 // no side effects. In this case executing the backege an infinte number
5096 // of times will yield undefined behavior.
5097 //
5098 // 2. In the set of iterations including and after K, the loop body executes
5099 // at least one side effect. In this case, that specific instance of side
5100 // effect is control dependent on poison, which also yields undefined
5101 // behavior.
5102
5103 auto *ExitingBB = L->getExitingBlock();
5104 auto *LatchBB = L->getLoopLatch();
5105 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5106 return false;
5107
5108 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005109 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005110
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005111 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5112 // things that are known to be fully poison under that assumption go on the
5113 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005114 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005115 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005116
5117 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00005118 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005119 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005120
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005121 for (auto *PoisonUser : Poison->users()) {
5122 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5123 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5124 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5125 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005126 assert(BI->isConditional() && "Only possibility!");
5127 if (BI->getParent() == LatchBB) {
5128 LatchControlDependentOnPoison = true;
5129 break;
5130 }
5131 }
5132 }
5133 }
5134
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005135 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5136}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005137
Sanjoy Das5603fc02016-09-26 02:44:07 +00005138ScalarEvolution::LoopProperties
5139ScalarEvolution::getLoopProperties(const Loop *L) {
5140 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005141
Sanjoy Das5603fc02016-09-26 02:44:07 +00005142 auto Itr = LoopPropertiesCache.find(L);
5143 if (Itr == LoopPropertiesCache.end()) {
5144 auto HasSideEffects = [](Instruction *I) {
5145 if (auto *SI = dyn_cast<StoreInst>(I))
5146 return !SI->isSimple();
5147
5148 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005149 };
5150
Sanjoy Das5603fc02016-09-26 02:44:07 +00005151 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5152 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005153
Sanjoy Das5603fc02016-09-26 02:44:07 +00005154 for (auto *BB : L->getBlocks())
5155 for (auto &I : *BB) {
5156 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5157 LP.HasNoAbnormalExits = false;
5158 if (HasSideEffects(&I))
5159 LP.HasNoSideEffects = false;
5160 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5161 break; // We're already as pessimistic as we can get.
5162 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005163
Sanjoy Das5603fc02016-09-26 02:44:07 +00005164 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005165 assert(InsertPair.second && "We just checked!");
5166 Itr = InsertPair.first;
5167 }
5168
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005169 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005170}
5171
Dan Gohmanaf752342009-07-07 17:06:11 +00005172const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005173 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005174 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005175
Dan Gohman69451a02010-03-09 23:46:50 +00005176 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005177 // Don't attempt to analyze instructions in blocks that aren't
5178 // reachable. Such instructions don't matter, and they aren't required
5179 // to obey basic rules for definitions dominating uses which this
5180 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005181 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005182 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005183 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005184 return getConstant(CI);
5185 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005186 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005187 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005188 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005189 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005190 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005191
Dan Gohman80ca01c2009-07-17 20:47:02 +00005192 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005193 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005194 switch (BO->Opcode) {
5195 case Instruction::Add: {
5196 // The simple thing to do would be to just call getSCEV on both operands
5197 // and call getAddExpr with the result. However if we're looking at a
5198 // bunch of things all added together, this can be quite inefficient,
5199 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5200 // Instead, gather up all the operands and make a single getAddExpr call.
5201 // LLVM IR canonical form means we need only traverse the left operands.
5202 SmallVector<const SCEV *, 4> AddOps;
5203 do {
5204 if (BO->Op) {
5205 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5206 AddOps.push_back(OpSCEV);
5207 break;
5208 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005209
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005210 // If a NUW or NSW flag can be applied to the SCEV for this
5211 // addition, then compute the SCEV for this addition by itself
5212 // with a separate call to getAddExpr. We need to do that
5213 // instead of pushing the operands of the addition onto AddOps,
5214 // since the flags are only known to apply to this particular
5215 // addition - they may not apply to other additions that can be
5216 // formed with operands from AddOps.
5217 const SCEV *RHS = getSCEV(BO->RHS);
5218 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5219 if (Flags != SCEV::FlagAnyWrap) {
5220 const SCEV *LHS = getSCEV(BO->LHS);
5221 if (BO->Opcode == Instruction::Sub)
5222 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5223 else
5224 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5225 break;
5226 }
Dan Gohman36bad002009-09-17 18:05:20 +00005227 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005228
5229 if (BO->Opcode == Instruction::Sub)
5230 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5231 else
5232 AddOps.push_back(getSCEV(BO->RHS));
5233
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005234 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005235 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5236 NewBO->Opcode != Instruction::Sub)) {
5237 AddOps.push_back(getSCEV(BO->LHS));
5238 break;
5239 }
5240 BO = NewBO;
5241 } while (true);
5242
5243 return getAddExpr(AddOps);
5244 }
5245
5246 case Instruction::Mul: {
5247 SmallVector<const SCEV *, 4> MulOps;
5248 do {
5249 if (BO->Op) {
5250 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5251 MulOps.push_back(OpSCEV);
5252 break;
5253 }
5254
5255 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5256 if (Flags != SCEV::FlagAnyWrap) {
5257 MulOps.push_back(
5258 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5259 break;
5260 }
5261 }
5262
5263 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005264 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005265 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5266 MulOps.push_back(getSCEV(BO->LHS));
5267 break;
5268 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005269 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005270 } while (true);
5271
5272 return getMulExpr(MulOps);
5273 }
5274 case Instruction::UDiv:
5275 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5276 case Instruction::Sub: {
5277 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5278 if (BO->Op)
5279 Flags = getNoWrapFlagsFromUB(BO->Op);
5280 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5281 }
5282 case Instruction::And:
5283 // For an expression like x&255 that merely masks off the high bits,
5284 // use zext(trunc(x)) as the SCEV expression.
5285 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5286 if (CI->isNullValue())
5287 return getSCEV(BO->RHS);
5288 if (CI->isAllOnesValue())
5289 return getSCEV(BO->LHS);
5290 const APInt &A = CI->getValue();
5291
5292 // Instcombine's ShrinkDemandedConstant may strip bits out of
5293 // constants, obscuring what would otherwise be a low-bits mask.
5294 // Use computeKnownBits to compute what ShrinkDemandedConstant
5295 // knew about to reconstruct a low-bits mask value.
5296 unsigned LZ = A.countLeadingZeros();
5297 unsigned TZ = A.countTrailingZeros();
5298 unsigned BitWidth = A.getBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +00005299 KnownBits Known(BitWidth);
5300 computeKnownBits(BO->LHS, Known, getDataLayout(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005301 0, &AC, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005302
5303 APInt EffectiveMask =
5304 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
Craig Topperb45eabc2017-04-26 16:39:58 +00005305 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005306 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5307 const SCEV *LHS = getSCEV(BO->LHS);
5308 const SCEV *ShiftedLHS = nullptr;
5309 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5310 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5311 // For an expression like (x * 8) & 8, simplify the multiply.
5312 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5313 unsigned GCD = std::min(MulZeros, TZ);
5314 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5315 SmallVector<const SCEV*, 4> MulOps;
5316 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5317 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5318 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5319 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5320 }
5321 }
5322 if (!ShiftedLHS)
5323 ShiftedLHS = getUDivExpr(LHS, MulCount);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005324 return getMulExpr(
5325 getZeroExtendExpr(
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005326 getTruncateExpr(ShiftedLHS,
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005327 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5328 BO->LHS->getType()),
5329 MulCount);
5330 }
Dan Gohman36bad002009-09-17 18:05:20 +00005331 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005332 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005333
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005334 case Instruction::Or:
Eli Friedmand0e6ae562017-04-20 23:59:05 +00005335 // If the RHS of the Or is a constant, we may have something like:
5336 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5337 // optimizations will transparently handle this case.
5338 //
5339 // In order for this transformation to be safe, the LHS must be of the
5340 // form X*(2^n) and the Or constant must be less than 2^n.
5341 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5342 const SCEV *LHS = getSCEV(BO->LHS);
5343 const APInt &CIVal = CI->getValue();
5344 if (GetMinTrailingZeros(LHS) >=
5345 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5346 // Build a plain add SCEV.
5347 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5348 // If the LHS of the add was an addrec and it has no-wrap flags,
5349 // transfer the no-wrap flags, since an or won't introduce a wrap.
5350 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5351 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5352 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5353 OldAR->getNoWrapFlags());
5354 }
5355 return S;
5356 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005357 }
5358 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005359
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005360 case Instruction::Xor:
5361 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5362 // If the RHS of xor is -1, then this is a not operation.
5363 if (CI->isAllOnesValue())
5364 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005365
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005366 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5367 // This is a variant of the check for xor with -1, and it handles
5368 // the case where instcombine has trimmed non-demanded bits out
5369 // of an xor with -1.
5370 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5371 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5372 if (LBO->getOpcode() == Instruction::And &&
5373 LCI->getValue() == CI->getValue())
5374 if (const SCEVZeroExtendExpr *Z =
5375 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5376 Type *UTy = BO->LHS->getType();
5377 const SCEV *Z0 = Z->getOperand();
5378 Type *Z0Ty = Z0->getType();
5379 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005380
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005381 // If C is a low-bits mask, the zero extend is serving to
5382 // mask off the high bits. Complement the operand and
5383 // re-apply the zext.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005384 if (CI->getValue().isMask(Z0TySize))
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005385 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5386
5387 // If C is a single bit, it may be in the sign-bit position
5388 // before the zero-extend. In this case, represent the xor
5389 // using an add, which is equivalent, and re-apply the zext.
5390 APInt Trunc = CI->getValue().trunc(Z0TySize);
5391 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Craig Topperbcfd2d12017-04-20 16:56:25 +00005392 Trunc.isSignMask())
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005393 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5394 UTy);
5395 }
5396 }
5397 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005398
5399 case Instruction::Shl:
5400 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005401 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5402 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005403
5404 // If the shift count is not less than the bitwidth, the result of
5405 // the shift is undefined. Don't try to analyze it, because the
5406 // resolution chosen here may differ from the resolution chosen in
5407 // other parts of the compiler.
5408 if (SA->getValue().uge(BitWidth))
5409 break;
5410
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005411 // It is currently not resolved how to interpret NSW for left
5412 // shift by BitWidth - 1, so we avoid applying flags in that
5413 // case. Remove this check (or this comment) once the situation
5414 // is resolved. See
5415 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5416 // and http://reviews.llvm.org/D8890 .
5417 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005418 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5419 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005420
Owen Andersonedb4a702009-07-24 23:12:02 +00005421 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005422 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005423 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005424 }
5425 break;
5426
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005427 case Instruction::AShr:
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005428 // AShr X, C, where C is a constant.
5429 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5430 if (!CI)
5431 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005432
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005433 Type *OuterTy = BO->LHS->getType();
5434 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5435 // If the shift count is not less than the bitwidth, the result of
5436 // the shift is undefined. Don't try to analyze it, because the
5437 // resolution chosen here may differ from the resolution chosen in
5438 // other parts of the compiler.
5439 if (CI->getValue().uge(BitWidth))
5440 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005441
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005442 if (CI->isNullValue())
5443 return getSCEV(BO->LHS); // shift by zero --> noop
5444
5445 uint64_t AShrAmt = CI->getZExtValue();
5446 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5447
5448 Operator *L = dyn_cast<Operator>(BO->LHS);
5449 if (L && L->getOpcode() == Instruction::Shl) {
5450 // X = Shl A, n
5451 // Y = AShr X, m
5452 // Both n and m are constant.
5453
5454 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5455 if (L->getOperand(1) == BO->RHS)
5456 // For a two-shift sext-inreg, i.e. n = m,
5457 // use sext(trunc(x)) as the SCEV expression.
5458 return getSignExtendExpr(
5459 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5460
5461 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5462 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5463 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5464 if (ShlAmt > AShrAmt) {
5465 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5466 // expression. We already checked that ShlAmt < BitWidth, so
5467 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5468 // ShlAmt - AShrAmt < Amt.
5469 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5470 ShlAmt - AShrAmt);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005471 return getSignExtendExpr(
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005472 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5473 getConstant(Mul)), OuterTy);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005474 }
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005475 }
5476 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005477 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005478 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005479 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005480
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005481 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005482 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005483 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005484
5485 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005486 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005487
5488 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005489 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005490
5491 case Instruction::BitCast:
5492 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005493 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005494 return getSCEV(U->getOperand(0));
5495 break;
5496
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005497 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5498 // lead to pointer expressions which cannot safely be expanded to GEPs,
5499 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5500 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005501
Dan Gohmanee750d12009-05-08 20:26:55 +00005502 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005503 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005504
Dan Gohman05e89732008-06-22 19:56:46 +00005505 case Instruction::PHI:
5506 return createNodeForPHI(cast<PHINode>(U));
5507
5508 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005509 // U can also be a select constant expr, which let fall through. Since
5510 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5511 // constant expressions cannot have instructions as operands, we'd have
5512 // returned getUnknown for a select constant expressions anyway.
5513 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005514 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5515 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005516 break;
5517
5518 case Instruction::Call:
5519 case Instruction::Invoke:
5520 if (Value *RV = CallSite(U).getReturnedArgOperand())
5521 return getSCEV(RV);
5522 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005523 }
5524
Dan Gohmanc8e23622009-04-21 23:15:49 +00005525 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005526}
5527
5528
5529
5530//===----------------------------------------------------------------------===//
5531// Iteration Count Computation Code
5532//
5533
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005534static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5535 if (!ExitCount)
5536 return 0;
5537
5538 ConstantInt *ExitConst = ExitCount->getValue();
5539
5540 // Guard against huge trip counts.
5541 if (ExitConst->getValue().getActiveBits() > 32)
5542 return 0;
5543
5544 // In case of integer overflow, this returns 0, which is correct.
5545 return ((unsigned)ExitConst->getZExtValue()) + 1;
5546}
5547
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005548unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005549 if (BasicBlock *ExitingBB = L->getExitingBlock())
5550 return getSmallConstantTripCount(L, ExitingBB);
5551
5552 // No trip count information for multiple exits.
5553 return 0;
5554}
5555
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005556unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005557 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005558 assert(ExitingBlock && "Must pass a non-null exiting block!");
5559 assert(L->isLoopExiting(ExitingBlock) &&
5560 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005561 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005562 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005563 return getConstantTripCount(ExitCount);
5564}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005565
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005566unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005567 const auto *MaxExitCount =
5568 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5569 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005570}
5571
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005572unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005573 if (BasicBlock *ExitingBB = L->getExitingBlock())
5574 return getSmallConstantTripMultiple(L, ExitingBB);
5575
5576 // No trip multiple information for multiple exits.
5577 return 0;
5578}
5579
Sanjoy Dasf8570812016-05-29 00:38:22 +00005580/// Returns the largest constant divisor of the trip count of this loop as a
5581/// normal unsigned value, if possible. This means that the actual trip count is
5582/// always a multiple of the returned value (don't forget the trip count could
5583/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005584///
5585/// Returns 1 if the trip count is unknown or not guaranteed to be the
5586/// multiple of a constant (which is also the case if the trip count is simply
5587/// constant, use getSmallConstantTripCount for that case), Will also return 1
5588/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005589///
5590/// As explained in the comments for getSmallConstantTripCount, this assumes
5591/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005592unsigned
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005593ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005594 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005595 assert(ExitingBlock && "Must pass a non-null exiting block!");
5596 assert(L->isLoopExiting(ExitingBlock) &&
5597 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005598 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005599 if (ExitCount == getCouldNotCompute())
5600 return 1;
5601
5602 // Get the trip count from the BE count by adding 1.
Eli Friedmanb1578d32017-03-20 20:25:46 +00005603 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005604
Eli Friedmanb1578d32017-03-20 20:25:46 +00005605 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5606 if (!TC)
5607 // Attempt to factor more general cases. Returns the greatest power of
5608 // two divisor. If overflow happens, the trip count expression is still
5609 // divisible by the greatest power of 2 divisor returned.
5610 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005611
Eli Friedmanb1578d32017-03-20 20:25:46 +00005612 ConstantInt *Result = TC->getValue();
Andrew Trick2b6860f2011-08-11 23:36:16 +00005613
Hal Finkel30bd9342012-10-24 19:46:44 +00005614 // Guard against huge trip counts (this requires checking
5615 // for zero to handle the case where the trip count == -1 and the
5616 // addition wraps).
5617 if (!Result || Result->getValue().getActiveBits() > 32 ||
5618 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005619 return 1;
5620
5621 return (unsigned)Result->getZExtValue();
5622}
5623
Sanjoy Dasf8570812016-05-29 00:38:22 +00005624/// Get the expression for the number of loop iterations for which this loop is
5625/// guaranteed not to exit via ExitingBlock. Otherwise return
5626/// SCEVCouldNotCompute.
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005627const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5628 BasicBlock *ExitingBlock) {
Andrew Trick77c55422011-08-02 04:23:35 +00005629 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005630}
5631
Silviu Baranga6f444df2016-04-08 14:29:09 +00005632const SCEV *
5633ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5634 SCEVUnionPredicate &Preds) {
5635 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5636}
5637
Dan Gohmanaf752342009-07-07 17:06:11 +00005638const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005639 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005640}
5641
Sanjoy Dasf8570812016-05-29 00:38:22 +00005642/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5643/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005644const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005645 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005646}
5647
John Brawn84b21832016-10-21 11:08:48 +00005648bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5649 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5650}
5651
Sanjoy Dasf8570812016-05-29 00:38:22 +00005652/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005653static void
5654PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5655 BasicBlock *Header = L->getHeader();
5656
5657 // Push all Loop-header PHIs onto the Worklist stack.
5658 for (BasicBlock::iterator I = Header->begin();
5659 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5660 Worklist.push_back(PN);
5661}
5662
Dan Gohman2b8da352009-04-30 20:47:05 +00005663const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005664ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5665 auto &BTI = getBackedgeTakenInfo(L);
5666 if (BTI.hasFullInfo())
5667 return BTI;
5668
5669 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5670
5671 if (!Pair.second)
5672 return Pair.first->second;
5673
5674 BackedgeTakenInfo Result =
5675 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5676
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005677 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005678}
5679
5680const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005681ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005682 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005683 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005684 // update the value. The temporary CouldNotCompute value tells SCEV
5685 // code elsewhere that it shouldn't attempt to request a new
5686 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005687 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005688 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005689 if (!Pair.second)
5690 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005691
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005692 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005693 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5694 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005695 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005696
5697 if (Result.getExact(this) != getCouldNotCompute()) {
5698 assert(isLoopInvariant(Result.getExact(this), L) &&
5699 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005700 "Computed backedge-taken count isn't loop invariant for loop!");
5701 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005702 }
5703 else if (Result.getMax(this) == getCouldNotCompute() &&
5704 isa<PHINode>(L->getHeader()->begin())) {
5705 // Only count loops that have phi nodes as not being computable.
5706 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005707 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005708
Chris Lattnera337f5e2011-01-09 02:16:18 +00005709 // Now that we know more about the trip count for this loop, forget any
5710 // existing SCEV values for PHI nodes in this loop since they are only
5711 // conservative estimates made without the benefit of trip count
5712 // information. This is similar to the code in forgetLoop, except that
5713 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005714 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005715 SmallVector<Instruction *, 16> Worklist;
5716 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005717
Chris Lattnera337f5e2011-01-09 02:16:18 +00005718 SmallPtrSet<Instruction *, 8> Visited;
5719 while (!Worklist.empty()) {
5720 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005721 if (!Visited.insert(I).second)
5722 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005723
Chris Lattnera337f5e2011-01-09 02:16:18 +00005724 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005725 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005726 if (It != ValueExprMap.end()) {
5727 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005728
Chris Lattnera337f5e2011-01-09 02:16:18 +00005729 // SCEVUnknown for a PHI either means that it has an unrecognized
5730 // structure, or it's a PHI that's in the progress of being computed
5731 // by createNodeForPHI. In the former case, additional loop trip
5732 // count information isn't going to change anything. In the later
5733 // case, createNodeForPHI will perform the necessary updates on its
5734 // own when it gets to that point.
5735 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005736 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005737 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005738 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005739 if (PHINode *PN = dyn_cast<PHINode>(I))
5740 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005741 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005742
5743 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005744 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005745 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005746
5747 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005748 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005749 // recusive call to getBackedgeTakenInfo (on a different
5750 // loop), which would invalidate the iterator computed
5751 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005752 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005753}
5754
Dan Gohman880c92a2009-10-31 15:04:55 +00005755void ScalarEvolution::forgetLoop(const Loop *L) {
5756 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005757 auto RemoveLoopFromBackedgeMap =
5758 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5759 auto BTCPos = Map.find(L);
5760 if (BTCPos != Map.end()) {
5761 BTCPos->second.clear();
5762 Map.erase(BTCPos);
5763 }
5764 };
5765
5766 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5767 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005768
Dan Gohman880c92a2009-10-31 15:04:55 +00005769 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005770 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005771 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005772
Dan Gohmandc191042009-07-08 19:23:34 +00005773 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005774 while (!Worklist.empty()) {
5775 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005776 if (!Visited.insert(I).second)
5777 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005778
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005779 ValueExprMapType::iterator It =
5780 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005781 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005782 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005783 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005784 if (PHINode *PN = dyn_cast<PHINode>(I))
5785 ConstantEvolutionLoopExitValue.erase(PN);
5786 }
5787
5788 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005789 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005790
5791 // Forget all contained loops too, to avoid dangling entries in the
5792 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005793 for (Loop *I : *L)
5794 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005795
Sanjoy Das5603fc02016-09-26 02:44:07 +00005796 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005797}
5798
Eric Christopheref6d5932010-07-29 01:25:38 +00005799void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005800 Instruction *I = dyn_cast<Instruction>(V);
5801 if (!I) return;
5802
5803 // Drop information about expressions based on loop-header PHIs.
5804 SmallVector<Instruction *, 16> Worklist;
5805 Worklist.push_back(I);
5806
5807 SmallPtrSet<Instruction *, 8> Visited;
5808 while (!Worklist.empty()) {
5809 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005810 if (!Visited.insert(I).second)
5811 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005812
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005813 ValueExprMapType::iterator It =
5814 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005815 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005816 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005817 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005818 if (PHINode *PN = dyn_cast<PHINode>(I))
5819 ConstantEvolutionLoopExitValue.erase(PN);
5820 }
5821
5822 PushDefUseChildren(I, Worklist);
5823 }
5824}
5825
Sanjoy Dasf8570812016-05-29 00:38:22 +00005826/// Get the exact loop backedge taken count considering all loop exits. A
5827/// computable result can only be returned for loops with a single exit.
5828/// Returning the minimum taken count among all exits is incorrect because one
5829/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5830/// the limit of each loop test is never skipped. This is a valid assumption as
5831/// long as the loop exits via that test. For precise results, it is the
5832/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005833/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005834const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005835ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5836 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005837 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005838 if (!isComplete() || ExitNotTaken.empty())
5839 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005840
Craig Topper9f008862014-04-15 04:59:12 +00005841 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005842 for (auto &ENT : ExitNotTaken) {
5843 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005844
5845 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005846 BECount = ENT.ExactNotTaken;
5847 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005848 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005849 if (Preds && !ENT.hasAlwaysTruePredicate())
5850 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005851
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005852 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005853 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005854 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005855
Andrew Trickbbb226a2011-09-02 21:20:46 +00005856 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005857 return BECount;
5858}
5859
Sanjoy Dasf8570812016-05-29 00:38:22 +00005860/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005861const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005862ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005863 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005864 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005865 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005866 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005867
Andrew Trick3ca3f982011-07-26 17:19:55 +00005868 return SE->getCouldNotCompute();
5869}
5870
5871/// getMax - Get the max backedge taken count for the loop.
5872const SCEV *
5873ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005874 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5875 return !ENT.hasAlwaysTruePredicate();
5876 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005877
Sanjoy Das73268612016-09-26 01:10:22 +00005878 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5879 return SE->getCouldNotCompute();
5880
5881 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005882}
5883
John Brawn84b21832016-10-21 11:08:48 +00005884bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5885 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5886 return !ENT.hasAlwaysTruePredicate();
5887 };
5888 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5889}
5890
Andrew Trick9093e152013-03-26 03:14:53 +00005891bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5892 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005893 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5894 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005895 return true;
5896
Silviu Baranga6f444df2016-04-08 14:29:09 +00005897 for (auto &ENT : ExitNotTaken)
5898 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5899 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005900 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005901
Andrew Trick9093e152013-03-26 03:14:53 +00005902 return false;
5903}
5904
Andrew Trick3ca3f982011-07-26 17:19:55 +00005905/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5906/// computable exit into a persistent ExitNotTakenInfo array.
5907ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005908 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5909 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00005910 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5911 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005912 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005913 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005914 std::transform(
5915 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005916 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005917 BasicBlock *ExitBB = EEI.first;
5918 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00005919 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005920 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00005921
5922 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5923 for (auto *Pred : EL.Predicates)
5924 Predicate->add(Pred);
5925
5926 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005927 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005928}
5929
Sanjoy Dasf8570812016-05-29 00:38:22 +00005930/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005931void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005932 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005933}
5934
Sanjoy Dasf8570812016-05-29 00:38:22 +00005935/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005936ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005937ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5938 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005939 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005940 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005941
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005942 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5943
5944 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005945 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005946 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005947 const SCEV *MustExitMaxBECount = nullptr;
5948 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00005949 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00005950
5951 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5952 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005953 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005954 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005955 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005956 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5957
Sanjoy Dasf0022122016-09-28 17:14:58 +00005958 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005959 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005960
5961 // 1. For each exit that can be computed, add an entry to ExitCounts.
5962 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005963 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005964 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005965 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005966 CouldComputeBECount = false;
5967 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005968 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005969
Andrew Trick839e30b2014-05-23 19:47:13 +00005970 // 2. Derive the loop's MaxBECount from each exit's max number of
5971 // non-exiting iterations. Partition the loop exits into two kinds:
5972 // LoopMustExits and LoopMayExits.
5973 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005974 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5975 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005976 // MaxBECount is the minimum EL.MaxNotTaken of computable
5977 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5978 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5979 // computable EL.MaxNotTaken.
5980 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005981 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00005982 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005983 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00005984 MustExitMaxOrZero = EL.MaxOrZero;
5985 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00005986 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005987 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005988 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005989 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005990 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5991 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005992 else {
5993 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005994 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005995 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005996 }
Dan Gohman96212b62009-06-22 00:31:57 +00005997 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005998 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5999 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00006000 // The loop backedge will be taken the maximum or zero times if there's
6001 // a single exit that must be taken the maximum or zero times.
6002 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00006003 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00006004 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00006005}
6006
Andrew Trick3ca3f982011-07-26 17:19:55 +00006007ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00006008ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6009 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00006010
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006011 // Okay, we've chosen an exiting block. See what condition causes us to exit
6012 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00006013 // lead to the loop header.
6014 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00006015 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00006016 for (auto *SBB : successors(ExitingBlock))
6017 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006018 if (Exit) // Multiple exit successors.
6019 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00006020 Exit = SBB;
6021 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006022 MustExecuteLoopHeader = false;
6023 }
Dan Gohmance973df2009-06-24 04:48:43 +00006024
Chris Lattner18954852007-01-07 02:24:26 +00006025 // At this point, we know we have a conditional branch that determines whether
6026 // the loop is exited. However, we don't know if the branch is executed each
6027 // time through the loop. If not, then the execution count of the branch will
6028 // not be equal to the trip count of the loop.
6029 //
6030 // Currently we check for this by checking to see if the Exit branch goes to
6031 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00006032 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00006033 // loop header. This is common for un-rotated loops.
6034 //
6035 // If both of those tests fail, walk up the unique predecessor chain to the
6036 // header, stopping if there is an edge that doesn't exit the loop. If the
6037 // header is reached, the execution count of the branch will be equal to the
6038 // trip count of the loop.
6039 //
6040 // More extensive analysis could be done to handle more cases here.
6041 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00006042 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00006043 // The simple checks failed, try climbing the unique predecessor chain
6044 // up to the header.
6045 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00006046 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00006047 BasicBlock *Pred = BB->getUniquePredecessor();
6048 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006049 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006050 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00006051 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00006052 if (PredSucc == BB)
6053 continue;
6054 // If the predecessor has a successor that isn't BB and isn't
6055 // outside the loop, assume the worst.
6056 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006057 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006058 }
6059 if (Pred == L->getHeader()) {
6060 Ok = true;
6061 break;
6062 }
6063 BB = Pred;
6064 }
6065 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006066 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006067 }
6068
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006069 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006070 TerminatorInst *Term = ExitingBlock->getTerminator();
6071 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6072 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6073 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006074 return computeExitLimitFromCond(
6075 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6076 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006077 }
6078
6079 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006080 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006081 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006082
6083 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006084}
6085
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006086ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6087 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6088 bool ControlsExit, bool AllowPredicates) {
6089 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6090 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6091 ControlsExit, AllowPredicates);
6092}
6093
6094Optional<ScalarEvolution::ExitLimit>
6095ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6096 BasicBlock *TBB, BasicBlock *FBB,
6097 bool ControlsExit, bool AllowPredicates) {
Sanjoy Das25972aa2017-04-24 00:46:40 +00006098 (void)this->L;
6099 (void)this->TBB;
6100 (void)this->FBB;
6101 (void)this->AllowPredicates;
6102
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006103 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6104 this->AllowPredicates == AllowPredicates &&
6105 "Variance in assumed invariant key components!");
6106 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6107 if (Itr == TripCountMap.end())
6108 return None;
6109 return Itr->second;
6110}
6111
6112void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6113 BasicBlock *TBB, BasicBlock *FBB,
6114 bool ControlsExit,
6115 bool AllowPredicates,
6116 const ExitLimit &EL) {
6117 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6118 this->AllowPredicates == AllowPredicates &&
6119 "Variance in assumed invariant key components!");
6120
6121 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6122 assert(InsertResult.second && "Expected successful insertion!");
Sanjoy Das25972aa2017-04-24 00:46:40 +00006123 (void)InsertResult;
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006124}
6125
6126ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6127 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6128 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6129
6130 if (auto MaybeEL =
6131 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6132 return *MaybeEL;
6133
6134 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6135 ControlsExit, AllowPredicates);
6136 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6137 return EL;
6138}
6139
6140ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6141 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6142 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006143 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00006144 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6145 if (BO->getOpcode() == Instruction::And) {
6146 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00006147 bool EitherMayExit = L->contains(TBB);
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006148 ExitLimit EL0 = computeExitLimitFromCondCached(
6149 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6150 AllowPredicates);
6151 ExitLimit EL1 = computeExitLimitFromCondCached(
6152 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6153 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006154 const SCEV *BECount = getCouldNotCompute();
6155 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006156 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006157 // Both conditions must be true for the loop to continue executing.
6158 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006159 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6160 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006161 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006162 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006163 BECount =
6164 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6165 if (EL0.MaxNotTaken == getCouldNotCompute())
6166 MaxBECount = EL1.MaxNotTaken;
6167 else if (EL1.MaxNotTaken == getCouldNotCompute())
6168 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006169 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006170 MaxBECount =
6171 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006172 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006173 // Both conditions must be true at the same time for the loop to exit.
6174 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006175 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006176 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6177 MaxBECount = EL0.MaxNotTaken;
6178 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6179 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006180 }
6181
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006182 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6183 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006184 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6185 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6186 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006187 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6188 !isa<SCEVCouldNotCompute>(BECount))
6189 MaxBECount = BECount;
6190
John Brawn84b21832016-10-21 11:08:48 +00006191 return ExitLimit(BECount, MaxBECount, false,
6192 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006193 }
6194 if (BO->getOpcode() == Instruction::Or) {
6195 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00006196 bool EitherMayExit = L->contains(FBB);
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006197 ExitLimit EL0 = computeExitLimitFromCondCached(
6198 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6199 AllowPredicates);
6200 ExitLimit EL1 = computeExitLimitFromCondCached(
6201 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6202 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006203 const SCEV *BECount = getCouldNotCompute();
6204 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006205 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006206 // Both conditions must be false for the loop to continue executing.
6207 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006208 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6209 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006210 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006211 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006212 BECount =
6213 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6214 if (EL0.MaxNotTaken == getCouldNotCompute())
6215 MaxBECount = EL1.MaxNotTaken;
6216 else if (EL1.MaxNotTaken == getCouldNotCompute())
6217 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006218 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006219 MaxBECount =
6220 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006221 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006222 // Both conditions must be false at the same time for the loop to exit.
6223 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006224 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006225 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6226 MaxBECount = EL0.MaxNotTaken;
6227 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6228 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006229 }
6230
John Brawn84b21832016-10-21 11:08:48 +00006231 return ExitLimit(BECount, MaxBECount, false,
6232 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006233 }
6234 }
6235
6236 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00006237 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006238 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6239 ExitLimit EL =
6240 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6241 if (EL.hasFullInfo() || !AllowPredicates)
6242 return EL;
6243
6244 // Try again, but use SCEV predicates this time.
6245 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6246 /*AllowPredicates=*/true);
6247 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006248
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006249 // Check for a constant condition. These are normally stripped out by
6250 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6251 // preserve the CFG and is temporarily leaving constant conditions
6252 // in place.
6253 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6254 if (L->contains(FBB) == !CI->getZExtValue())
6255 // The backedge is always taken.
6256 return getCouldNotCompute();
6257 else
6258 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006259 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006260 }
6261
Eli Friedmanebf98b02009-05-09 12:32:42 +00006262 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006263 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006264}
6265
Andrew Trick3ca3f982011-07-26 17:19:55 +00006266ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006267ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006268 ICmpInst *ExitCond,
6269 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006270 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006271 bool ControlsExit,
6272 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006273
Reid Spencer266e42b2006-12-23 06:05:41 +00006274 // If the condition was exit on true, convert the condition to exit on false
6275 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006276 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006277 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006278 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006279 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006280
6281 // Handle common loops like: for (X = "string"; *X; ++X)
6282 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6283 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006284 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006285 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006286 if (ItCnt.hasAnyInfo())
6287 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006288 }
6289
Dan Gohmanaf752342009-07-07 17:06:11 +00006290 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6291 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006292
6293 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006294 LHS = getSCEVAtScope(LHS, L);
6295 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006296
Dan Gohmance973df2009-06-24 04:48:43 +00006297 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006298 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006299 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006300 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006301 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006302 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006303 }
6304
Dan Gohman81585c12010-05-03 16:35:17 +00006305 // Simplify the operands before analyzing them.
6306 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6307
Chris Lattnerd934c702004-04-02 20:23:17 +00006308 // If we have a comparison of a chrec against a constant, try to use value
6309 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006310 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6311 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006312 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006313 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006314 ConstantRange CompRange =
6315 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006316
Dan Gohmanaf752342009-07-07 17:06:11 +00006317 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006318 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006319 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006320
Chris Lattnerd934c702004-04-02 20:23:17 +00006321 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006322 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006323 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006324 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006325 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006326 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006327 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006328 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006329 case ICmpInst::ICMP_EQ: { // while (X == Y)
6330 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006331 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006332 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006333 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006334 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006335 case ICmpInst::ICMP_SLT:
6336 case ICmpInst::ICMP_ULT: { // while (X < Y)
6337 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006338 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006339 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006340 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006341 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006342 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006343 case ICmpInst::ICMP_SGT:
6344 case ICmpInst::ICMP_UGT: { // while (X > Y)
6345 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006346 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006347 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006348 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006349 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006350 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006351 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006352 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006353 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006354 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006355
6356 auto *ExhaustiveCount =
6357 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6358
6359 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6360 return ExhaustiveCount;
6361
6362 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6363 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006364}
6365
Benjamin Kramer5a188542014-02-11 15:44:32 +00006366ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006367ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006368 SwitchInst *Switch,
6369 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006370 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006371 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6372
6373 // Give up if the exit is the default dest of a switch.
6374 if (Switch->getDefaultDest() == ExitingBlock)
6375 return getCouldNotCompute();
6376
6377 assert(L->contains(Switch->getDefaultDest()) &&
6378 "Default case must not exit the loop!");
6379 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6380 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6381
6382 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006383 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006384 if (EL.hasAnyInfo())
6385 return EL;
6386
6387 return getCouldNotCompute();
6388}
6389
Chris Lattnerec901cc2004-10-12 01:49:27 +00006390static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006391EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6392 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006393 const SCEV *InVal = SE.getConstant(C);
6394 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006395 assert(isa<SCEVConstant>(Val) &&
6396 "Evaluation of SCEV at constant didn't fold correctly?");
6397 return cast<SCEVConstant>(Val)->getValue();
6398}
6399
Sanjoy Dasf8570812016-05-29 00:38:22 +00006400/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6401/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006402ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006403ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006404 LoadInst *LI,
6405 Constant *RHS,
6406 const Loop *L,
6407 ICmpInst::Predicate predicate) {
6408
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006409 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006410
6411 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006412 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006413 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006414 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006415
6416 // Make sure that it is really a constant global we are gepping, with an
6417 // initializer, and make sure the first IDX is really 0.
6418 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006419 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006420 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6421 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006422 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006423
6424 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006425 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006426 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006427 unsigned VarIdxNum = 0;
6428 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6429 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6430 Indexes.push_back(CI);
6431 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006432 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006433 VarIdx = GEP->getOperand(i);
6434 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006435 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006436 }
6437
Andrew Trick7004e4b2012-03-26 22:33:59 +00006438 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6439 if (!VarIdx)
6440 return getCouldNotCompute();
6441
Chris Lattnerec901cc2004-10-12 01:49:27 +00006442 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6443 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006444 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006445 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006446
6447 // We can only recognize very limited forms of loop index expressions, in
6448 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006449 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006450 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006451 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6452 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006453 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006454
6455 unsigned MaxSteps = MaxBruteForceIterations;
6456 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006457 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006458 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006459 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006460
6461 // Form the GEP offset.
6462 Indexes[VarIdxNum] = Val;
6463
Chris Lattnere166a852012-01-24 05:49:24 +00006464 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6465 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006466 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006467
6468 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006469 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006470 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006471 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006472 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006473 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006474 }
6475 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006476 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006477}
6478
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006479ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6480 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6481 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6482 if (!RHS)
6483 return getCouldNotCompute();
6484
6485 const BasicBlock *Latch = L->getLoopLatch();
6486 if (!Latch)
6487 return getCouldNotCompute();
6488
6489 const BasicBlock *Predecessor = L->getLoopPredecessor();
6490 if (!Predecessor)
6491 return getCouldNotCompute();
6492
6493 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6494 // Return LHS in OutLHS and shift_opt in OutOpCode.
6495 auto MatchPositiveShift =
6496 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6497
6498 using namespace PatternMatch;
6499
6500 ConstantInt *ShiftAmt;
6501 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6502 OutOpCode = Instruction::LShr;
6503 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6504 OutOpCode = Instruction::AShr;
6505 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6506 OutOpCode = Instruction::Shl;
6507 else
6508 return false;
6509
6510 return ShiftAmt->getValue().isStrictlyPositive();
6511 };
6512
6513 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6514 //
6515 // loop:
6516 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6517 // %iv.shifted = lshr i32 %iv, <positive constant>
6518 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006519 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006520 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6521 auto MatchShiftRecurrence =
6522 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6523 Optional<Instruction::BinaryOps> PostShiftOpCode;
6524
6525 {
6526 Instruction::BinaryOps OpC;
6527 Value *V;
6528
6529 // If we encounter a shift instruction, "peel off" the shift operation,
6530 // and remember that we did so. Later when we inspect %iv's backedge
6531 // value, we will make sure that the backedge value uses the same
6532 // operation.
6533 //
6534 // Note: the peeled shift operation does not have to be the same
6535 // instruction as the one feeding into the PHI's backedge value. We only
6536 // really care about it being the same *kind* of shift instruction --
6537 // that's all that is required for our later inferences to hold.
6538 if (MatchPositiveShift(LHS, V, OpC)) {
6539 PostShiftOpCode = OpC;
6540 LHS = V;
6541 }
6542 }
6543
6544 PNOut = dyn_cast<PHINode>(LHS);
6545 if (!PNOut || PNOut->getParent() != L->getHeader())
6546 return false;
6547
6548 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6549 Value *OpLHS;
6550
6551 return
6552 // The backedge value for the PHI node must be a shift by a positive
6553 // amount
6554 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6555
6556 // of the PHI node itself
6557 OpLHS == PNOut &&
6558
6559 // and the kind of shift should be match the kind of shift we peeled
6560 // off, if any.
6561 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6562 };
6563
6564 PHINode *PN;
6565 Instruction::BinaryOps OpCode;
6566 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6567 return getCouldNotCompute();
6568
6569 const DataLayout &DL = getDataLayout();
6570
6571 // The key rationale for this optimization is that for some kinds of shift
6572 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6573 // within a finite number of iterations. If the condition guarding the
6574 // backedge (in the sense that the backedge is taken if the condition is true)
6575 // is false for the value the shift recurrence stabilizes to, then we know
6576 // that the backedge is taken only a finite number of times.
6577
6578 ConstantInt *StableValue = nullptr;
6579 switch (OpCode) {
6580 default:
6581 llvm_unreachable("Impossible case!");
6582
6583 case Instruction::AShr: {
6584 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6585 // bitwidth(K) iterations.
6586 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6587 bool KnownZero, KnownOne;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00006588 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006589 Predecessor->getTerminator(), &DT);
6590 auto *Ty = cast<IntegerType>(RHS->getType());
6591 if (KnownZero)
6592 StableValue = ConstantInt::get(Ty, 0);
6593 else if (KnownOne)
6594 StableValue = ConstantInt::get(Ty, -1, true);
6595 else
6596 return getCouldNotCompute();
6597
6598 break;
6599 }
6600 case Instruction::LShr:
6601 case Instruction::Shl:
6602 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6603 // stabilize to 0 in at most bitwidth(K) iterations.
6604 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6605 break;
6606 }
6607
6608 auto *Result =
6609 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6610 assert(Result->getType()->isIntegerTy(1) &&
6611 "Otherwise cannot be an operand to a branch instruction");
6612
6613 if (Result->isZeroValue()) {
6614 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6615 const SCEV *UpperBound =
6616 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006617 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006618 }
6619
6620 return getCouldNotCompute();
6621}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006622
Sanjoy Dasf8570812016-05-29 00:38:22 +00006623/// Return true if we can constant fold an instruction of the specified type,
6624/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006625static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006626 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006627 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6628 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006629 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006630
Chris Lattnerdd730472004-04-17 22:58:41 +00006631 if (const CallInst *CI = dyn_cast<CallInst>(I))
6632 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006633 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006634 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006635}
6636
Andrew Trick3a86ba72011-10-05 03:25:31 +00006637/// Determine whether this instruction can constant evolve within this loop
6638/// assuming its operands can all constant evolve.
6639static bool canConstantEvolve(Instruction *I, const Loop *L) {
6640 // An instruction outside of the loop can't be derived from a loop PHI.
6641 if (!L->contains(I)) return false;
6642
6643 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006644 // We don't currently keep track of the control flow needed to evaluate
6645 // PHIs, so we cannot handle PHIs inside of loops.
6646 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006647 }
6648
6649 // If we won't be able to constant fold this expression even if the operands
6650 // are constants, bail early.
6651 return CanConstantFold(I);
6652}
6653
6654/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6655/// recursing through each instruction operand until reaching a loop header phi.
6656static PHINode *
6657getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Michael Liao468fb742017-01-13 18:28:30 +00006658 DenseMap<Instruction *, PHINode *> &PHIMap,
6659 unsigned Depth) {
6660 if (Depth > MaxConstantEvolvingDepth)
6661 return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006662
6663 // Otherwise, we can evaluate this instruction if all of its operands are
6664 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006665 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006666 for (Value *Op : UseInst->operands()) {
6667 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006668
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006669 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006670 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006671
6672 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006673 if (!P)
6674 // If this operand is already visited, reuse the prior result.
6675 // We may have P != PHI if this is the deepest point at which the
6676 // inconsistent paths meet.
6677 P = PHIMap.lookup(OpInst);
6678 if (!P) {
6679 // Recurse and memoize the results, whether a phi is found or not.
6680 // This recursive call invalidates pointers into PHIMap.
Michael Liao468fb742017-01-13 18:28:30 +00006681 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006682 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006683 }
Craig Topper9f008862014-04-15 04:59:12 +00006684 if (!P)
6685 return nullptr; // Not evolving from PHI
6686 if (PHI && PHI != P)
6687 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006688 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006689 }
6690 // This is a expression evolving from a constant PHI!
6691 return PHI;
6692}
6693
Chris Lattnerdd730472004-04-17 22:58:41 +00006694/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6695/// in the loop that V is derived from. We allow arbitrary operations along the
6696/// way, but the operands of an operation must either be constants or a value
6697/// derived from a constant PHI. If this expression does not fit with these
6698/// constraints, return null.
6699static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006700 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006701 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006702
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006703 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006704 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006705
Andrew Trick3a86ba72011-10-05 03:25:31 +00006706 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006707 DenseMap<Instruction *, PHINode *> PHIMap;
Michael Liao468fb742017-01-13 18:28:30 +00006708 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
Chris Lattnerdd730472004-04-17 22:58:41 +00006709}
6710
6711/// EvaluateExpression - Given an expression that passes the
6712/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6713/// in the loop has the value PHIVal. If we can't fold this expression for some
6714/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006715static Constant *EvaluateExpression(Value *V, const Loop *L,
6716 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006717 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006718 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006719 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006720 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006721 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006722 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006723
Andrew Trick3a86ba72011-10-05 03:25:31 +00006724 if (Constant *C = Vals.lookup(I)) return C;
6725
Nick Lewyckya6674c72011-10-22 19:58:20 +00006726 // An instruction inside the loop depends on a value outside the loop that we
6727 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006728 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006729
6730 // An unmapped PHI can be due to a branch or another loop inside this loop,
6731 // or due to this not being the initial iteration through a loop where we
6732 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006733 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006734
Dan Gohmanf820bd32010-06-22 13:15:46 +00006735 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006736
6737 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006738 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6739 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006740 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006741 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006742 continue;
6743 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006744 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006745 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006746 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006747 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006748 }
6749
Nick Lewyckya6674c72011-10-22 19:58:20 +00006750 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006751 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006752 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006753 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6754 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006755 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006756 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006757 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006758}
6759
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006760
6761// If every incoming value to PN except the one for BB is a specific Constant,
6762// return that, else return nullptr.
6763static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6764 Constant *IncomingVal = nullptr;
6765
6766 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6767 if (PN->getIncomingBlock(i) == BB)
6768 continue;
6769
6770 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6771 if (!CurrentVal)
6772 return nullptr;
6773
6774 if (IncomingVal != CurrentVal) {
6775 if (IncomingVal)
6776 return nullptr;
6777 IncomingVal = CurrentVal;
6778 }
6779 }
6780
6781 return IncomingVal;
6782}
6783
Chris Lattnerdd730472004-04-17 22:58:41 +00006784/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6785/// in the header of its containing loop, we know the loop executes a
6786/// constant number of times, and the PHI node is just a recurrence
6787/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006788Constant *
6789ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006790 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006791 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006792 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006793 if (I != ConstantEvolutionLoopExitValue.end())
6794 return I->second;
6795
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006796 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006797 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006798
6799 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6800
Andrew Trick3a86ba72011-10-05 03:25:31 +00006801 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006802 BasicBlock *Header = L->getHeader();
6803 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006804
Sanjoy Dasdd709962015-10-08 18:28:36 +00006805 BasicBlock *Latch = L->getLoopLatch();
6806 if (!Latch)
6807 return nullptr;
6808
Sanjoy Das4493b402015-10-07 17:38:25 +00006809 for (auto &I : *Header) {
6810 PHINode *PHI = dyn_cast<PHINode>(&I);
6811 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006812 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006813 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006814 CurrentIterVals[PHI] = StartCST;
6815 }
6816 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006817 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006818
Sanjoy Dasdd709962015-10-08 18:28:36 +00006819 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006820
6821 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006822 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006823 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006824
Dan Gohman0bddac12009-02-24 18:55:53 +00006825 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006826 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006827 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006828 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006829 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006830 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006831
Nick Lewyckya6674c72011-10-22 19:58:20 +00006832 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006833 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006834 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006835 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006836 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006837 if (!NextPHI)
6838 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006839 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006840
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006841 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6842
Nick Lewyckya6674c72011-10-22 19:58:20 +00006843 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6844 // cease to be able to evaluate one of them or if they stop evolving,
6845 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006846 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006847 for (const auto &I : CurrentIterVals) {
6848 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006849 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006850 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006851 }
6852 // We use two distinct loops because EvaluateExpression may invalidate any
6853 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006854 for (const auto &I : PHIsToCompute) {
6855 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006856 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006857 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006858 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006859 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006860 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006861 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006862 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006863 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006864
6865 // If all entries in CurrentIterVals == NextIterVals then we can stop
6866 // iterating, the loop can't continue to change.
6867 if (StoppedEvolving)
6868 return RetVal = CurrentIterVals[PN];
6869
Andrew Trick3a86ba72011-10-05 03:25:31 +00006870 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006871 }
6872}
6873
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006874const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006875 Value *Cond,
6876 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006877 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006878 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006879
Dan Gohman866971e2010-06-19 14:17:24 +00006880 // If the loop is canonicalized, the PHI will have exactly two entries.
6881 // That's the only form we support here.
6882 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6883
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006884 DenseMap<Instruction *, Constant *> CurrentIterVals;
6885 BasicBlock *Header = L->getHeader();
6886 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6887
Sanjoy Dasdd709962015-10-08 18:28:36 +00006888 BasicBlock *Latch = L->getLoopLatch();
6889 assert(Latch && "Should follow from NumIncomingValues == 2!");
6890
Sanjoy Das4493b402015-10-07 17:38:25 +00006891 for (auto &I : *Header) {
6892 PHINode *PHI = dyn_cast<PHINode>(&I);
6893 if (!PHI)
6894 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006895 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006896 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006897 CurrentIterVals[PHI] = StartCST;
6898 }
6899 if (!CurrentIterVals.count(PN))
6900 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006901
6902 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6903 // the loop symbolically to determine when the condition gets a value of
6904 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006905 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006906 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006907 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006908 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006909 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006910
Zhou Sheng75b871f2007-01-11 12:24:14 +00006911 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006912 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006913
Reid Spencer983e3b32007-03-01 07:25:48 +00006914 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006915 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006916 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006917 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006918
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006919 // Update all the PHI nodes for the next iteration.
6920 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006921
6922 // Create a list of which PHIs we need to compute. We want to do this before
6923 // calling EvaluateExpression on them because that may invalidate iterators
6924 // into CurrentIterVals.
6925 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006926 for (const auto &I : CurrentIterVals) {
6927 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006928 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006929 PHIsToCompute.push_back(PHI);
6930 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006931 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006932 Constant *&NextPHI = NextIterVals[PHI];
6933 if (NextPHI) continue; // Already computed!
6934
Sanjoy Dasdd709962015-10-08 18:28:36 +00006935 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006936 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006937 }
6938 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006939 }
6940
6941 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006942 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006943}
6944
Dan Gohmanaf752342009-07-07 17:06:11 +00006945const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006946 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6947 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006948 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006949 for (auto &LS : Values)
6950 if (LS.first == L)
6951 return LS.second ? LS.second : V;
6952
6953 Values.emplace_back(L, nullptr);
6954
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006955 // Otherwise compute it.
6956 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006957 for (auto &LS : reverse(ValuesAtScopes[V]))
6958 if (LS.first == L) {
6959 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006960 break;
6961 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006962 return C;
6963}
6964
Nick Lewyckya6674c72011-10-22 19:58:20 +00006965/// This builds up a Constant using the ConstantExpr interface. That way, we
6966/// will return Constants for objects which aren't represented by a
6967/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6968/// Returns NULL if the SCEV isn't representable as a Constant.
6969static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006970 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006971 case scCouldNotCompute:
6972 case scAddRecExpr:
6973 break;
6974 case scConstant:
6975 return cast<SCEVConstant>(V)->getValue();
6976 case scUnknown:
6977 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6978 case scSignExtend: {
6979 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6980 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6981 return ConstantExpr::getSExt(CastOp, SS->getType());
6982 break;
6983 }
6984 case scZeroExtend: {
6985 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6986 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6987 return ConstantExpr::getZExt(CastOp, SZ->getType());
6988 break;
6989 }
6990 case scTruncate: {
6991 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6992 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6993 return ConstantExpr::getTrunc(CastOp, ST->getType());
6994 break;
6995 }
6996 case scAddExpr: {
6997 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6998 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006999 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7000 unsigned AS = PTy->getAddressSpace();
7001 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7002 C = ConstantExpr::getBitCast(C, DestPtrTy);
7003 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00007004 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7005 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00007006 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007007
7008 // First pointer!
7009 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007010 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00007011 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007012 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007013 // The offsets have been converted to bytes. We can add bytes to an
7014 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007015 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007016 }
7017
7018 // Don't bother trying to sum two pointers. We probably can't
7019 // statically compute a load that results from it anyway.
7020 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00007021 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007022
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007023 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7024 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00007025 C2 = ConstantExpr::getIntegerCast(
7026 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00007027 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007028 } else
7029 C = ConstantExpr::getAdd(C, C2);
7030 }
7031 return C;
7032 }
7033 break;
7034 }
7035 case scMulExpr: {
7036 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7037 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7038 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00007039 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007040 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7041 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00007042 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007043 C = ConstantExpr::getMul(C, C2);
7044 }
7045 return C;
7046 }
7047 break;
7048 }
7049 case scUDivExpr: {
7050 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7051 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7052 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7053 if (LHS->getType() == RHS->getType())
7054 return ConstantExpr::getUDiv(LHS, RHS);
7055 break;
7056 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00007057 case scSMaxExpr:
7058 case scUMaxExpr:
7059 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00007060 }
Craig Topper9f008862014-04-15 04:59:12 +00007061 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007062}
7063
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00007064const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007065 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00007066
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00007067 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00007068 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00007069 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007070 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007071 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00007072 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
7073 if (PHINode *PN = dyn_cast<PHINode>(I))
7074 if (PN->getParent() == LI->getHeader()) {
7075 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00007076 // to see if the loop that contains it has a known backedge-taken
7077 // count. If so, we may be able to force computation of the exit
7078 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00007079 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00007080 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00007081 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007082 // Okay, we know how many times the containing loop executes. If
7083 // this is a constant evolving PHI node, get the final value at
7084 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007085 Constant *RV =
7086 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00007087 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00007088 }
7089 }
7090
Reid Spencere6328ca2006-12-04 21:33:23 +00007091 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00007092 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00007093 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00007094 // result. This is particularly useful for computing loop exit values.
7095 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007096 SmallVector<Constant *, 4> Operands;
7097 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00007098 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007099 if (Constant *C = dyn_cast<Constant>(Op)) {
7100 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007101 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00007102 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007103
7104 // If any of the operands is non-constant and if they are
7105 // non-integer and non-pointer, don't even try to analyze them
7106 // with scev techniques.
7107 if (!isSCEVable(Op->getType()))
7108 return V;
7109
7110 const SCEV *OrigV = getSCEV(Op);
7111 const SCEV *OpV = getSCEVAtScope(OrigV, L);
7112 MadeImprovement |= OrigV != OpV;
7113
Nick Lewyckya6674c72011-10-22 19:58:20 +00007114 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007115 if (!C) return V;
7116 if (C->getType() != Op->getType())
7117 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7118 Op->getType(),
7119 false),
7120 C, Op->getType());
7121 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00007122 }
Dan Gohmance973df2009-06-24 04:48:43 +00007123
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007124 // Check to see if getSCEVAtScope actually made an improvement.
7125 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00007126 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00007127 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007128 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00007129 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007130 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007131 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7132 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00007133 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007134 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00007135 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007136 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00007137 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007138 }
Chris Lattnerdd730472004-04-17 22:58:41 +00007139 }
7140 }
7141
7142 // This is some other type of SCEVUnknown, just return it.
7143 return V;
7144 }
7145
Dan Gohmana30370b2009-05-04 22:02:23 +00007146 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007147 // Avoid performing the look-up in the common case where the specified
7148 // expression has no loop-variant portions.
7149 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007150 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007151 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007152 // Okay, at least one of these operands is loop variant but might be
7153 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00007154 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7155 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00007156 NewOps.push_back(OpAtScope);
7157
7158 for (++i; i != e; ++i) {
7159 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007160 NewOps.push_back(OpAtScope);
7161 }
7162 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007163 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007164 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007165 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007166 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007167 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00007168 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007169 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00007170 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007171 }
7172 }
7173 // If we got here, all operands are loop invariant.
7174 return Comm;
7175 }
7176
Dan Gohmana30370b2009-05-04 22:02:23 +00007177 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007178 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7179 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00007180 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7181 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00007182 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00007183 }
7184
7185 // If this is a loop recurrence for a loop that does not contain L, then we
7186 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00007187 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007188 // First, attempt to evaluate each operand.
7189 // Avoid performing the look-up in the common case where the specified
7190 // expression has no loop-variant portions.
7191 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7192 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7193 if (OpAtScope == AddRec->getOperand(i))
7194 continue;
7195
7196 // Okay, at least one of these operands is loop variant but might be
7197 // foldable. Build a new instance of the folded commutative expression.
7198 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7199 AddRec->op_begin()+i);
7200 NewOps.push_back(OpAtScope);
7201 for (++i; i != e; ++i)
7202 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7203
Andrew Trick759ba082011-04-27 01:21:25 +00007204 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00007205 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00007206 AddRec->getNoWrapFlags(SCEV::FlagNW));
7207 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00007208 // The addrec may be folded to a nonrecurrence, for example, if the
7209 // induction variable is multiplied by zero after constant folding. Go
7210 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00007211 if (!AddRec)
7212 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007213 break;
7214 }
7215
7216 // If the scope is outside the addrec's loop, evaluate it by using the
7217 // loop exit value of the addrec.
7218 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007219 // To evaluate this recurrence, we need to know how many times the AddRec
7220 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00007221 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007222 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00007223
Eli Friedman61f67622008-08-04 23:49:06 +00007224 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00007225 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007226 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007227
Dan Gohman8ca08852009-05-24 23:25:42 +00007228 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00007229 }
7230
Dan Gohmana30370b2009-05-04 22:02:23 +00007231 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007232 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007233 if (Op == Cast->getOperand())
7234 return Cast; // must be loop invariant
7235 return getZeroExtendExpr(Op, Cast->getType());
7236 }
7237
Dan Gohmana30370b2009-05-04 22:02:23 +00007238 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007239 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007240 if (Op == Cast->getOperand())
7241 return Cast; // must be loop invariant
7242 return getSignExtendExpr(Op, Cast->getType());
7243 }
7244
Dan Gohmana30370b2009-05-04 22:02:23 +00007245 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007246 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007247 if (Op == Cast->getOperand())
7248 return Cast; // must be loop invariant
7249 return getTruncateExpr(Op, Cast->getType());
7250 }
7251
Torok Edwinfbcc6632009-07-14 16:55:14 +00007252 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007253}
7254
Dan Gohmanaf752342009-07-07 17:06:11 +00007255const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007256 return getSCEVAtScope(getSCEV(V), L);
7257}
7258
Sanjoy Dasf8570812016-05-29 00:38:22 +00007259/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007260///
7261/// A * X = B (mod N)
7262///
7263/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7264/// A and B isn't important.
7265///
7266/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007267static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007268 ScalarEvolution &SE) {
7269 uint32_t BW = A.getBitWidth();
Eli Friedman10d1ff62017-01-31 00:42:42 +00007270 assert(BW == SE.getTypeSizeInBits(B->getType()));
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007271 assert(A != 0 && "A must be non-zero.");
7272
7273 // 1. D = gcd(A, N)
7274 //
7275 // The gcd of A and N may have only one prime factor: 2. The number of
7276 // trailing zeros in A is its multiplicity
7277 uint32_t Mult2 = A.countTrailingZeros();
7278 // D = 2^Mult2
7279
7280 // 2. Check if B is divisible by D.
7281 //
7282 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7283 // is not less than multiplicity of this prime factor for D.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007284 if (SE.GetMinTrailingZeros(B) < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007285 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007286
7287 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7288 // modulo (N / D).
7289 //
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007290 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7291 // (N / D) in general. The inverse itself always fits into BW bits, though,
7292 // so we immediately truncate it.
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007293 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7294 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007295 Mod.setBit(BW - Mult2); // Mod = N / D
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007296 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007297
7298 // 4. Compute the minimum unsigned root of the equation:
7299 // I * (B / D) mod (N / D)
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007300 // To simplify the computation, we factor out the divide by D:
7301 // (I * B mod N) / D
Eli Friedman10d1ff62017-01-31 00:42:42 +00007302 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7303 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007304}
Chris Lattnerd934c702004-04-02 20:23:17 +00007305
Sanjoy Dasf8570812016-05-29 00:38:22 +00007306/// Find the roots of the quadratic equation for the given quadratic chrec
7307/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7308/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007309///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007310static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007311SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007312 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007313 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7314 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7315 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007316
Chris Lattnerd934c702004-04-02 20:23:17 +00007317 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007318 if (!LC || !MC || !NC)
7319 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007320
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007321 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7322 const APInt &L = LC->getAPInt();
7323 const APInt &M = MC->getAPInt();
7324 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007325 APInt Two(BitWidth, 2);
7326 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007327
Dan Gohmance973df2009-06-24 04:48:43 +00007328 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007329 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007330 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007331 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7332 // The B coefficient is M-N/2
7333 APInt B(M);
Craig Topper9ab8d7f2017-04-01 05:08:57 +00007334 B -= N.sdiv(Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007335
Reid Spencer983e3b32007-03-01 07:25:48 +00007336 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007337 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007338
Reid Spencer983e3b32007-03-01 07:25:48 +00007339 // Compute the B^2-4ac term.
7340 APInt SqrtTerm(B);
7341 SqrtTerm *= B;
7342 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007343
Nick Lewyckyfb780832012-08-01 09:14:36 +00007344 if (SqrtTerm.isNegative()) {
7345 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007346 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007347 }
7348
Reid Spencer983e3b32007-03-01 07:25:48 +00007349 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7350 // integer value or else APInt::sqrt() will assert.
7351 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007352
Dan Gohmance973df2009-06-24 04:48:43 +00007353 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007354 // The divisions must be performed as signed divisions.
7355 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007356 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007357 if (TwoA.isMinValue())
7358 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007359
Owen Anderson47db9412009-07-22 00:24:57 +00007360 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007361
7362 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007363 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007364 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007365 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007366
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007367 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7368 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007369 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007370}
7371
Andrew Trick3ca3f982011-07-26 17:19:55 +00007372ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007373ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007374 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007375
7376 // This is only used for loops with a "x != y" exit test. The exit condition
7377 // is now expressed as a single expression, V = x-y. So the exit test is
7378 // effectively V != 0. We know and take advantage of the fact that this
7379 // expression only being used in a comparison by zero context.
7380
Sanjoy Dasf0022122016-09-28 17:14:58 +00007381 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007382 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007383 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007384 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007385 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007386 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007387 }
7388
Dan Gohman48f82222009-05-04 22:30:44 +00007389 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007390 if (!AddRec && AllowPredicates)
7391 // Try to make this an AddRec using runtime tests, in the first X
7392 // iterations of this loop, where X is the SCEV expression found by the
7393 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007394 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007395
Chris Lattnerd934c702004-04-02 20:23:17 +00007396 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007397 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007398
Chris Lattnerdff679f2011-01-09 22:39:48 +00007399 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7400 // the quadratic equation to solve it.
7401 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007402 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7403 const SCEVConstant *R1 = Roots->first;
7404 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007405 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007406 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7407 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007408 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007409 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007410
Chris Lattnerd934c702004-04-02 20:23:17 +00007411 // We can only use this value if the chrec ends up with an exact zero
7412 // value at this index. When solving for "X*X != 5", for example, we
7413 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007414 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007415 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007416 // We found a quadratic root!
7417 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007418 }
7419 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007420 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007421 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007422
Chris Lattnerdff679f2011-01-09 22:39:48 +00007423 // Otherwise we can only handle this if it is affine.
7424 if (!AddRec->isAffine())
7425 return getCouldNotCompute();
7426
7427 // If this is an affine expression, the execution count of this branch is
7428 // the minimum unsigned root of the following equation:
7429 //
7430 // Start + Step*N = 0 (mod 2^BW)
7431 //
7432 // equivalent to:
7433 //
7434 // Step*N = -Start (mod 2^BW)
7435 //
7436 // where BW is the common bit width of Start and Step.
7437
7438 // Get the initial value for the loop.
7439 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7440 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7441
7442 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007443 //
7444 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7445 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7446 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7447 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007448 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007449 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007450 return getCouldNotCompute();
7451
Andrew Trick8b55b732011-03-14 16:50:06 +00007452 // For positive steps (counting up until unsigned overflow):
7453 // N = -Start/Step (as unsigned)
7454 // For negative steps (counting down to zero):
7455 // N = Start/-Step
7456 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007457 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007458 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007459
7460 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007461 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7462 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007463 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
Eli Friedman83962652017-01-11 20:55:48 +00007464 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
Eli Friedmanbd6deda2017-01-11 21:07:15 +00007465
7466 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7467 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7468 // case, and see if we can improve the bound.
7469 //
7470 // Explicitly handling this here is necessary because getUnsignedRange
7471 // isn't context-sensitive; it doesn't know that we only care about the
7472 // range inside the loop.
7473 const SCEV *Zero = getZero(Distance->getType());
7474 const SCEV *One = getOne(Distance->getType());
7475 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7476 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7477 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7478 // as "unsigned_max(Distance + 1) - 1".
7479 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7480 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7481 }
Eli Friedman83962652017-01-11 20:55:48 +00007482 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007483 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007484
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007485 // If the condition controls loop exit (the loop exits only if the expression
7486 // is true) and the addition is no-wrap we can use unsigned divide to
7487 // compute the backedge count. In this case, the step may not divide the
7488 // distance, but we don't care because if the condition is "missed" the loop
7489 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007490 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7491 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007492 const SCEV *Exact =
7493 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
John Brawn84b21832016-10-21 11:08:48 +00007494 return ExitLimit(Exact, Exact, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007495 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007496
Eli Friedman10d1ff62017-01-31 00:42:42 +00007497 // Solve the general equation.
7498 const SCEV *E = SolveLinEquationWithOverflow(
7499 StepC->getAPInt(), getNegativeSCEV(Start), *this);
7500 return ExitLimit(E, E, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007501}
7502
Andrew Trick3ca3f982011-07-26 17:19:55 +00007503ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007504ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007505 // Loops that look like: while (X == 0) are very strange indeed. We don't
7506 // handle them yet except for the trivial case. This could be expanded in the
7507 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007508
Chris Lattnerd934c702004-04-02 20:23:17 +00007509 // If the value is a constant, check to see if it is known to be non-zero
7510 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007511 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007512 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007513 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007514 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007515 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007516
Chris Lattnerd934c702004-04-02 20:23:17 +00007517 // We could implement others, but I really doubt anyone writes loops like
7518 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007519 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007520}
7521
Dan Gohman4e3c1132010-04-15 16:19:08 +00007522std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007523ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007524 // If the block has a unique predecessor, then there is no path from the
7525 // predecessor to the block that does not go through the direct edge
7526 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007527 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007528 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007529
7530 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007531 // If the header has a unique predecessor outside the loop, it must be
7532 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007533 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007534 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007535
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007536 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007537}
7538
Sanjoy Dasf8570812016-05-29 00:38:22 +00007539/// SCEV structural equivalence is usually sufficient for testing whether two
7540/// expressions are equal, however for the purposes of looking for a condition
7541/// guarding a loop, it can be useful to be a little more general, since a
7542/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007543///
Dan Gohmanaf752342009-07-07 17:06:11 +00007544static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007545 // Quick check to see if they are the same SCEV.
7546 if (A == B) return true;
7547
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007548 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7549 // Not all instructions that are "identical" compute the same value. For
7550 // instance, two distinct alloca instructions allocating the same type are
7551 // identical and do not read memory; but compute distinct values.
7552 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7553 };
7554
Dan Gohman450f4e02009-06-20 00:35:32 +00007555 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7556 // two different instructions with the same value. Check for this case.
7557 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7558 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7559 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7560 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007561 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007562 return true;
7563
7564 // Otherwise assume they may have a different value.
7565 return false;
7566}
7567
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007568bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007569 const SCEV *&LHS, const SCEV *&RHS,
7570 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007571 bool Changed = false;
7572
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007573 // If we hit the max recursion limit bail out.
7574 if (Depth >= 3)
7575 return false;
7576
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007577 // Canonicalize a constant to the right side.
7578 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7579 // Check for both operands constant.
7580 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7581 if (ConstantExpr::getICmp(Pred,
7582 LHSC->getValue(),
7583 RHSC->getValue())->isNullValue())
7584 goto trivially_false;
7585 else
7586 goto trivially_true;
7587 }
7588 // Otherwise swap the operands to put the constant on the right.
7589 std::swap(LHS, RHS);
7590 Pred = ICmpInst::getSwappedPredicate(Pred);
7591 Changed = true;
7592 }
7593
7594 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007595 // addrec's loop, put the addrec on the left. Also make a dominance check,
7596 // as both operands could be addrecs loop-invariant in each other's loop.
7597 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7598 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007599 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007600 std::swap(LHS, RHS);
7601 Pred = ICmpInst::getSwappedPredicate(Pred);
7602 Changed = true;
7603 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007604 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007605
7606 // If there's a constant operand, canonicalize comparisons with boundary
7607 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7608 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007609 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007610
7611 bool SimplifiedByConstantRange = false;
7612
7613 if (!ICmpInst::isEquality(Pred)) {
7614 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7615 if (ExactCR.isFullSet())
7616 goto trivially_true;
7617 else if (ExactCR.isEmptySet())
7618 goto trivially_false;
7619
7620 APInt NewRHS;
7621 CmpInst::Predicate NewPred;
7622 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7623 ICmpInst::isEquality(NewPred)) {
7624 // We were able to convert an inequality to an equality.
7625 Pred = NewPred;
7626 RHS = getConstant(NewRHS);
7627 Changed = SimplifiedByConstantRange = true;
7628 }
7629 }
7630
7631 if (!SimplifiedByConstantRange) {
7632 switch (Pred) {
7633 default:
7634 break;
7635 case ICmpInst::ICMP_EQ:
7636 case ICmpInst::ICMP_NE:
7637 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7638 if (!RA)
7639 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7640 if (const SCEVMulExpr *ME =
7641 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7642 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7643 ME->getOperand(0)->isAllOnesValue()) {
7644 RHS = AE->getOperand(1);
7645 LHS = ME->getOperand(1);
7646 Changed = true;
7647 }
7648 break;
7649
7650
7651 // The "Should have been caught earlier!" messages refer to the fact
7652 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7653 // should have fired on the corresponding cases, and canonicalized the
7654 // check to trivially_true or trivially_false.
7655
7656 case ICmpInst::ICMP_UGE:
7657 assert(!RA.isMinValue() && "Should have been caught earlier!");
7658 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007659 RHS = getConstant(RA - 1);
7660 Changed = true;
7661 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007662 case ICmpInst::ICMP_ULE:
7663 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7664 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007665 RHS = getConstant(RA + 1);
7666 Changed = true;
7667 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007668 case ICmpInst::ICMP_SGE:
7669 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7670 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007671 RHS = getConstant(RA - 1);
7672 Changed = true;
7673 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007674 case ICmpInst::ICMP_SLE:
7675 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7676 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007677 RHS = getConstant(RA + 1);
7678 Changed = true;
7679 break;
7680 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007681 }
7682 }
7683
7684 // Check for obvious equality.
7685 if (HasSameValue(LHS, RHS)) {
7686 if (ICmpInst::isTrueWhenEqual(Pred))
7687 goto trivially_true;
7688 if (ICmpInst::isFalseWhenEqual(Pred))
7689 goto trivially_false;
7690 }
7691
Dan Gohman81585c12010-05-03 16:35:17 +00007692 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7693 // adding or subtracting 1 from one of the operands.
7694 switch (Pred) {
7695 case ICmpInst::ICMP_SLE:
7696 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7697 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007698 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007699 Pred = ICmpInst::ICMP_SLT;
7700 Changed = true;
7701 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007702 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007703 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007704 Pred = ICmpInst::ICMP_SLT;
7705 Changed = true;
7706 }
7707 break;
7708 case ICmpInst::ICMP_SGE:
7709 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007710 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007711 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007712 Pred = ICmpInst::ICMP_SGT;
7713 Changed = true;
7714 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7715 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007716 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007717 Pred = ICmpInst::ICMP_SGT;
7718 Changed = true;
7719 }
7720 break;
7721 case ICmpInst::ICMP_ULE:
7722 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007723 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007724 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007725 Pred = ICmpInst::ICMP_ULT;
7726 Changed = true;
7727 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007728 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007729 Pred = ICmpInst::ICMP_ULT;
7730 Changed = true;
7731 }
7732 break;
7733 case ICmpInst::ICMP_UGE:
7734 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007735 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007736 Pred = ICmpInst::ICMP_UGT;
7737 Changed = true;
7738 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007739 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007740 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007741 Pred = ICmpInst::ICMP_UGT;
7742 Changed = true;
7743 }
7744 break;
7745 default:
7746 break;
7747 }
7748
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007749 // TODO: More simplifications are possible here.
7750
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007751 // Recursively simplify until we either hit a recursion limit or nothing
7752 // changes.
7753 if (Changed)
7754 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7755
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007756 return Changed;
7757
7758trivially_true:
7759 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007760 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007761 Pred = ICmpInst::ICMP_EQ;
7762 return true;
7763
7764trivially_false:
7765 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007766 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007767 Pred = ICmpInst::ICMP_NE;
7768 return true;
7769}
7770
Dan Gohmane65c9172009-07-13 21:35:55 +00007771bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7772 return getSignedRange(S).getSignedMax().isNegative();
7773}
7774
7775bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7776 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7777}
7778
7779bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7780 return !getSignedRange(S).getSignedMin().isNegative();
7781}
7782
7783bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7784 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7785}
7786
7787bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7788 return isKnownNegative(S) || isKnownPositive(S);
7789}
7790
7791bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7792 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007793 // Canonicalize the inputs first.
7794 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7795
Dan Gohman07591692010-04-11 22:16:48 +00007796 // If LHS or RHS is an addrec, check to see if the condition is true in
7797 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007798 // If LHS and RHS are both addrec, both conditions must be true in
7799 // every iteration of the loop.
7800 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7801 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7802 bool LeftGuarded = false;
7803 bool RightGuarded = false;
7804 if (LAR) {
7805 const Loop *L = LAR->getLoop();
7806 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7807 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7808 if (!RAR) return true;
7809 LeftGuarded = true;
7810 }
7811 }
7812 if (RAR) {
7813 const Loop *L = RAR->getLoop();
7814 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7815 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7816 if (!LAR) return true;
7817 RightGuarded = true;
7818 }
7819 }
7820 if (LeftGuarded && RightGuarded)
7821 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007822
Sanjoy Das7d910f22015-10-02 18:50:30 +00007823 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7824 return true;
7825
Dan Gohman07591692010-04-11 22:16:48 +00007826 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007827 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007828}
7829
Sanjoy Das5dab2052015-07-27 21:42:49 +00007830bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7831 ICmpInst::Predicate Pred,
7832 bool &Increasing) {
7833 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7834
7835#ifndef NDEBUG
7836 // Verify an invariant: inverting the predicate should turn a monotonically
7837 // increasing change to a monotonically decreasing one, and vice versa.
7838 bool IncreasingSwapped;
7839 bool ResultSwapped = isMonotonicPredicateImpl(
7840 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7841
7842 assert(Result == ResultSwapped && "should be able to analyze both!");
7843 if (ResultSwapped)
7844 assert(Increasing == !IncreasingSwapped &&
7845 "monotonicity should flip as we flip the predicate");
7846#endif
7847
7848 return Result;
7849}
7850
7851bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7852 ICmpInst::Predicate Pred,
7853 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007854
7855 // A zero step value for LHS means the induction variable is essentially a
7856 // loop invariant value. We don't really depend on the predicate actually
7857 // flipping from false to true (for increasing predicates, and the other way
7858 // around for decreasing predicates), all we care about is that *if* the
7859 // predicate changes then it only changes from false to true.
7860 //
7861 // A zero step value in itself is not very useful, but there may be places
7862 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7863 // as general as possible.
7864
Sanjoy Das366acc12015-08-06 20:43:41 +00007865 switch (Pred) {
7866 default:
7867 return false; // Conservative answer
7868
7869 case ICmpInst::ICMP_UGT:
7870 case ICmpInst::ICMP_UGE:
7871 case ICmpInst::ICMP_ULT:
7872 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007873 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007874 return false;
7875
7876 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007877 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007878
7879 case ICmpInst::ICMP_SGT:
7880 case ICmpInst::ICMP_SGE:
7881 case ICmpInst::ICMP_SLT:
7882 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007883 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007884 return false;
7885
7886 const SCEV *Step = LHS->getStepRecurrence(*this);
7887
7888 if (isKnownNonNegative(Step)) {
7889 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7890 return true;
7891 }
7892
7893 if (isKnownNonPositive(Step)) {
7894 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7895 return true;
7896 }
7897
7898 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007899 }
7900
Sanjoy Das5dab2052015-07-27 21:42:49 +00007901 }
7902
Sanjoy Das366acc12015-08-06 20:43:41 +00007903 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007904}
7905
7906bool ScalarEvolution::isLoopInvariantPredicate(
7907 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7908 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7909 const SCEV *&InvariantRHS) {
7910
7911 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7912 if (!isLoopInvariant(RHS, L)) {
7913 if (!isLoopInvariant(LHS, L))
7914 return false;
7915
7916 std::swap(LHS, RHS);
7917 Pred = ICmpInst::getSwappedPredicate(Pred);
7918 }
7919
7920 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7921 if (!ArLHS || ArLHS->getLoop() != L)
7922 return false;
7923
7924 bool Increasing;
7925 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7926 return false;
7927
7928 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7929 // true as the loop iterates, and the backedge is control dependent on
7930 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7931 //
7932 // * if the predicate was false in the first iteration then the predicate
7933 // is never evaluated again, since the loop exits without taking the
7934 // backedge.
7935 // * if the predicate was true in the first iteration then it will
7936 // continue to be true for all future iterations since it is
7937 // monotonically increasing.
7938 //
7939 // For both the above possibilities, we can replace the loop varying
7940 // predicate with its value on the first iteration of the loop (which is
7941 // loop invariant).
7942 //
7943 // A similar reasoning applies for a monotonically decreasing predicate, by
7944 // replacing true with false and false with true in the above two bullets.
7945
7946 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7947
7948 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7949 return false;
7950
7951 InvariantPred = Pred;
7952 InvariantLHS = ArLHS->getStart();
7953 InvariantRHS = RHS;
7954 return true;
7955}
7956
Sanjoy Das401e6312016-02-01 20:48:10 +00007957bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7958 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007959 if (HasSameValue(LHS, RHS))
7960 return ICmpInst::isTrueWhenEqual(Pred);
7961
Dan Gohman07591692010-04-11 22:16:48 +00007962 // This code is split out from isKnownPredicate because it is called from
7963 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007964
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007965 auto CheckRanges =
7966 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7967 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7968 .contains(RangeLHS);
7969 };
7970
7971 // The check at the top of the function catches the case where the values are
7972 // known to be equal.
7973 if (Pred == CmpInst::ICMP_EQ)
7974 return false;
7975
7976 if (Pred == CmpInst::ICMP_NE)
7977 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7978 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7979 isKnownNonZero(getMinusSCEV(LHS, RHS));
7980
7981 if (CmpInst::isSigned(Pred))
7982 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7983
7984 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007985}
7986
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007987bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7988 const SCEV *LHS,
7989 const SCEV *RHS) {
7990
7991 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7992 // Return Y via OutY.
7993 auto MatchBinaryAddToConst =
7994 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7995 SCEV::NoWrapFlags ExpectedFlags) {
7996 const SCEV *NonConstOp, *ConstOp;
7997 SCEV::NoWrapFlags FlagsPresent;
7998
7999 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8000 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8001 return false;
8002
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008003 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008004 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8005 };
8006
8007 APInt C;
8008
8009 switch (Pred) {
8010 default:
8011 break;
8012
8013 case ICmpInst::ICMP_SGE:
8014 std::swap(LHS, RHS);
8015 case ICmpInst::ICMP_SLE:
8016 // X s<= (X + C)<nsw> if C >= 0
8017 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8018 return true;
8019
8020 // (X + C)<nsw> s<= X if C <= 0
8021 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8022 !C.isStrictlyPositive())
8023 return true;
8024 break;
8025
8026 case ICmpInst::ICMP_SGT:
8027 std::swap(LHS, RHS);
8028 case ICmpInst::ICMP_SLT:
8029 // X s< (X + C)<nsw> if C > 0
8030 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8031 C.isStrictlyPositive())
8032 return true;
8033
8034 // (X + C)<nsw> s< X if C < 0
8035 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8036 return true;
8037 break;
8038 }
8039
8040 return false;
8041}
8042
Sanjoy Das7d910f22015-10-02 18:50:30 +00008043bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8044 const SCEV *LHS,
8045 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00008046 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00008047 return false;
8048
8049 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8050 // the stack can result in exponential time complexity.
8051 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8052
8053 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8054 //
8055 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8056 // isKnownPredicate. isKnownPredicate is more powerful, but also more
8057 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8058 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
8059 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00008060 return isKnownNonNegative(RHS) &&
8061 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8062 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00008063}
8064
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008065bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8066 ICmpInst::Predicate Pred,
8067 const SCEV *LHS, const SCEV *RHS) {
8068 // No need to even try if we know the module has no guards.
8069 if (!HasGuards)
8070 return false;
8071
8072 return any_of(*BB, [&](Instruction &I) {
8073 using namespace llvm::PatternMatch;
8074
8075 Value *Condition;
8076 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8077 m_Value(Condition))) &&
8078 isImpliedCond(Pred, LHS, RHS, Condition, false);
8079 });
8080}
8081
Dan Gohmane65c9172009-07-13 21:35:55 +00008082/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8083/// protected by a conditional between LHS and RHS. This is used to
8084/// to eliminate casts.
8085bool
8086ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8087 ICmpInst::Predicate Pred,
8088 const SCEV *LHS, const SCEV *RHS) {
8089 // Interpret a null as meaning no loop, where there is obviously no guard
8090 // (interprocedural conditions notwithstanding).
8091 if (!L) return true;
8092
Sanjoy Das401e6312016-02-01 20:48:10 +00008093 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8094 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008095
Dan Gohmane65c9172009-07-13 21:35:55 +00008096 BasicBlock *Latch = L->getLoopLatch();
8097 if (!Latch)
8098 return false;
8099
8100 BranchInst *LoopContinuePredicate =
8101 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008102 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8103 isImpliedCond(Pred, LHS, RHS,
8104 LoopContinuePredicate->getCondition(),
8105 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8106 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00008107
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008108 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008109 // -- that can lead to O(n!) time complexity.
8110 if (WalkingBEDominatingConds)
8111 return false;
8112
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00008113 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008114
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00008115 // See if we can exploit a trip count to prove the predicate.
8116 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8117 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8118 if (LatchBECount != getCouldNotCompute()) {
8119 // We know that Latch branches back to the loop header exactly
8120 // LatchBECount times. This means the backdege condition at Latch is
8121 // equivalent to "{0,+,1} u< LatchBECount".
8122 Type *Ty = LatchBECount->getType();
8123 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8124 const SCEV *LoopCounter =
8125 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8126 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8127 LatchBECount))
8128 return true;
8129 }
8130
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008131 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008132 for (auto &AssumeVH : AC.assumptions()) {
8133 if (!AssumeVH)
8134 continue;
8135 auto *CI = cast<CallInst>(AssumeVH);
8136 if (!DT.dominates(CI, Latch->getTerminator()))
8137 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008138
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008139 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8140 return true;
8141 }
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008142
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008143 // If the loop is not reachable from the entry block, we risk running into an
8144 // infinite loop as we walk up into the dom tree. These loops do not matter
8145 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008146 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008147 return false;
8148
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008149 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8150 return true;
8151
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008152 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8153 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008154
8155 assert(DTN && "should reach the loop header before reaching the root!");
8156
8157 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008158 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8159 return true;
8160
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008161 BasicBlock *PBB = BB->getSinglePredecessor();
8162 if (!PBB)
8163 continue;
8164
8165 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8166 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8167 continue;
8168
8169 Value *Condition = ContinuePredicate->getCondition();
8170
8171 // If we have an edge `E` within the loop body that dominates the only
8172 // latch, the condition guarding `E` also guards the backedge. This
8173 // reasoning works only for loops with a single latch.
8174
8175 BasicBlockEdge DominatingEdge(PBB, BB);
8176 if (DominatingEdge.isSingleEdge()) {
8177 // We're constructively (and conservatively) enumerating edges within the
8178 // loop body that dominate the latch. The dominator tree better agree
8179 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008180 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008181
8182 if (isImpliedCond(Pred, LHS, RHS, Condition,
8183 BB != ContinuePredicate->getSuccessor(0)))
8184 return true;
8185 }
8186 }
8187
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008188 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008189}
8190
Dan Gohmane65c9172009-07-13 21:35:55 +00008191bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008192ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8193 ICmpInst::Predicate Pred,
8194 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008195 // Interpret a null as meaning no loop, where there is obviously no guard
8196 // (interprocedural conditions notwithstanding).
8197 if (!L) return false;
8198
Sanjoy Das401e6312016-02-01 20:48:10 +00008199 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8200 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008201
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008202 // Starting at the loop predecessor, climb up the predecessor chain, as long
8203 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008204 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008205 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008206 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008207 Pair.first;
8208 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008209
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008210 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8211 return true;
8212
Dan Gohman2a62fd92008-08-12 20:17:31 +00008213 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008214 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008215 if (!LoopEntryPredicate ||
8216 LoopEntryPredicate->isUnconditional())
8217 continue;
8218
Dan Gohmane18c2d62010-08-10 23:46:30 +00008219 if (isImpliedCond(Pred, LHS, RHS,
8220 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008221 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008222 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008223 }
8224
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008225 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008226 for (auto &AssumeVH : AC.assumptions()) {
8227 if (!AssumeVH)
8228 continue;
8229 auto *CI = cast<CallInst>(AssumeVH);
8230 if (!DT.dominates(CI, L->getHeader()))
8231 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008232
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008233 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8234 return true;
8235 }
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008236
Dan Gohman2a62fd92008-08-12 20:17:31 +00008237 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008238}
8239
Dan Gohmane18c2d62010-08-10 23:46:30 +00008240bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008241 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008242 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008243 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008244 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008245 return false;
8246
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008247 auto ClearOnExit =
8248 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8249
Dan Gohman8b0a4192010-03-01 17:49:51 +00008250 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008251 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008252 if (BO->getOpcode() == Instruction::And) {
8253 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008254 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8255 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008256 } else if (BO->getOpcode() == Instruction::Or) {
8257 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008258 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8259 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008260 }
8261 }
8262
Dan Gohmane18c2d62010-08-10 23:46:30 +00008263 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008264 if (!ICI) return false;
8265
Andrew Trickfa594032012-11-29 18:35:13 +00008266 // Now that we found a conditional branch that dominates the loop or controls
8267 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008268 ICmpInst::Predicate FoundPred;
8269 if (Inverse)
8270 FoundPred = ICI->getInversePredicate();
8271 else
8272 FoundPred = ICI->getPredicate();
8273
8274 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8275 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008276
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008277 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8278}
8279
8280bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8281 const SCEV *RHS,
8282 ICmpInst::Predicate FoundPred,
8283 const SCEV *FoundLHS,
8284 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008285 // Balance the types.
8286 if (getTypeSizeInBits(LHS->getType()) <
8287 getTypeSizeInBits(FoundLHS->getType())) {
8288 if (CmpInst::isSigned(Pred)) {
8289 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8290 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8291 } else {
8292 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8293 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8294 }
8295 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008296 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008297 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008298 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8299 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8300 } else {
8301 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8302 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8303 }
8304 }
8305
Dan Gohman430f0cc2009-07-21 23:03:19 +00008306 // Canonicalize the query to match the way instcombine will have
8307 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008308 if (SimplifyICmpOperands(Pred, LHS, RHS))
8309 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008310 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008311 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8312 if (FoundLHS == FoundRHS)
8313 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008314
8315 // Check to see if we can make the LHS or RHS match.
8316 if (LHS == FoundRHS || RHS == FoundLHS) {
8317 if (isa<SCEVConstant>(RHS)) {
8318 std::swap(FoundLHS, FoundRHS);
8319 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8320 } else {
8321 std::swap(LHS, RHS);
8322 Pred = ICmpInst::getSwappedPredicate(Pred);
8323 }
8324 }
8325
8326 // Check whether the found predicate is the same as the desired predicate.
8327 if (FoundPred == Pred)
8328 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8329
8330 // Check whether swapping the found predicate makes it the same as the
8331 // desired predicate.
8332 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8333 if (isa<SCEVConstant>(RHS))
8334 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8335 else
8336 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8337 RHS, LHS, FoundLHS, FoundRHS);
8338 }
8339
Sanjoy Das6e78b172015-10-22 19:57:34 +00008340 // Unsigned comparison is the same as signed comparison when both the operands
8341 // are non-negative.
8342 if (CmpInst::isUnsigned(FoundPred) &&
8343 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8344 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8345 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8346
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008347 // Check if we can make progress by sharpening ranges.
8348 if (FoundPred == ICmpInst::ICMP_NE &&
8349 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8350
8351 const SCEVConstant *C = nullptr;
8352 const SCEV *V = nullptr;
8353
8354 if (isa<SCEVConstant>(FoundLHS)) {
8355 C = cast<SCEVConstant>(FoundLHS);
8356 V = FoundRHS;
8357 } else {
8358 C = cast<SCEVConstant>(FoundRHS);
8359 V = FoundLHS;
8360 }
8361
8362 // The guarding predicate tells us that C != V. If the known range
8363 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8364 // range we consider has to correspond to same signedness as the
8365 // predicate we're interested in folding.
8366
8367 APInt Min = ICmpInst::isSigned(Pred) ?
8368 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8369
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008370 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008371 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8372 // This is true even if (Min + 1) wraps around -- in case of
8373 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8374
8375 APInt SharperMin = Min + 1;
8376
8377 switch (Pred) {
8378 case ICmpInst::ICMP_SGE:
8379 case ICmpInst::ICMP_UGE:
8380 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8381 // RHS, we're done.
8382 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8383 getConstant(SharperMin)))
8384 return true;
8385
8386 case ICmpInst::ICMP_SGT:
8387 case ICmpInst::ICMP_UGT:
8388 // We know from the range information that (V `Pred` Min ||
8389 // V == Min). We know from the guarding condition that !(V
8390 // == Min). This gives us
8391 //
8392 // V `Pred` Min || V == Min && !(V == Min)
8393 // => V `Pred` Min
8394 //
8395 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8396
8397 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8398 return true;
8399
8400 default:
8401 // No change
8402 break;
8403 }
8404 }
8405 }
8406
Dan Gohman430f0cc2009-07-21 23:03:19 +00008407 // Check whether the actual condition is beyond sufficient.
8408 if (FoundPred == ICmpInst::ICMP_EQ)
8409 if (ICmpInst::isTrueWhenEqual(Pred))
8410 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8411 return true;
8412 if (Pred == ICmpInst::ICMP_NE)
8413 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8414 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8415 return true;
8416
8417 // Otherwise assume the worst.
8418 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008419}
8420
Sanjoy Das1ed69102015-10-13 02:53:27 +00008421bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8422 const SCEV *&L, const SCEV *&R,
8423 SCEV::NoWrapFlags &Flags) {
8424 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8425 if (!AE || AE->getNumOperands() != 2)
8426 return false;
8427
8428 L = AE->getOperand(0);
8429 R = AE->getOperand(1);
8430 Flags = AE->getNoWrapFlags();
8431 return true;
8432}
8433
Sanjoy Das0b1af852016-07-23 00:28:56 +00008434Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8435 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008436 // We avoid subtracting expressions here because this function is usually
8437 // fairly deep in the call stack (i.e. is called many times).
8438
Sanjoy Das96709c42015-09-25 23:53:45 +00008439 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8440 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8441 const auto *MAR = cast<SCEVAddRecExpr>(More);
8442
8443 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008444 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008445
8446 // We look at affine expressions only; not for correctness but to keep
8447 // getStepRecurrence cheap.
8448 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008449 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008450
Sanjoy Das1ed69102015-10-13 02:53:27 +00008451 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008452 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008453
8454 Less = LAR->getStart();
8455 More = MAR->getStart();
8456
8457 // fall through
8458 }
8459
8460 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008461 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8462 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008463 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008464 }
8465
8466 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008467 SCEV::NoWrapFlags Flags;
8468 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008469 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008470 if (R == More)
8471 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008472
Sanjoy Das1ed69102015-10-13 02:53:27 +00008473 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008474 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008475 if (R == Less)
8476 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008477
Sanjoy Das0b1af852016-07-23 00:28:56 +00008478 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008479}
8480
8481bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8482 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8483 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8484 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8485 return false;
8486
8487 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8488 if (!AddRecLHS)
8489 return false;
8490
8491 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8492 if (!AddRecFoundLHS)
8493 return false;
8494
8495 // We'd like to let SCEV reason about control dependencies, so we constrain
8496 // both the inequalities to be about add recurrences on the same loop. This
8497 // way we can use isLoopEntryGuardedByCond later.
8498
8499 const Loop *L = AddRecFoundLHS->getLoop();
8500 if (L != AddRecLHS->getLoop())
8501 return false;
8502
8503 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8504 //
8505 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8506 // ... (2)
8507 //
8508 // Informal proof for (2), assuming (1) [*]:
8509 //
8510 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8511 //
8512 // Then
8513 //
8514 // FoundLHS s< FoundRHS s< INT_MIN - C
8515 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8516 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8517 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8518 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8519 // <=> FoundLHS + C s< FoundRHS + C
8520 //
8521 // [*]: (1) can be proved by ruling out overflow.
8522 //
8523 // [**]: This can be proved by analyzing all the four possibilities:
8524 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8525 // (A s>= 0, B s>= 0).
8526 //
8527 // Note:
8528 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8529 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8530 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8531 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8532 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8533 // C)".
8534
Sanjoy Das0b1af852016-07-23 00:28:56 +00008535 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8536 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8537 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008538 return false;
8539
Sanjoy Das0b1af852016-07-23 00:28:56 +00008540 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008541 return true;
8542
Sanjoy Das96709c42015-09-25 23:53:45 +00008543 APInt FoundRHSLimit;
8544
8545 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008546 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008547 } else {
8548 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008549 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008550 }
8551
8552 // Try to prove (1) or (2), as needed.
8553 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8554 getConstant(FoundRHSLimit));
8555}
8556
Dan Gohman430f0cc2009-07-21 23:03:19 +00008557bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8558 const SCEV *LHS, const SCEV *RHS,
8559 const SCEV *FoundLHS,
8560 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008561 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8562 return true;
8563
Sanjoy Das96709c42015-09-25 23:53:45 +00008564 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8565 return true;
8566
Dan Gohman430f0cc2009-07-21 23:03:19 +00008567 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8568 FoundLHS, FoundRHS) ||
8569 // ~x < ~y --> x > y
8570 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8571 getNotSCEV(FoundRHS),
8572 getNotSCEV(FoundLHS));
8573}
8574
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008575
8576/// If Expr computes ~A, return A else return nullptr
8577static const SCEV *MatchNotExpr(const SCEV *Expr) {
8578 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008579 if (!Add || Add->getNumOperands() != 2 ||
8580 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008581 return nullptr;
8582
8583 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008584 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8585 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008586 return nullptr;
8587
8588 return AddRHS->getOperand(1);
8589}
8590
8591
8592/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8593template<typename MaxExprType>
8594static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8595 const SCEV *Candidate) {
8596 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8597 if (!MaxExpr) return false;
8598
Sanjoy Das347d2722015-12-01 07:49:27 +00008599 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008600}
8601
8602
8603/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8604template<typename MaxExprType>
8605static bool IsMinConsistingOf(ScalarEvolution &SE,
8606 const SCEV *MaybeMinExpr,
8607 const SCEV *Candidate) {
8608 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8609 if (!MaybeMaxExpr)
8610 return false;
8611
8612 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8613}
8614
Hal Finkela8d205f2015-08-19 01:51:51 +00008615static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8616 ICmpInst::Predicate Pred,
8617 const SCEV *LHS, const SCEV *RHS) {
8618
8619 // If both sides are affine addrecs for the same loop, with equal
8620 // steps, and we know the recurrences don't wrap, then we only
8621 // need to check the predicate on the starting values.
8622
8623 if (!ICmpInst::isRelational(Pred))
8624 return false;
8625
8626 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8627 if (!LAR)
8628 return false;
8629 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8630 if (!RAR)
8631 return false;
8632 if (LAR->getLoop() != RAR->getLoop())
8633 return false;
8634 if (!LAR->isAffine() || !RAR->isAffine())
8635 return false;
8636
8637 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8638 return false;
8639
Hal Finkelff08a2e2015-08-19 17:26:07 +00008640 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8641 SCEV::FlagNSW : SCEV::FlagNUW;
8642 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008643 return false;
8644
8645 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8646}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008647
8648/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8649/// expression?
8650static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8651 ICmpInst::Predicate Pred,
8652 const SCEV *LHS, const SCEV *RHS) {
8653 switch (Pred) {
8654 default:
8655 return false;
8656
8657 case ICmpInst::ICMP_SGE:
8658 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008659 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008660 case ICmpInst::ICMP_SLE:
8661 return
8662 // min(A, ...) <= A
8663 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8664 // A <= max(A, ...)
8665 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8666
8667 case ICmpInst::ICMP_UGE:
8668 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008669 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008670 case ICmpInst::ICMP_ULE:
8671 return
8672 // min(A, ...) <= A
8673 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8674 // A <= max(A, ...)
8675 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8676 }
8677
8678 llvm_unreachable("covered switch fell through?!");
8679}
8680
Max Kazantsev2e44d292017-03-31 12:05:30 +00008681bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8682 const SCEV *LHS, const SCEV *RHS,
8683 const SCEV *FoundLHS,
8684 const SCEV *FoundRHS,
8685 unsigned Depth) {
8686 assert(getTypeSizeInBits(LHS->getType()) ==
8687 getTypeSizeInBits(RHS->getType()) &&
8688 "LHS and RHS have different sizes?");
8689 assert(getTypeSizeInBits(FoundLHS->getType()) ==
8690 getTypeSizeInBits(FoundRHS->getType()) &&
8691 "FoundLHS and FoundRHS have different sizes?");
8692 // We want to avoid hurting the compile time with analysis of too big trees.
8693 if (Depth > MaxSCEVOperationsImplicationDepth)
8694 return false;
8695 // We only want to work with ICMP_SGT comparison so far.
8696 // TODO: Extend to ICMP_UGT?
8697 if (Pred == ICmpInst::ICMP_SLT) {
8698 Pred = ICmpInst::ICMP_SGT;
8699 std::swap(LHS, RHS);
8700 std::swap(FoundLHS, FoundRHS);
8701 }
8702 if (Pred != ICmpInst::ICMP_SGT)
8703 return false;
8704
8705 auto GetOpFromSExt = [&](const SCEV *S) {
8706 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8707 return Ext->getOperand();
8708 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8709 // the constant in some cases.
8710 return S;
8711 };
8712
8713 // Acquire values from extensions.
8714 auto *OrigFoundLHS = FoundLHS;
8715 LHS = GetOpFromSExt(LHS);
8716 FoundLHS = GetOpFromSExt(FoundLHS);
8717
8718 // Is the SGT predicate can be proved trivially or using the found context.
8719 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8720 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8721 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8722 FoundRHS, Depth + 1);
8723 };
8724
8725 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8726 // We want to avoid creation of any new non-constant SCEV. Since we are
8727 // going to compare the operands to RHS, we should be certain that we don't
8728 // need any size extensions for this. So let's decline all cases when the
8729 // sizes of types of LHS and RHS do not match.
8730 // TODO: Maybe try to get RHS from sext to catch more cases?
8731 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8732 return false;
8733
8734 // Should not overflow.
8735 if (!LHSAddExpr->hasNoSignedWrap())
8736 return false;
8737
8738 auto *LL = LHSAddExpr->getOperand(0);
8739 auto *LR = LHSAddExpr->getOperand(1);
8740 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8741
8742 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8743 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8744 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8745 };
8746 // Try to prove the following rule:
8747 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8748 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8749 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8750 return true;
8751 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8752 Value *LL, *LR;
8753 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8754 using namespace llvm::PatternMatch;
8755 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8756 // Rules for division.
8757 // We are going to perform some comparisons with Denominator and its
8758 // derivative expressions. In general case, creating a SCEV for it may
8759 // lead to a complex analysis of the entire graph, and in particular it
8760 // can request trip count recalculation for the same loop. This would
8761 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8762 // this, we only want to create SCEVs that are constants in this section.
8763 // So we bail if Denominator is not a constant.
8764 if (!isa<ConstantInt>(LR))
8765 return false;
8766
8767 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8768
8769 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8770 // then a SCEV for the numerator already exists and matches with FoundLHS.
8771 auto *Numerator = getExistingSCEV(LL);
8772 if (!Numerator || Numerator->getType() != FoundLHS->getType())
8773 return false;
8774
8775 // Make sure that the numerator matches with FoundLHS and the denominator
8776 // is positive.
8777 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8778 return false;
8779
8780 auto *DTy = Denominator->getType();
8781 auto *FRHSTy = FoundRHS->getType();
8782 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8783 // One of types is a pointer and another one is not. We cannot extend
8784 // them properly to a wider type, so let us just reject this case.
8785 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8786 // to avoid this check.
8787 return false;
8788
8789 // Given that:
8790 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8791 auto *WTy = getWiderType(DTy, FRHSTy);
8792 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8793 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8794
8795 // Try to prove the following rule:
8796 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8797 // For example, given that FoundLHS > 2. It means that FoundLHS is at
8798 // least 3. If we divide it by Denominator < 4, we will have at least 1.
8799 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8800 if (isKnownNonPositive(RHS) &&
8801 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8802 return true;
8803
8804 // Try to prove the following rule:
8805 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8806 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8807 // If we divide it by Denominator > 2, then:
8808 // 1. If FoundLHS is negative, then the result is 0.
8809 // 2. If FoundLHS is non-negative, then the result is non-negative.
8810 // Anyways, the result is non-negative.
8811 auto *MinusOne = getNegativeSCEV(getOne(WTy));
8812 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8813 if (isKnownNegative(RHS) &&
8814 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8815 return true;
8816 }
8817 }
8818
8819 return false;
8820}
8821
8822bool
8823ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8824 const SCEV *LHS, const SCEV *RHS) {
8825 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8826 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8827 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8828 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8829}
8830
Dan Gohmane65c9172009-07-13 21:35:55 +00008831bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008832ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8833 const SCEV *LHS, const SCEV *RHS,
8834 const SCEV *FoundLHS,
8835 const SCEV *FoundRHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008836 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008837 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8838 case ICmpInst::ICMP_EQ:
8839 case ICmpInst::ICMP_NE:
8840 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8841 return true;
8842 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008843 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008844 case ICmpInst::ICMP_SLE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008845 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8846 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008847 return true;
8848 break;
8849 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008850 case ICmpInst::ICMP_SGE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008851 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8852 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008853 return true;
8854 break;
8855 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008856 case ICmpInst::ICMP_ULE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008857 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8858 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008859 return true;
8860 break;
8861 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008862 case ICmpInst::ICMP_UGE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008863 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8864 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008865 return true;
8866 break;
8867 }
8868
Max Kazantsev2e44d292017-03-31 12:05:30 +00008869 // Maybe it can be proved via operations?
8870 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8871 return true;
8872
Dan Gohmane65c9172009-07-13 21:35:55 +00008873 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008874}
8875
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008876bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8877 const SCEV *LHS,
8878 const SCEV *RHS,
8879 const SCEV *FoundLHS,
8880 const SCEV *FoundRHS) {
8881 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8882 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8883 // reduce the compile time impact of this optimization.
8884 return false;
8885
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008886 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008887 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008888 return false;
8889
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008890 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008891
8892 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8893 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8894 ConstantRange FoundLHSRange =
8895 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8896
Sanjoy Das095f5b22016-07-22 20:47:55 +00008897 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8898 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008899
8900 // We can also compute the range of values for `LHS` that satisfy the
8901 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008902 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008903 ConstantRange SatisfyingLHSRange =
8904 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8905
8906 // The antecedent implies the consequent if every value of `LHS` that
8907 // satisfies the antecedent also satisfies the consequent.
8908 return SatisfyingLHSRange.contains(LHSRange);
8909}
8910
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008911bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8912 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008913 assert(isKnownPositive(Stride) && "Positive stride expected!");
8914
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008915 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008916
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008917 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008918 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008919
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008920 if (IsSigned) {
8921 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8922 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8923 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8924 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008925
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008926 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8927 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008928 }
Dan Gohman01048422009-06-21 23:46:38 +00008929
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008930 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8931 APInt MaxValue = APInt::getMaxValue(BitWidth);
8932 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8933 .getUnsignedMax();
8934
8935 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8936 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8937}
8938
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008939bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8940 bool IsSigned, bool NoWrap) {
8941 if (NoWrap) return false;
8942
8943 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008944 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008945
8946 if (IsSigned) {
8947 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8948 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8949 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8950 .getSignedMax();
8951
8952 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8953 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8954 }
8955
8956 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8957 APInt MinValue = APInt::getMinValue(BitWidth);
8958 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8959 .getUnsignedMax();
8960
8961 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8962 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8963}
8964
Johannes Doerfert2683e562015-02-09 12:34:23 +00008965const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008966 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008967 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008968 Delta = Equality ? getAddExpr(Delta, Step)
8969 : getAddExpr(Delta, getMinusSCEV(Step, One));
8970 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008971}
8972
Andrew Trick3ca3f982011-07-26 17:19:55 +00008973ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008974ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008975 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008976 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008977 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008978 // We handle only IV < Invariant
8979 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008980 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008981
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008982 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008983 bool PredicatedIV = false;
8984
8985 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008986 // Try to make this an AddRec using runtime tests, in the first X
8987 // iterations of this loop, where X is the SCEV expression found by the
8988 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008989 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008990 PredicatedIV = true;
8991 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008992
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008993 // Avoid weird loops
8994 if (!IV || IV->getLoop() != L || !IV->isAffine())
8995 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008996
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008997 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008998 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008999
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009000 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00009001
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009002 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00009003
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009004 // Avoid negative or zero stride values.
9005 if (!PositiveStride) {
9006 // We can compute the correct backedge taken count for loops with unknown
9007 // strides if we can prove that the loop is not an infinite loop with side
9008 // effects. Here's the loop structure we are trying to handle -
9009 //
9010 // i = start
9011 // do {
9012 // A[i] = i;
9013 // i += s;
9014 // } while (i < end);
9015 //
9016 // The backedge taken count for such loops is evaluated as -
9017 // (max(end, start + stride) - start - 1) /u stride
9018 //
9019 // The additional preconditions that we need to check to prove correctness
9020 // of the above formula is as follows -
9021 //
9022 // a) IV is either nuw or nsw depending upon signedness (indicated by the
9023 // NoWrap flag).
9024 // b) loop is single exit with no side effects.
9025 //
9026 //
9027 // Precondition a) implies that if the stride is negative, this is a single
9028 // trip loop. The backedge taken count formula reduces to zero in this case.
9029 //
9030 // Precondition b) implies that the unknown stride cannot be zero otherwise
9031 // we have UB.
9032 //
9033 // The positive stride case is the same as isKnownPositive(Stride) returning
9034 // true (original behavior of the function).
9035 //
9036 // We want to make sure that the stride is truly unknown as there are edge
9037 // cases where ScalarEvolution propagates no wrap flags to the
9038 // post-increment/decrement IV even though the increment/decrement operation
9039 // itself is wrapping. The computed backedge taken count may be wrong in
9040 // such cases. This is prevented by checking that the stride is not known to
9041 // be either positive or non-positive. For example, no wrap flags are
9042 // propagated to the post-increment IV of this loop with a trip count of 2 -
9043 //
9044 // unsigned char i;
9045 // for(i=127; i<128; i+=129)
9046 // A[i] = i;
9047 //
9048 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9049 !loopHasNoSideEffects(L))
9050 return getCouldNotCompute();
9051
9052 } else if (!Stride->isOne() &&
9053 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9054 // Avoid proven overflow cases: this will ensure that the backedge taken
9055 // count will not generate any unsigned overflow. Relaxed no-overflow
9056 // conditions exploit NoWrapFlags, allowing to optimize in presence of
9057 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009058 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00009059
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009060 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9061 : ICmpInst::ICMP_ULT;
9062 const SCEV *Start = IV->getStart();
9063 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00009064 // If the backedge is taken at least once, then it will be taken
9065 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9066 // is the LHS value of the less-than comparison the first time it is evaluated
9067 // and End is the RHS.
9068 const SCEV *BECountIfBackedgeTaken =
9069 computeBECount(getMinusSCEV(End, Start), Stride, false);
9070 // If the loop entry is guarded by the result of the backedge test of the
9071 // first loop iteration, then we know the backedge will be taken at least
9072 // once and so the backedge taken count is as above. If not then we use the
9073 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9074 // as if the backedge is taken at least once max(End,Start) is End and so the
9075 // result is as above, and if not max(End,Start) is Start so we get a backedge
9076 // count of zero.
9077 const SCEV *BECount;
9078 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9079 BECount = BECountIfBackedgeTaken;
9080 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00009081 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00009082 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9083 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009084
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00009085 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00009086 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009087 if (isa<SCEVConstant>(BECount))
9088 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00009089 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00009090 // If we know exactly how many times the backedge will be taken if it's
9091 // taken at least once, then the backedge count will either be that or
9092 // zero.
9093 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00009094 MaxOrZero = true;
9095 } else {
John Brawnecf79302016-10-18 10:10:53 +00009096 // Calculate the maximum backedge count based on the range of values
9097 // permitted by Start, End, and Stride.
9098 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
9099 : getUnsignedRange(Start).getUnsignedMin();
9100
9101 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9102
9103 APInt StrideForMaxBECount;
9104
9105 if (PositiveStride)
9106 StrideForMaxBECount =
9107 IsSigned ? getSignedRange(Stride).getSignedMin()
9108 : getUnsignedRange(Stride).getUnsignedMin();
9109 else
9110 // Using a stride of 1 is safe when computing max backedge taken count for
9111 // a loop with unknown stride.
9112 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9113
9114 APInt Limit =
9115 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9116 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9117
9118 // Although End can be a MAX expression we estimate MaxEnd considering only
9119 // the case End = RHS. This is safe because in the other case (End - Start)
9120 // is zero, leading to a zero maximum backedge taken count.
9121 APInt MaxEnd =
9122 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9123 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9124
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009125 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009126 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00009127 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009128
9129 if (isa<SCEVCouldNotCompute>(MaxBECount))
9130 MaxBECount = BECount;
9131
John Brawn84b21832016-10-21 11:08:48 +00009132 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009133}
9134
9135ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00009136ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009137 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00009138 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00009139 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009140 // We handle only IV > Invariant
9141 if (!isLoopInvariant(RHS, L))
9142 return getCouldNotCompute();
9143
9144 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00009145 if (!IV && AllowPredicates)
9146 // Try to make this an AddRec using runtime tests, in the first X
9147 // iterations of this loop, where X is the SCEV expression found by the
9148 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00009149 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009150
9151 // Avoid weird loops
9152 if (!IV || IV->getLoop() != L || !IV->isAffine())
9153 return getCouldNotCompute();
9154
Mark Heffernan2beab5f2014-10-10 17:39:11 +00009155 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009156 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9157
9158 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9159
9160 // Avoid negative or zero stride values
9161 if (!isKnownPositive(Stride))
9162 return getCouldNotCompute();
9163
9164 // Avoid proven overflow cases: this will ensure that the backedge taken count
9165 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00009166 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009167 // behaviors like the case of C language.
9168 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9169 return getCouldNotCompute();
9170
9171 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9172 : ICmpInst::ICMP_UGT;
9173
9174 const SCEV *Start = IV->getStart();
9175 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00009176 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9177 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009178
9179 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9180
9181 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9182 : getUnsignedRange(Start).getUnsignedMax();
9183
9184 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9185 : getUnsignedRange(Stride).getUnsignedMin();
9186
9187 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9188 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9189 : APInt::getMinValue(BitWidth) + (MinStride - 1);
9190
9191 // Although End can be a MIN expression we estimate MinEnd considering only
9192 // the case End = RHS. This is safe because in the other case (Start - End)
9193 // is zero, leading to a zero maximum backedge taken count.
9194 APInt MinEnd =
9195 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9196 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9197
9198
9199 const SCEV *MaxBECount = getCouldNotCompute();
9200 if (isa<SCEVConstant>(BECount))
9201 MaxBECount = BECount;
9202 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00009203 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009204 getConstant(MinStride), false);
9205
9206 if (isa<SCEVCouldNotCompute>(MaxBECount))
9207 MaxBECount = BECount;
9208
John Brawn84b21832016-10-21 11:08:48 +00009209 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00009210}
9211
Benjamin Kramerc321e532016-06-08 19:09:22 +00009212const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00009213 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00009214 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00009215 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009216
9217 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00009218 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00009219 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00009220 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009221 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00009222 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00009223 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00009224 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00009225 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009226 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00009227 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00009228 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009229 }
9230
9231 // The only time we can solve this is when we have all constant indices.
9232 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00009233 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00009234 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009235
9236 // Okay at this point we know that all elements of the chrec are constants and
9237 // that the start element is zero.
9238
9239 // First check to see if the range contains zero. If not, the first
9240 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00009241 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00009242 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009243 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00009244
Chris Lattnerd934c702004-04-02 20:23:17 +00009245 if (isAffine()) {
9246 // If this is an affine expression then we have this situation:
9247 // Solve {0,+,A} in Range === Ax in Range
9248
Nick Lewycky52460262007-07-16 02:08:00 +00009249 // We know that zero is in the range. If A is positive then we know that
9250 // the upper value of the range must be the first possible exit value.
9251 // If A is negative then the lower of the range is the last possible loop
9252 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00009253 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009254 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00009255 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00009256
Nick Lewycky52460262007-07-16 02:08:00 +00009257 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00009258 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00009259 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00009260
9261 // Evaluate at the exit value. If we really did fall out of the valid
9262 // range, then we computed our trip count, otherwise wrap around or other
9263 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00009264 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009265 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00009266 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009267
9268 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00009269 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00009270 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00009271 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00009272 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00009273 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00009274 } else if (isQuadratic()) {
9275 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9276 // quadratic equation to solve it. To do this, we must frame our problem in
9277 // terms of figuring out when zero is crossed, instead of when
9278 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00009279 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00009280 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00009281 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00009282
9283 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00009284 if (auto Roots =
9285 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00009286 const SCEVConstant *R1 = Roots->first;
9287 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00009288 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00009289 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9290 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00009291 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00009292 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00009293
Chris Lattnerd934c702004-04-02 20:23:17 +00009294 // Make sure the root is not off by one. The returned iteration should
9295 // not be in the range, but the previous one should be. When solving
9296 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00009297 ConstantInt *R1Val =
9298 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009299 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009300 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00009301 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009302 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00009303
Dan Gohmana37eaf22007-10-22 18:31:58 +00009304 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009305 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00009306 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00009307 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009308 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009309
Chris Lattnerd934c702004-04-02 20:23:17 +00009310 // If R1 was not in the range, then it is a good return value. Make
9311 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00009312 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009313 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00009314 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009315 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00009316 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00009317 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009318 }
9319 }
9320 }
9321
Dan Gohman31efa302009-04-18 17:58:19 +00009322 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009323}
9324
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009325// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009326static inline bool containsUndefs(const SCEV *S) {
9327 return SCEVExprContains(S, [](const SCEV *S) {
9328 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9329 return isa<UndefValue>(SU->getValue());
9330 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9331 return isa<UndefValue>(SC->getValue());
9332 return false;
9333 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009334}
9335
9336namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009337// Collect all steps of SCEV expressions.
9338struct SCEVCollectStrides {
9339 ScalarEvolution &SE;
9340 SmallVectorImpl<const SCEV *> &Strides;
9341
9342 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9343 : SE(SE), Strides(S) {}
9344
9345 bool follow(const SCEV *S) {
9346 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9347 Strides.push_back(AR->getStepRecurrence(SE));
9348 return true;
9349 }
9350 bool isDone() const { return false; }
9351};
9352
9353// Collect all SCEVUnknown and SCEVMulExpr expressions.
9354struct SCEVCollectTerms {
9355 SmallVectorImpl<const SCEV *> &Terms;
9356
9357 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9358 : Terms(T) {}
9359
9360 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009361 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9362 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009363 if (!containsUndefs(S))
9364 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009365
9366 // Stop recursion: once we collected a term, do not walk its operands.
9367 return false;
9368 }
9369
9370 // Keep looking.
9371 return true;
9372 }
9373 bool isDone() const { return false; }
9374};
Tobias Grosser374bce02015-10-12 08:02:00 +00009375
9376// Check if a SCEV contains an AddRecExpr.
9377struct SCEVHasAddRec {
9378 bool &ContainsAddRec;
9379
9380 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9381 ContainsAddRec = false;
9382 }
9383
9384 bool follow(const SCEV *S) {
9385 if (isa<SCEVAddRecExpr>(S)) {
9386 ContainsAddRec = true;
9387
9388 // Stop recursion: once we collected a term, do not walk its operands.
9389 return false;
9390 }
9391
9392 // Keep looking.
9393 return true;
9394 }
9395 bool isDone() const { return false; }
9396};
9397
9398// Find factors that are multiplied with an expression that (possibly as a
9399// subexpression) contains an AddRecExpr. In the expression:
9400//
9401// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9402//
9403// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9404// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9405// parameters as they form a product with an induction variable.
9406//
9407// This collector expects all array size parameters to be in the same MulExpr.
9408// It might be necessary to later add support for collecting parameters that are
9409// spread over different nested MulExpr.
9410struct SCEVCollectAddRecMultiplies {
9411 SmallVectorImpl<const SCEV *> &Terms;
9412 ScalarEvolution &SE;
9413
9414 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9415 : Terms(T), SE(SE) {}
9416
9417 bool follow(const SCEV *S) {
9418 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9419 bool HasAddRec = false;
9420 SmallVector<const SCEV *, 0> Operands;
9421 for (auto Op : Mul->operands()) {
9422 if (isa<SCEVUnknown>(Op)) {
9423 Operands.push_back(Op);
9424 } else {
9425 bool ContainsAddRec;
9426 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9427 visitAll(Op, ContiansAddRec);
9428 HasAddRec |= ContainsAddRec;
9429 }
9430 }
9431 if (Operands.size() == 0)
9432 return true;
9433
9434 if (!HasAddRec)
9435 return false;
9436
9437 Terms.push_back(SE.getMulExpr(Operands));
9438 // Stop recursion: once we collected a term, do not walk its operands.
9439 return false;
9440 }
9441
9442 // Keep looking.
9443 return true;
9444 }
9445 bool isDone() const { return false; }
9446};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009447}
Sebastian Pop448712b2014-05-07 18:01:20 +00009448
Tobias Grosser374bce02015-10-12 08:02:00 +00009449/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9450/// two places:
9451/// 1) The strides of AddRec expressions.
9452/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009453void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9454 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009455 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009456 SCEVCollectStrides StrideCollector(*this, Strides);
9457 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009458
9459 DEBUG({
9460 dbgs() << "Strides:\n";
9461 for (const SCEV *S : Strides)
9462 dbgs() << *S << "\n";
9463 });
9464
9465 for (const SCEV *S : Strides) {
9466 SCEVCollectTerms TermCollector(Terms);
9467 visitAll(S, TermCollector);
9468 }
9469
9470 DEBUG({
9471 dbgs() << "Terms:\n";
9472 for (const SCEV *T : Terms)
9473 dbgs() << *T << "\n";
9474 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009475
9476 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9477 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009478}
9479
Sebastian Popb1a548f2014-05-12 19:01:53 +00009480static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009481 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009482 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009483 int Last = Terms.size() - 1;
9484 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009485
Sebastian Pop448712b2014-05-07 18:01:20 +00009486 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009487 if (Last == 0) {
9488 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009489 SmallVector<const SCEV *, 2> Qs;
9490 for (const SCEV *Op : M->operands())
9491 if (!isa<SCEVConstant>(Op))
9492 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009493
Sebastian Pope30bd352014-05-27 22:41:56 +00009494 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009495 }
9496
Sebastian Pope30bd352014-05-27 22:41:56 +00009497 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009498 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009499 }
9500
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009501 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009502 // Normalize the terms before the next call to findArrayDimensionsRec.
9503 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009504 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009505
9506 // Bail out when GCD does not evenly divide one of the terms.
9507 if (!R->isZero())
9508 return false;
9509
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009510 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009511 }
9512
Tobias Grosser3080cf12014-05-08 07:55:34 +00009513 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009514 Terms.erase(
9515 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9516 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009517
Sebastian Pop448712b2014-05-07 18:01:20 +00009518 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009519 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9520 return false;
9521
Sebastian Pope30bd352014-05-27 22:41:56 +00009522 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009523 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009524}
Sebastian Popc62c6792013-11-12 22:47:20 +00009525
Sebastian Pop448712b2014-05-07 18:01:20 +00009526
9527// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009528static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009529 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009530 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009531 return true;
9532 return false;
9533}
9534
9535// Return the number of product terms in S.
9536static inline int numberOfTerms(const SCEV *S) {
9537 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9538 return Expr->getNumOperands();
9539 return 1;
9540}
9541
Sebastian Popa6e58602014-05-27 22:41:45 +00009542static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9543 if (isa<SCEVConstant>(T))
9544 return nullptr;
9545
9546 if (isa<SCEVUnknown>(T))
9547 return T;
9548
9549 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9550 SmallVector<const SCEV *, 2> Factors;
9551 for (const SCEV *Op : M->operands())
9552 if (!isa<SCEVConstant>(Op))
9553 Factors.push_back(Op);
9554
9555 return SE.getMulExpr(Factors);
9556 }
9557
9558 return T;
9559}
9560
9561/// Return the size of an element read or written by Inst.
9562const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9563 Type *Ty;
9564 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9565 Ty = Store->getValueOperand()->getType();
9566 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009567 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009568 else
9569 return nullptr;
9570
9571 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9572 return getSizeOfExpr(ETy, Ty);
9573}
9574
Sebastian Popa6e58602014-05-27 22:41:45 +00009575void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9576 SmallVectorImpl<const SCEV *> &Sizes,
9577 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009578 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009579 return;
9580
9581 // Early return when Terms do not contain parameters: we do not delinearize
9582 // non parametric SCEVs.
9583 if (!containsParameters(Terms))
9584 return;
9585
9586 DEBUG({
9587 dbgs() << "Terms:\n";
9588 for (const SCEV *T : Terms)
9589 dbgs() << *T << "\n";
9590 });
9591
9592 // Remove duplicates.
9593 std::sort(Terms.begin(), Terms.end());
9594 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9595
9596 // Put larger terms first.
9597 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9598 return numberOfTerms(LHS) > numberOfTerms(RHS);
9599 });
9600
Sebastian Popa6e58602014-05-27 22:41:45 +00009601 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9602
Tobias Grosser374bce02015-10-12 08:02:00 +00009603 // Try to divide all terms by the element size. If term is not divisible by
9604 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009605 for (const SCEV *&Term : Terms) {
9606 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009607 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009608 if (!Q->isZero())
9609 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009610 }
9611
9612 SmallVector<const SCEV *, 4> NewTerms;
9613
9614 // Remove constant factors.
9615 for (const SCEV *T : Terms)
9616 if (const SCEV *NewT = removeConstantFactors(SE, T))
9617 NewTerms.push_back(NewT);
9618
Sebastian Pop448712b2014-05-07 18:01:20 +00009619 DEBUG({
9620 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009621 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009622 dbgs() << *T << "\n";
9623 });
9624
Sebastian Popa6e58602014-05-27 22:41:45 +00009625 if (NewTerms.empty() ||
9626 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009627 Sizes.clear();
9628 return;
9629 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009630
Sebastian Popa6e58602014-05-27 22:41:45 +00009631 // The last element to be pushed into Sizes is the size of an element.
9632 Sizes.push_back(ElementSize);
9633
Sebastian Pop448712b2014-05-07 18:01:20 +00009634 DEBUG({
9635 dbgs() << "Sizes:\n";
9636 for (const SCEV *S : Sizes)
9637 dbgs() << *S << "\n";
9638 });
9639}
9640
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009641void ScalarEvolution::computeAccessFunctions(
9642 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9643 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009644
Sebastian Popb1a548f2014-05-12 19:01:53 +00009645 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009646 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009647 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009648
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009649 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009650 if (!AR->isAffine())
9651 return;
9652
9653 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009654 int Last = Sizes.size() - 1;
9655 for (int i = Last; i >= 0; i--) {
9656 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009657 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009658
9659 DEBUG({
9660 dbgs() << "Res: " << *Res << "\n";
9661 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9662 dbgs() << "Res divided by Sizes[i]:\n";
9663 dbgs() << "Quotient: " << *Q << "\n";
9664 dbgs() << "Remainder: " << *R << "\n";
9665 });
9666
9667 Res = Q;
9668
Sebastian Popa6e58602014-05-27 22:41:45 +00009669 // Do not record the last subscript corresponding to the size of elements in
9670 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009671 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009672
9673 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009674 if (isa<SCEVAddRecExpr>(R)) {
9675 Subscripts.clear();
9676 Sizes.clear();
9677 return;
9678 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009679
Sebastian Pop448712b2014-05-07 18:01:20 +00009680 continue;
9681 }
9682
9683 // Record the access function for the current subscript.
9684 Subscripts.push_back(R);
9685 }
9686
9687 // Also push in last position the remainder of the last division: it will be
9688 // the access function of the innermost dimension.
9689 Subscripts.push_back(Res);
9690
9691 std::reverse(Subscripts.begin(), Subscripts.end());
9692
9693 DEBUG({
9694 dbgs() << "Subscripts:\n";
9695 for (const SCEV *S : Subscripts)
9696 dbgs() << *S << "\n";
9697 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009698}
9699
Sebastian Popc62c6792013-11-12 22:47:20 +00009700/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9701/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009702/// is the offset start of the array. The SCEV->delinearize algorithm computes
9703/// the multiples of SCEV coefficients: that is a pattern matching of sub
9704/// expressions in the stride and base of a SCEV corresponding to the
9705/// computation of a GCD (greatest common divisor) of base and stride. When
9706/// SCEV->delinearize fails, it returns the SCEV unchanged.
9707///
9708/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9709///
9710/// void foo(long n, long m, long o, double A[n][m][o]) {
9711///
9712/// for (long i = 0; i < n; i++)
9713/// for (long j = 0; j < m; j++)
9714/// for (long k = 0; k < o; k++)
9715/// A[i][j][k] = 1.0;
9716/// }
9717///
9718/// the delinearization input is the following AddRec SCEV:
9719///
9720/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9721///
9722/// From this SCEV, we are able to say that the base offset of the access is %A
9723/// because it appears as an offset that does not divide any of the strides in
9724/// the loops:
9725///
9726/// CHECK: Base offset: %A
9727///
9728/// and then SCEV->delinearize determines the size of some of the dimensions of
9729/// the array as these are the multiples by which the strides are happening:
9730///
9731/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9732///
9733/// Note that the outermost dimension remains of UnknownSize because there are
9734/// no strides that would help identifying the size of the last dimension: when
9735/// the array has been statically allocated, one could compute the size of that
9736/// dimension by dividing the overall size of the array by the size of the known
9737/// dimensions: %m * %o * 8.
9738///
9739/// Finally delinearize provides the access functions for the array reference
9740/// that does correspond to A[i][j][k] of the above C testcase:
9741///
9742/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9743///
9744/// The testcases are checking the output of a function pass:
9745/// DelinearizationPass that walks through all loads and stores of a function
9746/// asking for the SCEV of the memory access with respect to all enclosing
9747/// loops, calling SCEV->delinearize on that and printing the results.
9748
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009749void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009750 SmallVectorImpl<const SCEV *> &Subscripts,
9751 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009752 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009753 // First step: collect parametric terms.
9754 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009755 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009756
Sebastian Popb1a548f2014-05-12 19:01:53 +00009757 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009758 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009759
Sebastian Pop448712b2014-05-07 18:01:20 +00009760 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009761 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009762
Sebastian Popb1a548f2014-05-12 19:01:53 +00009763 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009764 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009765
Sebastian Pop448712b2014-05-07 18:01:20 +00009766 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009767 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009768
Sebastian Pop28e6b972014-05-27 22:41:51 +00009769 if (Subscripts.empty())
9770 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009771
Sebastian Pop448712b2014-05-07 18:01:20 +00009772 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009773 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009774 dbgs() << "ArrayDecl[UnknownSize]";
9775 for (const SCEV *S : Sizes)
9776 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009777
Sebastian Pop444621a2014-05-09 22:45:02 +00009778 dbgs() << "\nArrayRef";
9779 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009780 dbgs() << "[" << *S << "]";
9781 dbgs() << "\n";
9782 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009783}
Chris Lattnerd934c702004-04-02 20:23:17 +00009784
9785//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009786// SCEVCallbackVH Class Implementation
9787//===----------------------------------------------------------------------===//
9788
Dan Gohmand33a0902009-05-19 19:22:47 +00009789void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009790 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009791 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9792 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009793 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009794 // this now dangles!
9795}
9796
Dan Gohman7a066722010-07-28 01:09:07 +00009797void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009798 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009799
Dan Gohman48f82222009-05-04 22:30:44 +00009800 // Forget all the expressions associated with users of the old value,
9801 // so that future queries will recompute the expressions using the new
9802 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009803 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009804 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009805 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009806 while (!Worklist.empty()) {
9807 User *U = Worklist.pop_back_val();
9808 // Deleting the Old value will cause this to dangle. Postpone
9809 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009810 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009811 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009812 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009813 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009814 if (PHINode *PN = dyn_cast<PHINode>(U))
9815 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009816 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009817 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009818 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009819 // Delete the Old value.
9820 if (PHINode *PN = dyn_cast<PHINode>(Old))
9821 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009822 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009823 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009824}
9825
Dan Gohmand33a0902009-05-19 19:22:47 +00009826ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009827 : CallbackVH(V), SE(se) {}
9828
9829//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009830// ScalarEvolution Class Implementation
9831//===----------------------------------------------------------------------===//
9832
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009833ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009834 AssumptionCache &AC, DominatorTree &DT,
9835 LoopInfo &LI)
9836 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009837 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009838 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9839 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009840 FirstUnknown(nullptr) {
9841
9842 // To use guards for proving predicates, we need to scan every instruction in
9843 // relevant basic blocks, and not just terminators. Doing this is a waste of
9844 // time if the IR does not actually contain any calls to
9845 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9846 //
9847 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9848 // to _add_ guards to the module when there weren't any before, and wants
9849 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9850 // efficient in lieu of being smart in that rather obscure case.
9851
9852 auto *GuardDecl = F.getParent()->getFunction(
9853 Intrinsic::getName(Intrinsic::experimental_guard));
9854 HasGuards = GuardDecl && !GuardDecl->use_empty();
9855}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009856
9857ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009858 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009859 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009860 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009861 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009862 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00009863 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009864 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009865 PredicatedBackedgeTakenCounts(
9866 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009867 ConstantEvolutionLoopExitValue(
9868 std::move(Arg.ConstantEvolutionLoopExitValue)),
9869 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9870 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009871 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009872 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009873 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9874 SignedRanges(std::move(Arg.SignedRanges)),
9875 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009876 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009877 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9878 FirstUnknown(Arg.FirstUnknown) {
9879 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009880}
9881
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009882ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009883 // Iterate through all the SCEVUnknown instances and call their
9884 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009885 for (SCEVUnknown *U = FirstUnknown; U;) {
9886 SCEVUnknown *Tmp = U;
9887 U = U->Next;
9888 Tmp->~SCEVUnknown();
9889 }
Craig Topper9f008862014-04-15 04:59:12 +00009890 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009891
Wei Mia49559b2016-02-04 01:27:38 +00009892 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009893 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009894 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009895
9896 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9897 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009898 for (auto &BTCI : BackedgeTakenCounts)
9899 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009900 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9901 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009902
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009903 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009904 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009905 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009906}
9907
Dan Gohmanc8e23622009-04-21 23:15:49 +00009908bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009909 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009910}
9911
Dan Gohmanc8e23622009-04-21 23:15:49 +00009912static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009913 const Loop *L) {
9914 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009915 for (Loop *I : *L)
9916 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009917
Dan Gohmanbc694912010-01-09 18:17:45 +00009918 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009919 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009920 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009921
Dan Gohmancb0efec2009-12-18 01:14:11 +00009922 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009923 L->getExitBlocks(ExitBlocks);
9924 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009925 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009926
Dan Gohman0bddac12009-02-24 18:55:53 +00009927 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9928 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009929 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009930 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009931 }
9932
Dan Gohmanbc694912010-01-09 18:17:45 +00009933 OS << "\n"
9934 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009935 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009936 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009937
9938 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9939 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +00009940 if (SE->isBackedgeTakenCountMaxOrZero(L))
9941 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +00009942 } else {
9943 OS << "Unpredictable max backedge-taken count. ";
9944 }
9945
Silviu Baranga6f444df2016-04-08 14:29:09 +00009946 OS << "\n"
9947 "Loop ";
9948 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9949 OS << ": ";
9950
9951 SCEVUnionPredicate Pred;
9952 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9953 if (!isa<SCEVCouldNotCompute>(PBT)) {
9954 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9955 OS << " Predicates:\n";
9956 Pred.print(OS, 4);
9957 } else {
9958 OS << "Unpredictable predicated backedge-taken count. ";
9959 }
Dan Gohman69942932009-06-24 00:33:16 +00009960 OS << "\n";
Eli Friedmanb1578d32017-03-20 20:25:46 +00009961
9962 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9963 OS << "Loop ";
9964 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9965 OS << ": ";
9966 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
9967 }
Chris Lattnerd934c702004-04-02 20:23:17 +00009968}
9969
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009970static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9971 switch (LD) {
9972 case ScalarEvolution::LoopVariant:
9973 return "Variant";
9974 case ScalarEvolution::LoopInvariant:
9975 return "Invariant";
9976 case ScalarEvolution::LoopComputable:
9977 return "Computable";
9978 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009979 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009980}
9981
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009982void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009983 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009984 // out SCEV values of all instructions that are interesting. Doing
9985 // this potentially causes it to create new SCEV objects though,
9986 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009987 // observable from outside the class though, so casting away the
9988 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009989 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009990
Dan Gohmanbc694912010-01-09 18:17:45 +00009991 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009992 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009993 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009994 for (Instruction &I : instructions(F))
9995 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9996 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009997 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009998 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009999 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +000010000 if (!isa<SCEVCouldNotCompute>(SV)) {
10001 OS << " U: ";
10002 SE.getUnsignedRange(SV).print(OS);
10003 OS << " S: ";
10004 SE.getSignedRange(SV).print(OS);
10005 }
Misha Brukman01808ca2005-04-21 21:13:18 +000010006
Sanjoy Dasd9f6d332015-10-18 00:29:16 +000010007 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +000010008
Dan Gohmanaf752342009-07-07 17:06:11 +000010009 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +000010010 if (AtUse != SV) {
10011 OS << " --> ";
10012 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +000010013 if (!isa<SCEVCouldNotCompute>(AtUse)) {
10014 OS << " U: ";
10015 SE.getUnsignedRange(AtUse).print(OS);
10016 OS << " S: ";
10017 SE.getSignedRange(AtUse).print(OS);
10018 }
Dan Gohmanb9063a82009-06-19 17:49:54 +000010019 }
10020
10021 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +000010022 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +000010023 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +000010024 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +000010025 OS << "<<Unknown>>";
10026 } else {
10027 OS << *ExitValue;
10028 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010029
10030 bool First = true;
10031 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10032 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +000010033 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010034 First = false;
10035 } else {
10036 OS << ", ";
10037 }
10038
Sanjoy Das013a4ac2016-05-03 17:49:57 +000010039 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10040 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010041 }
10042
Sanjoy Das013a4ac2016-05-03 17:49:57 +000010043 for (auto *InnerL : depth_first(L)) {
10044 if (InnerL == L)
10045 continue;
10046 if (First) {
10047 OS << "\t\t" "LoopDispositions: { ";
10048 First = false;
10049 } else {
10050 OS << ", ";
10051 }
10052
10053 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10054 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10055 }
10056
10057 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +000010058 }
10059
Chris Lattnerd934c702004-04-02 20:23:17 +000010060 OS << "\n";
10061 }
10062
Dan Gohmanbc694912010-01-09 18:17:45 +000010063 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010064 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +000010065 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +000010066 for (Loop *I : LI)
10067 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +000010068}
Dan Gohmane20f8242009-04-21 00:47:46 +000010069
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010070ScalarEvolution::LoopDisposition
10071ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010072 auto &Values = LoopDispositions[S];
10073 for (auto &V : Values) {
10074 if (V.getPointer() == L)
10075 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010076 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010077 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010078 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010079 auto &Values2 = LoopDispositions[S];
10080 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10081 if (V.getPointer() == L) {
10082 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010083 break;
10084 }
10085 }
10086 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010087}
10088
10089ScalarEvolution::LoopDisposition
10090ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +000010091 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +000010092 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010093 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010094 case scTruncate:
10095 case scZeroExtend:
10096 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010097 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +000010098 case scAddRecExpr: {
10099 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10100
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010101 // If L is the addrec's loop, it's computable.
10102 if (AR->getLoop() == L)
10103 return LoopComputable;
10104
Dan Gohmanafd6db92010-11-17 21:23:15 +000010105 // Add recurrences are never invariant in the function-body (null loop).
10106 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010107 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010108
10109 // This recurrence is variant w.r.t. L if L contains AR's loop.
10110 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010111 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010112
10113 // This recurrence is invariant w.r.t. L if AR's loop contains L.
10114 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010115 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010116
10117 // This recurrence is variant w.r.t. L if any of its operands
10118 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +000010119 for (auto *Op : AR->operands())
10120 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010121 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010122
10123 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010124 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010125 }
10126 case scAddExpr:
10127 case scMulExpr:
10128 case scUMaxExpr:
10129 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +000010130 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +000010131 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10132 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010133 if (D == LoopVariant)
10134 return LoopVariant;
10135 if (D == LoopComputable)
10136 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010137 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010138 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010139 }
10140 case scUDivExpr: {
10141 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010142 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10143 if (LD == LoopVariant)
10144 return LoopVariant;
10145 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10146 if (RD == LoopVariant)
10147 return LoopVariant;
10148 return (LD == LoopInvariant && RD == LoopInvariant) ?
10149 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010150 }
10151 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010152 // All non-instruction values are loop invariant. All instructions are loop
10153 // invariant if they are not contained in the specified loop.
10154 // Instructions are never considered invariant in the function body
10155 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +000010156 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010157 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10158 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010159 case scCouldNotCompute:
10160 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +000010161 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010162 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010163}
10164
10165bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10166 return getLoopDisposition(S, L) == LoopInvariant;
10167}
10168
10169bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10170 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010171}
Dan Gohman20d9ce22010-11-17 21:41:58 +000010172
Dan Gohman8ea83d82010-11-18 00:34:22 +000010173ScalarEvolution::BlockDisposition
10174ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010175 auto &Values = BlockDispositions[S];
10176 for (auto &V : Values) {
10177 if (V.getPointer() == BB)
10178 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010179 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010180 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010181 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010182 auto &Values2 = BlockDispositions[S];
10183 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10184 if (V.getPointer() == BB) {
10185 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010186 break;
10187 }
10188 }
10189 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010190}
10191
Dan Gohman8ea83d82010-11-18 00:34:22 +000010192ScalarEvolution::BlockDisposition
10193ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +000010194 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +000010195 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +000010196 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010197 case scTruncate:
10198 case scZeroExtend:
10199 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +000010200 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +000010201 case scAddRecExpr: {
10202 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +000010203 // to test for proper dominance too, because the instruction which
10204 // produces the addrec's value is a PHI, and a PHI effectively properly
10205 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +000010206 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010207 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010208 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +000010209
10210 // Fall through into SCEVNAryExpr handling.
10211 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010212 }
Dan Gohman20d9ce22010-11-17 21:41:58 +000010213 case scAddExpr:
10214 case scMulExpr:
10215 case scUMaxExpr:
10216 case scSMaxExpr: {
10217 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010218 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +000010219 for (const SCEV *NAryOp : NAry->operands()) {
10220 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010221 if (D == DoesNotDominateBlock)
10222 return DoesNotDominateBlock;
10223 if (D == DominatesBlock)
10224 Proper = false;
10225 }
10226 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010227 }
10228 case scUDivExpr: {
10229 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010230 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10231 BlockDisposition LD = getBlockDisposition(LHS, BB);
10232 if (LD == DoesNotDominateBlock)
10233 return DoesNotDominateBlock;
10234 BlockDisposition RD = getBlockDisposition(RHS, BB);
10235 if (RD == DoesNotDominateBlock)
10236 return DoesNotDominateBlock;
10237 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10238 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010239 }
10240 case scUnknown:
10241 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +000010242 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10243 if (I->getParent() == BB)
10244 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010245 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010246 return ProperlyDominatesBlock;
10247 return DoesNotDominateBlock;
10248 }
10249 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010250 case scCouldNotCompute:
10251 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +000010252 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010253 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +000010254}
10255
10256bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10257 return getBlockDisposition(S, BB) >= DominatesBlock;
10258}
10259
10260bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10261 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010262}
Dan Gohman534749b2010-11-17 22:27:42 +000010263
10264bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +000010265 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +000010266}
Dan Gohman7e6b3932010-11-17 23:28:48 +000010267
10268void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10269 ValuesAtScopes.erase(S);
10270 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010271 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010272 UnsignedRanges.erase(S);
10273 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +000010274 ExprValueMap.erase(S);
10275 HasRecMap.erase(S);
Igor Laevskyc11c1ed2017-02-14 15:53:12 +000010276 MinTrailingZerosCache.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +000010277
Silviu Baranga6f444df2016-04-08 14:29:09 +000010278 auto RemoveSCEVFromBackedgeMap =
10279 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10280 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10281 BackedgeTakenInfo &BEInfo = I->second;
10282 if (BEInfo.hasOperand(S, this)) {
10283 BEInfo.clear();
10284 Map.erase(I++);
10285 } else
10286 ++I;
10287 }
10288 };
10289
10290 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10291 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010292}
Benjamin Kramer214935e2012-10-26 17:31:32 +000010293
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010294void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010295 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010296 ScalarEvolution SE2(F, TLI, AC, DT, LI);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010297
Sanjoy Das148e49f2017-04-23 23:04:45 +000010298 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
Benjamin Kramer214935e2012-10-26 17:31:32 +000010299
Sanjoy Das148e49f2017-04-23 23:04:45 +000010300 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10301 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10302 const SCEV *visitConstant(const SCEVConstant *Constant) {
10303 return SE.getConstant(Constant->getAPInt());
10304 }
10305 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10306 return SE.getUnknown(Expr->getValue());
10307 }
Benjamin Kramer214935e2012-10-26 17:31:32 +000010308
Sanjoy Das148e49f2017-04-23 23:04:45 +000010309 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10310 return SE.getCouldNotCompute();
10311 }
10312 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10313 };
10314
10315 SCEVMapper SCM(SE2);
10316
10317 while (!LoopStack.empty()) {
10318 auto *L = LoopStack.pop_back_val();
10319 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10320
10321 auto *CurBECount = SCM.visit(
10322 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10323 auto *NewBECount = SE2.getBackedgeTakenCount(L);
10324
10325 if (CurBECount == SE2.getCouldNotCompute() ||
10326 NewBECount == SE2.getCouldNotCompute()) {
10327 // NB! This situation is legal, but is very suspicious -- whatever pass
10328 // change the loop to make a trip count go from could not compute to
10329 // computable or vice-versa *should have* invalidated SCEV. However, we
10330 // choose not to assert here (for now) since we don't want false
10331 // positives.
10332 continue;
10333 }
10334
10335 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10336 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10337 // not propagate undef aggressively). This means we can (and do) fail
10338 // verification in cases where a transform makes the trip count of a loop
10339 // go from "undef" to "undef+1" (say). The transform is fine, since in
10340 // both cases the loop iterates "undef" times, but SCEV thinks we
10341 // increased the trip count of the loop by 1 incorrectly.
10342 continue;
10343 }
10344
10345 if (SE.getTypeSizeInBits(CurBECount->getType()) >
10346 SE.getTypeSizeInBits(NewBECount->getType()))
10347 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10348 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10349 SE.getTypeSizeInBits(NewBECount->getType()))
10350 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10351
10352 auto *ConstantDelta =
10353 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10354
10355 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10356 dbgs() << "Trip Count Changed!\n";
10357 dbgs() << "Old: " << *CurBECount << "\n";
10358 dbgs() << "New: " << *NewBECount << "\n";
10359 dbgs() << "Delta: " << *ConstantDelta << "\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010360 std::abort();
10361 }
10362 }
Benjamin Kramer214935e2012-10-26 17:31:32 +000010363}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010364
Chandler Carruth082c1832017-01-09 07:44:34 +000010365bool ScalarEvolution::invalidate(
10366 Function &F, const PreservedAnalyses &PA,
10367 FunctionAnalysisManager::Invalidator &Inv) {
10368 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10369 // of its dependencies is invalidated.
10370 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10371 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10372 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10373 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10374 Inv.invalidate<LoopAnalysis>(F, PA);
10375}
10376
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010377AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010378
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010379ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010380 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010381 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010382 AM.getResult<AssumptionAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010383 AM.getResult<DominatorTreeAnalysis>(F),
10384 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010385}
10386
10387PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010388ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010389 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010390 return PreservedAnalyses::all();
10391}
10392
10393INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10394 "Scalar Evolution Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010395INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010396INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10397INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10398INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10399INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10400 "Scalar Evolution Analysis", false, true)
10401char ScalarEvolutionWrapperPass::ID = 0;
10402
10403ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10404 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10405}
10406
10407bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10408 SE.reset(new ScalarEvolution(
10409 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010410 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010411 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10412 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10413 return false;
10414}
10415
10416void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10417
10418void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10419 SE->print(OS);
10420}
10421
10422void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10423 if (!VerifySCEV)
10424 return;
10425
10426 SE->verify();
10427}
10428
10429void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10430 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010431 AU.addRequiredTransitive<AssumptionCacheTracker>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010432 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10433 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10434 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10435}
Silviu Barangae3c05342015-11-02 14:41:02 +000010436
10437const SCEVPredicate *
10438ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10439 const SCEVConstant *RHS) {
10440 FoldingSetNodeID ID;
10441 // Unique this node based on the arguments
10442 ID.AddInteger(SCEVPredicate::P_Equal);
10443 ID.AddPointer(LHS);
10444 ID.AddPointer(RHS);
10445 void *IP = nullptr;
10446 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10447 return S;
10448 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10449 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10450 UniquePreds.InsertNode(Eq, IP);
10451 return Eq;
10452}
10453
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010454const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10455 const SCEVAddRecExpr *AR,
10456 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10457 FoldingSetNodeID ID;
10458 // Unique this node based on the arguments
10459 ID.AddInteger(SCEVPredicate::P_Wrap);
10460 ID.AddPointer(AR);
10461 ID.AddInteger(AddedFlags);
10462 void *IP = nullptr;
10463 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10464 return S;
10465 auto *OF = new (SCEVAllocator)
10466 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10467 UniquePreds.InsertNode(OF, IP);
10468 return OF;
10469}
10470
Benjamin Kramer83709b12015-11-16 09:01:28 +000010471namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010472
Silviu Barangae3c05342015-11-02 14:41:02 +000010473class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10474public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010475 /// Rewrites \p S in the context of a loop L and the SCEV predication
10476 /// infrastructure.
10477 ///
10478 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10479 /// equivalences present in \p Pred.
10480 ///
10481 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10482 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010483 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010484 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10485 SCEVUnionPredicate *Pred) {
10486 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010487 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010488 }
10489
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010490 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010491 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10492 SCEVUnionPredicate *Pred)
10493 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010494
10495 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010496 if (Pred) {
10497 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10498 for (auto *Pred : ExprPreds)
10499 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10500 if (IPred->getLHS() == Expr)
10501 return IPred->getRHS();
10502 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010503
10504 return Expr;
10505 }
10506
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010507 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10508 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010509 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010510 if (AR && AR->getLoop() == L && AR->isAffine()) {
10511 // This couldn't be folded because the operand didn't have the nuw
10512 // flag. Add the nusw flag as an assumption that we could make.
10513 const SCEV *Step = AR->getStepRecurrence(SE);
10514 Type *Ty = Expr->getType();
10515 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10516 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10517 SE.getSignExtendExpr(Step, Ty), L,
10518 AR->getNoWrapFlags());
10519 }
10520 return SE.getZeroExtendExpr(Operand, Expr->getType());
10521 }
10522
10523 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10524 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010525 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010526 if (AR && AR->getLoop() == L && AR->isAffine()) {
10527 // This couldn't be folded because the operand didn't have the nsw
10528 // flag. Add the nssw flag as an assumption that we could make.
10529 const SCEV *Step = AR->getStepRecurrence(SE);
10530 Type *Ty = Expr->getType();
10531 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10532 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10533 SE.getSignExtendExpr(Step, Ty), L,
10534 AR->getNoWrapFlags());
10535 }
10536 return SE.getSignExtendExpr(Operand, Expr->getType());
10537 }
10538
Silviu Barangae3c05342015-11-02 14:41:02 +000010539private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010540 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10541 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10542 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010543 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010544 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010545 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010546 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010547 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010548 return true;
10549 }
10550
Sanjoy Dasf0022122016-09-28 17:14:58 +000010551 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10552 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010553 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010554};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010555} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010556
Sanjoy Das807d33d2016-02-20 01:44:10 +000010557const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010558 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010559 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010560}
10561
Sanjoy Dasf0022122016-09-28 17:14:58 +000010562const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10563 const SCEV *S, const Loop *L,
10564 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10565
10566 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10567 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010568 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10569
10570 if (!AddRec)
10571 return nullptr;
10572
10573 // Since the transformation was successful, we can now transfer the SCEV
10574 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010575 for (auto *P : TransformPreds)
10576 Preds.insert(P);
10577
Silviu Barangad68ed852016-03-23 15:29:30 +000010578 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010579}
10580
10581/// SCEV predicates
10582SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10583 SCEVPredicateKind Kind)
10584 : FastID(ID), Kind(Kind) {}
10585
10586SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10587 const SCEVUnknown *LHS,
10588 const SCEVConstant *RHS)
10589 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10590
10591bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010592 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010593
10594 if (!Op)
10595 return false;
10596
10597 return Op->LHS == LHS && Op->RHS == RHS;
10598}
10599
10600bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10601
10602const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10603
10604void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10605 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10606}
10607
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010608SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10609 const SCEVAddRecExpr *AR,
10610 IncrementWrapFlags Flags)
10611 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10612
10613const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10614
10615bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10616 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10617
10618 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10619}
10620
10621bool SCEVWrapPredicate::isAlwaysTrue() const {
10622 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10623 IncrementWrapFlags IFlags = Flags;
10624
10625 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10626 IFlags = clearFlags(IFlags, IncrementNSSW);
10627
10628 return IFlags == IncrementAnyWrap;
10629}
10630
10631void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10632 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10633 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10634 OS << "<nusw>";
10635 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10636 OS << "<nssw>";
10637 OS << "\n";
10638}
10639
10640SCEVWrapPredicate::IncrementWrapFlags
10641SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10642 ScalarEvolution &SE) {
10643 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10644 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10645
10646 // We can safely transfer the NSW flag as NSSW.
10647 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10648 ImpliedFlags = IncrementNSSW;
10649
10650 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10651 // If the increment is positive, the SCEV NUW flag will also imply the
10652 // WrapPredicate NUSW flag.
10653 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10654 if (Step->getValue()->getValue().isNonNegative())
10655 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10656 }
10657
10658 return ImpliedFlags;
10659}
10660
Silviu Barangae3c05342015-11-02 14:41:02 +000010661/// Union predicates don't get cached so create a dummy set ID for it.
10662SCEVUnionPredicate::SCEVUnionPredicate()
10663 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10664
10665bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010666 return all_of(Preds,
10667 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010668}
10669
10670ArrayRef<const SCEVPredicate *>
10671SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10672 auto I = SCEVToPreds.find(Expr);
10673 if (I == SCEVToPreds.end())
10674 return ArrayRef<const SCEVPredicate *>();
10675 return I->second;
10676}
10677
10678bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010679 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010680 return all_of(Set->Preds,
10681 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010682
10683 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10684 if (ScevPredsIt == SCEVToPreds.end())
10685 return false;
10686 auto &SCEVPreds = ScevPredsIt->second;
10687
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010688 return any_of(SCEVPreds,
10689 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010690}
10691
10692const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10693
10694void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10695 for (auto Pred : Preds)
10696 Pred->print(OS, Depth);
10697}
10698
10699void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010700 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010701 for (auto Pred : Set->Preds)
10702 add(Pred);
10703 return;
10704 }
10705
10706 if (implies(N))
10707 return;
10708
10709 const SCEV *Key = N->getExpr();
10710 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10711 " associated expression!");
10712
10713 SCEVToPreds[Key].push_back(N);
10714 Preds.push_back(N);
10715}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010716
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010717PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10718 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010719 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010720
10721const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10722 const SCEV *Expr = SE.getSCEV(V);
10723 RewriteEntry &Entry = RewriteMap[Expr];
10724
10725 // If we already have an entry and the version matches, return it.
10726 if (Entry.second && Generation == Entry.first)
10727 return Entry.second;
10728
10729 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010730 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010731 if (Entry.second)
10732 Expr = Entry.second;
10733
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010734 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010735 Entry = {Generation, NewSCEV};
10736
10737 return NewSCEV;
10738}
10739
Silviu Baranga6f444df2016-04-08 14:29:09 +000010740const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10741 if (!BackedgeCount) {
10742 SCEVUnionPredicate BackedgePred;
10743 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10744 addPredicate(BackedgePred);
10745 }
10746 return BackedgeCount;
10747}
10748
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010749void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10750 if (Preds.implies(&Pred))
10751 return;
10752 Preds.add(&Pred);
10753 updateGeneration();
10754}
10755
10756const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10757 return Preds;
10758}
10759
10760void PredicatedScalarEvolution::updateGeneration() {
10761 // If the generation number wrapped recompute everything.
10762 if (++Generation == 0) {
10763 for (auto &II : RewriteMap) {
10764 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010765 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010766 }
10767 }
10768}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010769
10770void PredicatedScalarEvolution::setNoOverflow(
10771 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10772 const SCEV *Expr = getSCEV(V);
10773 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10774
10775 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10776
10777 // Clear the statically implied flags.
10778 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10779 addPredicate(*SE.getWrapPredicate(AR, Flags));
10780
10781 auto II = FlagsMap.insert({V, Flags});
10782 if (!II.second)
10783 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10784}
10785
10786bool PredicatedScalarEvolution::hasNoOverflow(
10787 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10788 const SCEV *Expr = getSCEV(V);
10789 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10790
10791 Flags = SCEVWrapPredicate::clearFlags(
10792 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10793
10794 auto II = FlagsMap.find(V);
10795
10796 if (II != FlagsMap.end())
10797 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10798
10799 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10800}
10801
Silviu Barangad68ed852016-03-23 15:29:30 +000010802const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010803 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010804 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10805 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010806
10807 if (!New)
10808 return nullptr;
10809
Sanjoy Dasf0022122016-09-28 17:14:58 +000010810 for (auto *P : NewPreds)
10811 Preds.add(P);
10812
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010813 updateGeneration();
10814 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10815 return New;
10816}
10817
Silviu Baranga6f444df2016-04-08 14:29:09 +000010818PredicatedScalarEvolution::PredicatedScalarEvolution(
10819 const PredicatedScalarEvolution &Init)
10820 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10821 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010822 for (const auto &I : Init.FlagsMap)
10823 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010824}
Silviu Barangab77365b2016-04-14 16:08:45 +000010825
10826void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10827 // For each block.
10828 for (auto *BB : L.getBlocks())
10829 for (auto &I : *BB) {
10830 if (!SE.isSCEVable(I.getType()))
10831 continue;
10832
10833 auto *Expr = SE.getSCEV(&I);
10834 auto II = RewriteMap.find(Expr);
10835
10836 if (II == RewriteMap.end())
10837 continue;
10838
10839 // Don't print things that are not interesting.
10840 if (II->second.second == Expr)
10841 continue;
10842
10843 OS.indent(Depth) << "[PSE]" << I << ":\n";
10844 OS.indent(Depth + 2) << *Expr << "\n";
10845 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10846 }
10847}